-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
55 lines (44 loc) · 1.24 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
const natural = require('javascript-natural-sort')
const { CompositeDisposable } = require('atom')
// internal
const getRanges = require('./get/ranges')
const sortJSON = require('./sort/json')
const sortLine = require('./sort/line')
const sortLines = require('./sort/lines')
const sortYAML = require('./sort/yaml')
// region subscriptions
const subscriptions = new CompositeDisposable()
const activate = () =>
subscriptions.add(
atom.commands.add('atom-workspace', {
'sorter:sort': () => sort(),
'sorter:natural-sort': () => sort(natural),
})
)
const deactivate = () => subscriptions.dispose()
// endregion
// region sort
const sort = sortingFunction => {
const editor = atom.workspace.getActiveTextEditor()
if (!editor) return null
return getRanges(editor).forEach(range =>
editor.setTextInBufferRange(
range,
(lines => {
try {
return sortJSON(lines, sortingFunction)
} catch (error) {
try {
return sortYAML(lines, sortingFunction)
} catch (error) {
return lines.length === 1
? sortLine(lines[0], sortingFunction)
: sortLines(lines, sortingFunction)
}
}
})(editor.getTextInBufferRange(range).split(/\r?\n/g))
)
)
}
// endregion
module.exports = { activate, deactivate }