-
Notifications
You must be signed in to change notification settings - Fork 11
/
extension.js
347 lines (308 loc) · 12.2 KB
/
extension.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
339
340
341
342
343
344
345
346
347
const ctagz = require('ctagz')
const lineReader = require('line-reader')
const path = require('path')
const Promise = require('bluebird')
const vscode = require('vscode')
const eachLine = Promise.promisify(lineReader.eachLine)
// Called when the plugin is first activated
function activate(context) {
console.log('ctagsx is live')
let disposable = vscode.commands.registerCommand('extension.findCTags', () => findCTagsInDocument(context))
context.subscriptions.push(disposable)
disposable = vscode.commands.registerCommand('extension.findCTagsPrompt', () => findCTagsFromPrompt(context))
context.subscriptions.push(disposable)
disposable = vscode.commands.registerCommand('extension.ctagsJumpBack', () => jumpBack(context))
context.subscriptions.push(disposable)
disposable = vscode.commands.registerCommand('extension.ctagsClearJumpStack', () => clearJumpStack(context))
context.subscriptions.push(disposable)
disposable = vscode.commands.registerCommand('extension.createTerminal', createTerminal)
context.subscriptions.push(disposable)
if (!vscode.workspace.getConfiguration('ctagsx').get('disableDefinitionProvider')) {
disposable = vscode.languages.registerDefinitionProvider({ pattern: '**/*' }, { provideDefinition })
context.subscriptions.push(disposable)
}
}
exports.activate = activate
// Called when the plugin is deactivated
function deactivate() {
console.log('ctagsx is tombstoned')
}
exports.deactivate = deactivate
function createTerminal() {
vscode.window.createTerminal().show()
}
function findCTagsFromPrompt(context) {
const options = {
'prompt': 'Enter a tag to search for'
}
// TODO: Provide completion (jtanx/ctagz#2)
return vscode.window.showInputBox(options).then(tag => {
if (!tag) {
return
}
return findCTags(context, tag)
})
}
function findCTagsInDocument(context) {
const editor = vscode.window.activeTextEditor
if (!editor) {
console.log('ctagsx: Cannot search - no active editor (file too large? https://github.com/Microsoft/vscode/issues/3147)')
return
}
const tag = getTag(editor)
if (!tag) {
return
}
return findCTags(context, tag)
}
function findCTags(context, tag) {
const editor = vscode.window.activeTextEditor
let searchPath = vscode.workspace.rootPath
if (editor && !editor.document.isUntitled && editor.document.uri.scheme === 'file') {
searchPath = editor.document.fileName
}
if (!searchPath) {
console.log('ctagsx: Could not get a path to search for tags file')
if (editor) {
console.log('ctagsx: Document is untitled? ', editor.document.isUntitled)
console.log('ctagsx: Document URI:', editor.document.uri.toString())
} else {
console.log('ctagsx: Active text editor is undefined')
}
console.log('ctagsx: Workspace root: ', vscode.workspace.rootPath)
return vscode.window.showWarningMessage(`ctagsx: No searchable path (no workspace folder open?)`)
}
ctagz.findCTagsBSearch(searchPath, tag)
.then(result => {
const options = result.results.map(tag => {
if (!path.isAbsolute(tag.file)) {
tag.file = path.join(path.dirname(result.tagsFile), tag.file)
}
tag.tagKind = tag.kind
tag.description = tag.tagKind || ''
tag.label = tag.file
tag.detail = tag.address.pattern || `Line ${tag.address.lineNumber}`
delete tag.kind // #20 -> avoid conflict with QuickPickItem
return tag
})
if (!options.length) {
if (!result.tagsFile) {
return vscode.window.showWarningMessage(`ctagsx: No tags file found`)
}
return vscode.window.showInformationMessage(`ctagsx: No tags found for ${tag}`)
} else if (options.length === 1) {
return revealCTags(context, editor, options[0])
} else {
return vscode.window.showQuickPick(options).then(opt => {
return revealCTags(context, editor, opt)
})
}
})
.catch(err => {
console.log(err.stack)
vscode.window.showErrorMessage(`ctagsx: Search failed: ${err}`)
})
}
function provideDefinition(document, position, canceller) {
if (document.isUntitled || document.uri.scheme !== 'file') {
console.log('ctagsx: Cannot provide definitions for untitled (unsaved) and/or non-local (non file://) documents')
return Promise.reject()
}
let tag, range
const editor = vscode.window.activeTextEditor
if (editor && editor.document == document && position.isEqual(editor.selection.active)) {
range = editor.selection
tag = editor.document.getText(editor.selection).trim()
}
if (!tag) {
range = document.getWordRangeAtPosition(position)
if (!range) {
console.log('ctagsx: Cannot provide definition without a valid tag (word range)')
return Promise.reject()
}
tag = document.getText(range)
if (!tag) {
console.log('ctagsx: Cannot provide definition with an empty tag')
return Promise.reject()
}
}
return ctagz.findCTagsBSearch(document.fileName, tag)
.then(result => {
const options = result.results.map(tag => {
if (!path.isAbsolute(tag.file)) {
tag.file = path.join(path.dirname(result.tagsFile), tag.file)
}
tag.tagKind = tag.kind
delete tag.kind
return tag
})
const results = []
return Promise.each(options, item => {
if (canceller.isCancellationRequested) {
return
}
return getLineNumber(item, document, range, canceller).then(sel => {
if (sel) {
results.push(new vscode.Location(vscode.Uri.file(item.file), sel.start))
}
})
}).then(() => {
return results
})
})
.catch(err => {
console.log(err.stack)
})
}
function jumpBack(context) {
const stack = context.workspaceState.get('CTAGSX_JUMP_STACK', [])
if (stack.length > 0) {
const position = stack.pop()
return context.workspaceState.update('CTAGSX_JUMP_STACK', stack).then(() => {
const uri = vscode.Uri.parse(position.uri)
const sel = new vscode.Selection(position.lineNumber, position.charPos, position.lineNumber, position.charPos)
return openAndReveal(context, vscode.window.activeTextEditor, uri, sel)
})
}
}
function clearJumpStack(context) {
return context.workspaceState.update('CTAGSX_JUMP_STACK', [])
}
function saveState(context, editor) {
if (!editor) {
// Can happen on manual entry with no editor open
return Promise.resolve()
}
const currentPosition = {
uri: editor.document.uri.toString(),
lineNumber: editor.selection.active.line,
charPos: editor.selection.active.character
}
const stack = context.workspaceState.get('CTAGSX_JUMP_STACK', [])
if (stack.length > 0) {
const lastPosition = stack[stack.length - 1]
// As long as the jump position was roughly the same line, don't save to the stack
if (lastPosition.uri === currentPosition.uri && lastPosition.lineNumber === currentPosition.lineNumber) {
return Promise.resolve()
} else if (stack.length > 50) {
stack.shift()
}
}
stack.push(currentPosition)
console.log('ctagsx: Jump stack:', stack)
return context.workspaceState.update('CTAGSX_JUMP_STACK', stack)
}
function getTag(editor) {
const tag = editor.document.getText(editor.selection).trim()
if (!tag) {
const range = editor.document.getWordRangeAtPosition(editor.selection.active)
if (range) {
return editor.document.getText(range)
}
}
return tag
}
function getLineNumberPattern(entry, canceller) {
let matchWhole = false
let pattern = entry.address.pattern
if (pattern.startsWith("^")) {
pattern = pattern.substring(1, pattern.length)
} else {
console.error(`ctagsx: Unsupported pattern ${pattern}`)
return Promise.resolve(0)
}
if (pattern.endsWith("$")) {
pattern = pattern.substring(0, pattern.length - 1)
matchWhole = true
}
let lineNumber = 0
let charPos = 0
let found
return eachLine(entry.file, line => {
lineNumber += 1
if ((matchWhole && line === pattern) || line.startsWith(pattern)) {
found = true
charPos = Math.max(line.indexOf(entry.name), 0)
console.log(`ctagsx: Found '${pattern}' at ${lineNumber}:${charPos}`)
return false
} else if (canceller && canceller.isCancellationRequested) {
console.log('ctagsx: Cancelled pattern searching')
return false
}
})
.then(() => {
if (found) {
return new vscode.Selection(lineNumber - 1, charPos, lineNumber - 1, charPos)
}
})
}
/**
* Attempts to infer the line number/character position for a file
* navigation based on the selection/range that triggered this search.
* @param {*} document Document that triggered this call
* @param {*} sel Selection or range that triggered this call
*/
function getFileLineNumber(document, sel) {
let pos = sel.end.translate(0, 1)
let range = document.getWordRangeAtPosition(pos)
if (range) {
let text = document.getText(range)
if (text.match(/[0-9]+/)) {
const lineNumber = Math.max(0, parseInt(text, 10) - 1)
let charPos = 0
pos = range.end.translate(0, 1)
range = document.getWordRangeAtPosition(pos)
if (range) {
text = document.getText(range)
if (text.match(/[0-9]+/)) {
charPos = Math.max(0, parseInt(text) - 1)
}
}
console.log(`ctagsx: Resolved file position to line ${lineNumber + 1}, char ${charPos + 1}`)
return Promise.resolve(new vscode.Selection(lineNumber, charPos, lineNumber, charPos))
}
}
return Promise.resolve()
}
/**
* Finds the line number (selection) within the document
* @param {*} entry The tag entry
* @param {*} document The document that triggered this call (optional)
* @param {*} sel The selection or range that triggered this call (optional)
* @param {*} canceller The cancellation token to cancel this action
* @returns A promise resolving to the selection within the document, or undefined if not found
*/
function getLineNumber(entry, document, sel, canceller) {
if (entry.address.lineNumber === 0) {
return getLineNumberPattern(entry, canceller)
} else if (entry.tagKind === 'F') {
if (document) {
return getFileLineNumber(document, sel)
}
}
const lineNumber = Math.max(0, entry.address.lineNumber - 1)
return Promise.resolve(new vscode.Selection(lineNumber, 0, lineNumber, 0))
}
function openAndReveal(context, editor, document, sel, doSaveState) {
if (doSaveState) {
return saveState(context, editor).then(() => openAndReveal(context, editor, document, sel))
}
return vscode.workspace.openTextDocument(document).then(doc => {
const showOptions = {
viewColumn: editor ? editor.viewColumn : vscode.ViewColumn.One,
preview: vscode.workspace.getConfiguration('ctagsx').get('openAsPreview'),
selection: sel
}
return vscode.window.showTextDocument(doc, showOptions)
})
}
function revealCTags(context, editor, entry) {
if (!entry) {
return
}
const document = editor ? editor.document : null
const triggeredSel = editor ? editor.selection : null
return getLineNumber(entry, document, triggeredSel).then(sel => {
return openAndReveal(context, editor, entry.file, sel, true)
})
}