/
utils.js
338 lines (289 loc) · 8.95 KB
/
utils.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
const Path = require('path')
const {Point, Range} = require('atom')
function splitPane (basePane, {split}) {
const paneWasActive = basePane.isActive()
if (!['right', 'down'].includes(split)) {
throw new Error('split must either of `right` or `down`')
}
const pane = split === 'right' ? basePane.splitRight() : basePane.splitDown()
// Atom doesn't allow 'split' pane without activating it.
// So re-activte basePane if it originally was active.
if (paneWasActive && !basePane.isActive()) basePane.activate()
return pane
}
function saveVmpPaneMaximizedState () {
const classList = atom.workspace.getElement().classList
if (!classList.contains('vim-mode-plus--pane-maximized')) {
return
}
let command
if (classList.contains('vim-mode-plus--pane-centered')) {
command = 'vim-mode-plus:maximize-pane'
} else {
command = 'vim-mode-plus:maximize-pane-without-center'
}
return () => {
atom.commands.dispatch(atom.workspace.getElement(), command)
}
}
function saveEditorState (editor) {
const oldScrollTop = editor.element.getScrollTop()
const oldCursorPosition = editor.getCursorBufferPosition()
const oldFoldStartRows = editor.displayLayer.foldsMarkerLayer.findMarkers({}).map(m => m.getStartPosition().row)
return ({activatePane = true} = {}) => {
const pane = paneForItem(editor)
if (!pane) return
if (activatePane) pane.activate()
pane.activateItem(editor)
if (!editor.getCursorBufferPosition().isEqual(oldCursorPosition)) {
editor.setCursorBufferPosition(oldCursorPosition)
}
for (const row of oldFoldStartRows.reverse()) {
if (!editor.isFoldedAtBufferRow(row)) {
editor.foldBufferRow(row)
}
}
editor.element.setScrollTop(oldScrollTop)
}
}
function requireFrom (pack, path) {
const packPath = atom.packages.resolvePackagePath(pack)
return require(`${packPath}/lib/${path}`)
}
function limitNumber (number, {max, min} = {}) {
if (max != null) number = Math.min(number, max)
if (min != null) number = Math.max(number, min)
return number
}
function getCurrentWord (editor) {
const selection = editor.getLastSelection()
if (!selection.isEmpty()) {
return selection.getText()
} else {
const point = selection.cursor.getBufferPosition()
selection.selectWord()
const text = selection.getText()
selection.cursor.setBufferPosition(point)
return text
}
}
function getActiveEditor () {
const item = atom.workspace
.getActivePaneContainer()
.getActivePane()
.getActiveItem()
if (atom.workspace.isTextEditor(item)) {
return item
}
}
function isActiveEditor (editor) {
return getActiveEditor() === editor
}
function getValidIndexForList (list, index) {
const length = list.length
if (length === 0) return -1
index = index % length
return index >= 0 ? index : length + index
}
// Respect goalColumn when moving cursor.
function setBufferRow (cursor, row) {
if (cursor.goalColumn == null) {
cursor.goalColumn = cursor.getBufferColumn()
}
cursor.setBufferPosition([row, cursor.goalColumn])
}
function isTextEditor (item) {
return atom.workspace.isTextEditor(item)
}
function paneForItem (item) {
return atom.workspace.paneForItem(item)
}
function getVisibleEditors () {
return atom.workspace
.getPanes()
.map(pane => pane.getActiveEditor())
.filter(editor => editor)
}
function getFirstCharacterPositionForBufferRow (editor, row) {
let point
editor.scanInBufferRange(/\S/, editor.bufferRangeForBufferRow(row), event => {
point = event.range.start
})
return point || new Point(row, 0)
}
function cloneRegExp (regExp) {
return new RegExp(regExp.source, regExp.flags)
}
// Utils used in Ui
// =========================
// item utils
// -------------------------
function getPrefixedTextLengthInfo (item) {
const lineHeaderLength = item._lineHeader ? item._lineHeader.length : 0
const truncationIndicatorLength = item._truncationIndicator ? item._truncationIndicator.length : 0
const totalLength = lineHeaderLength + truncationIndicatorLength
return {lineHeaderLength, truncationIndicatorLength, totalLength}
}
function compareByPoint (a, b) {
return a.point.compare(b.point)
}
function toMB (num) {
return Math.floor(num / (1024 * 1024))
}
const ignoreSubject = ['refresh']
function startMeasureMemory (subject, simple = true) {
if (ignoreSubject.includes(subject)) {
return () => {}
}
console.time(subject)
const v8 = require('v8')
const before = v8.getHeapStatistics()
console.time(subject)
return function () {
const after = v8.getHeapStatistics()
const diff = {}
for (let key of Object.keys(before)) {
diff[key] = after[key] - before[key]
}
console.info(`= ${subject}`)
if (simple) {
console.timeEnd(subject)
// console.log("diff.used_heap_size", toMB(diff.used_heap_size))
} else {
const table = [before, after, diff]
for (let result of table) {
for (const key in result) {
const value = result[key]
result[key] = toMB(value)
}
}
console.timeEnd(subject)
console.table(table)
}
}
}
// If editor was given, return first project path which editor's path is contained.
function getProjectPaths (editor) {
if (!editor) return atom.project.getPaths()
const filePath = editor.getPath()
if (filePath) {
const dir = atom.project.getDirectories().find(dir => dir.contains(filePath))
if (dir) return [dir.getPath()]
}
atom.notifications.addInfo('This file is not belonging to any project', {dismissable: true})
}
function suppressEvent (event) {
if (event != null) {
event.preventDefault()
event.stopPropagation()
}
}
function relativizeFilePath (filePath) {
const [projectPath, relativeFilePath] = atom.project.relativizePath(filePath)
return Path.join(Path.basename(projectPath), relativeFilePath)
}
function getMemoizedRelativizeFilePath () {
const cache = {}
return filePath => (cache[filePath] = cache[filePath] || relativizeFilePath(filePath))
}
function isExcludeFilter (text, negateByEndingExclamation) {
return (text.length > 1 && text.startsWith('!')) || (negateByEndingExclamation && text.endsWith('!'))
}
function scanItemsForBuffer (buffer, regex) {
const items = []
const filePath = buffer.getPath()
regex = cloneRegExp(regex)
const lines = buffer.getLines()
for (let row = 0; row < lines.length; row++) {
let match
const text = lines[row]
regex.lastIndex = 0
while ((match = regex.exec(text))) {
const point = new Point(row, match.index)
const range = new Range(point, [row, regex.lastIndex])
items.push({text, point, range, filePath})
// Avoid infinite loop in zero length match when regex is /^/
if (!match[0]) break
}
}
return items
}
function scanItemsForFilePath (filePath, regex) {
return atom.workspace.open(filePath, {activateItem: false}).then(editor => {
return scanItemsForBuffer(editor.buffer, regex)
})
}
function parsePromptLine (promptLineText, {useFirstQueryAsSearchTerm, negateByEndingExclamation}) {
let searchTerm, match
const includeFilters = []
const excludeFilters = []
const regex = /\S+/g
if (useFirstQueryAsSearchTerm) {
regex.exec(promptLineText)
searchTerm = new Range([0, 0], [0, regex.lastIndex])
}
while ((match = regex.exec(promptLineText))) {
const range = new Range([0, match.index], [0, regex.lastIndex])
const text = promptLineText.slice(match.index, regex.lastIndex)
if (isExcludeFilter(text, negateByEndingExclamation)) {
excludeFilters.push(range)
} else {
includeFilters.push(range)
}
}
return {searchTerm, includeFilters, excludeFilters}
}
function redrawPoint (editor, point, where) {
let coefficient
if (where === 'upper-middle') {
coefficient = 0.25
} else if (where === 'center') {
coefficient = 0.5
} else {
throw new Error(`where must be 'center' or 'upper-middle' but got ${where}`)
}
const {top} = editor.element.pixelPositionForBufferPosition(point)
const editorHeight = editor.element.getHeight()
const lineHeightInPixel = editor.getLineHeightInPixels()
const scrollTop = limitNumber(top - editorHeight * coefficient, {
min: top - editorHeight + lineHeightInPixel * 3,
max: top - lineHeightInPixel * 2
})
editor.element.setScrollTop(Math.round(scrollTop))
}
function getLocationForItem (item) {
return atom.workspace
.paneForItem(item)
.getContainer()
.getLocation()
}
module.exports = {
splitPane,
saveEditorState,
saveVmpPaneMaximizedState,
requireFrom,
limitNumber,
getCurrentWord,
getActiveEditor,
isActiveEditor,
getValidIndexForList,
setBufferRow,
isTextEditor,
paneForItem,
getVisibleEditors,
getFirstCharacterPositionForBufferRow,
cloneRegExp,
getPrefixedTextLengthInfo,
compareByPoint,
getProjectPaths,
suppressEvent,
startMeasureMemory,
relativizeFilePath,
getMemoizedRelativizeFilePath,
isExcludeFilter,
scanItemsForBuffer,
scanItemsForFilePath,
parsePromptLine,
redrawPoint,
getLocationForItem
}