-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
90 lines (79 loc) · 2.27 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
83
84
85
86
87
88
89
90
"use strict";
const {CompositeDisposable} = require("atom");
const {resolve, sep} = require("path");
const SCOPE_NAME = "source.file-magic";
module.exports = {
activated: false,
disposables: null,
pathPattern: null,
grammar: null,
activate(){
this.disposables = new CompositeDisposable(
atom.config.observe("language-file-magic.paths", paths => {
this.pathPattern = new RegExp(paths.map(path => {
path = resolve(path);
if(!/\*/.test(path)) path += sep + "*";
return path
.replace(/[\\/]+/g, sep)
.replace(/\*+/g, "\u274B")
.replace(/[/\\^$*+?{}[\]().|]/g, "\\$&")
.replace(/\u274B+/g, "[-.\\w]+") + "$";
}).join("|"), "i");
const {editors} = atom.textEditors;
if(this.activated && editors)
editors.forEach(ed => this.enchant(ed));
})
);
this.waitToLoad().then(grammar => {
this.grammar = grammar;
this.disposables.add(
atom.workspace.observeTextEditors(ed => this.enchant(ed))
);
});
atom.textEditors.editors.forEach(editor => {
const gram = editor.getGrammar();
if(gram && SCOPE_NAME === gram.scopeName)
editor.setTabLength(8);
});
this.activated = true;
},
deactivate(){
if(this.disposables)
this.disposables.dispose();
this.disposables = null;
this.grammar = null;
this.activated = false;
},
enchant(editor){
if(!editor) return;
const isMagical = this.pathPattern.test(editor.getPath());
const override = atom.textEditors.getGrammarOverride(editor);
if(isMagical && (!override || SCOPE_NAME === override)){
editor.setGrammar(this.grammar);
atom.textEditors.setGrammarOverride(editor, SCOPE_NAME);
}
else if(!isMagical && SCOPE_NAME === override)
atom.textEditors.clearGrammarOverride(editor);
},
waitToLoad(){
return new Promise(resolve => {
let grammar = atom.grammars.grammarForScopeName(SCOPE_NAME);
if(grammar)
resolve(grammar);
else{
const disposables = new CompositeDisposable();
const handler = () => {
grammar = atom.grammars.grammarForScopeName(SCOPE_NAME);
if(grammar){
disposables.dispose();
resolve(grammar);
}
};
disposables.add(
atom.packages.onDidActivatePackage(handler),
atom.packages.onDidActivateInitialPackages(handler)
);
}
});
},
};