This repository has been archived by the owner on Jan 23, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
82 lines (65 loc) · 1.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/** @babel */
import path from 'path';
import {CompositeDisposable} from 'atom';
import importFrom from 'import-from';
import {allowUnsafeNewFunction} from 'loophole';
const SUPPORTED_SCOPES = [
'source.js',
'source.jsx',
'source.js.jsx'
];
function init(editor, onSave) {
const fp = editor.getPath();
let esformatter;
allowUnsafeNewFunction(() => {
esformatter = importFrom.silent(path.dirname(fp), 'esformatter') || require('esformatter');
});
const selectedText = onSave ? null : editor.getSelectedText();
const text = selectedText || editor.getText();
let retText = '';
try {
retText = esformatter.format(text, esformatter.rc(fp));
} catch (err) {
console.error(err);
atom.notifications.addError('esformatter', {detail: err.message});
return;
}
const cursorPosition = editor.getCursorBufferPosition();
const line = atom.views.getView(editor).getFirstVisibleScreenRow() +
editor.getVerticalScrollMargin();
if (selectedText) {
editor.setTextInBufferRange(editor.getSelectedBufferRange(), retText);
} else {
editor.getBuffer().setTextViaDiff(retText);
}
editor.setCursorBufferPosition(cursorPosition);
if (editor.getScreenLineCount() > line) {
editor.scrollToScreenPosition([line, 0]);
}
}
export const config = {
formatOnSave: {
type: 'boolean',
default: false
}
};
export function deactivate() {
this.subscriptions.dispose();
}
export function activate() {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.workspace.observeTextEditors(editor => {
editor.getBuffer().onWillSave(() => {
const isJS = SUPPORTED_SCOPES.includes(editor.getGrammar().scopeName);
if (isJS && atom.config.get('esformatter.formatOnSave')) {
init(editor, true);
}
});
}));
this.subscriptions.add(atom.commands.add('atom-workspace', 'esformatter', () => {
const editor = atom.workspace.getActiveTextEditor();
if (editor) {
init(editor);
}
}));
}