/
index.ts
1102 lines (1043 loc) · 38.7 KB
/
index.ts
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { NeovimClient as Neovim } from '@chemzqm/neovim'
import binarySearch from 'binary-search'
import { CancellationTokenSource, CodeAction, CodeActionContext, CodeActionKind, Definition, Disposable, DocumentHighlight, DocumentHighlightKind, DocumentLink, DocumentSymbol, ExecuteCommandParams, ExecuteCommandRequest, Hover, Location, LocationLink, MarkedString, MarkupContent, Position, Range, SymbolInformation, SymbolKind, TextEdit, SelectionRange } from 'vscode-languageserver-protocol'
import Uri from 'vscode-uri'
import commandManager from '../commands'
import diagnosticManager from '../diagnostic/manager'
import events from '../events'
import extensions from '../extensions'
import languages from '../languages'
import Document from '../model/document'
import FloatFactory from '../model/floatFactory'
import { TextDocumentContentProvider } from '../provider'
import services from '../services'
import snippetManager from '../snippets/manager'
import { Documentation } from '../types'
import { disposeAll, wait } from '../util'
import { getSymbolKind } from '../util/convert'
import { positionInRange } from '../util/position'
import { byteSlice, indexOf, isWord } from '../util/string'
import workspace from '../workspace'
import CodeLensManager from './codelens'
import Colors from './colors'
import debounce = require('debounce')
import { equals } from '../util/object'
const logger = require('../util/logger')('Handler')
const pairs: Map<string, string> = new Map([
['<', '>'],
['>', '<'],
['{', '}'],
['[', ']'],
['(', ')'],
])
interface SymbolInfo {
filepath?: string
lnum: number
col: number
text: string
kind: string
level?: number
containerName?: string
selectionRange: Range
range?: Range
}
interface CommandItem {
id: string
title: string
}
interface SignaturePart {
text: string
type: 'Label' | 'MoreMsg' | 'Normal'
}
interface Preferences {
signatureMaxHeight: number
signaturePreferAbove: boolean
signatureHideOnChange: boolean
signatureHelpTarget: string
triggerSignatureHelp: boolean
formatOnType: boolean
hoverTarget: string
previewAutoClose: boolean
bracketEnterImprove: boolean
currentFunctionSymbolAutoUpdate: boolean
}
export default class Handler {
private preferences: Preferences
/*bufnr and srcId list*/
private highlightsMap: Map<number, number[]> = new Map()
private hoverPosition: [number, number, number]
private colors: Colors
private hoverFactory: FloatFactory
private signatureFactory: FloatFactory
private documentLines: string[] = []
private currentSymbols: SymbolInformation[]
private codeLensManager: CodeLensManager
private signatureTokenSource: CancellationTokenSource
private disposables: Disposable[] = []
constructor(private nvim: Neovim) {
this.getPreferences()
workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('coc.preferences')) {
this.getPreferences()
}
})
this.hoverFactory = new FloatFactory(nvim, workspace.env)
let { signaturePreferAbove, signatureMaxHeight } = this.preferences
this.signatureFactory = new FloatFactory(nvim, workspace.env, signaturePreferAbove, signatureMaxHeight)
events.on(['TextChangedI', 'TextChangedP'], async () => {
if (this.preferences.signatureHideOnChange) {
this.signatureFactory.close()
}
this.hoverFactory.close()
}, null, this.disposables)
let lastInsert: number
events.on('InsertCharPre', async () => {
lastInsert = Date.now()
}, null, this.disposables)
events.on('Enter', async bufnr => {
let { bracketEnterImprove } = this.preferences
await this.onCharacterType('\n', bufnr)
if (bracketEnterImprove) {
let line = (await nvim.call('line', '.') as number) - 1
let doc = workspace.getDocument(bufnr)
if (!doc) return
let pre = doc.getline(line - 1)
let curr = doc.getline(line)
let prevChar = pre[pre.length - 1]
if (prevChar && pairs.has(prevChar)) {
let nextChar = curr.trim()[0]
if (nextChar && pairs.get(prevChar) == nextChar) {
let edits: TextEdit[] = []
let opts = await workspace.getFormatOptions(doc.uri)
let space = opts.insertSpaces ? ' '.repeat(opts.tabSize) : '\t'
let preIndent = pre.match(/^\s*/)[0]
let currIndent = curr.match(/^\s*/)[0]
let newText = '\n' + preIndent + space
let pos: Position = Position.create(line - 1, pre.length)
// make sure indent of current line
if (preIndent != currIndent) {
edits.push({ range: Range.create(Position.create(line, 0), Position.create(line, currIndent.length)), newText: preIndent })
}
edits.push({ range: Range.create(pos, pos), newText })
await doc.applyEdits(nvim, edits)
await workspace.moveTo(Position.create(line, newText.length - 1))
}
}
}
}, null, this.disposables)
events.on('TextChangedI', async bufnr => {
let curr = Date.now()
if (!lastInsert || curr - lastInsert > 50) return
let doc = workspace.getDocument(bufnr)
if (!doc) return
let { triggerSignatureHelp, formatOnType } = this.preferences
if (!triggerSignatureHelp && !formatOnType) return
let pre = await this.getPreviousCharacter()
if (!pre || isWord(pre) || doc.paused) return
await this.onCharacterType(pre, bufnr)
if (languages.shouldTriggerSignatureHelp(doc.textDocument, pre)) {
if (workspace.isVim) await wait(50)
if (doc.dirty) {
doc.forceSync()
await wait(60)
}
if (lastInsert > curr) return
try {
await this.showSignatureHelp()
} catch (e) {
logger.error(`Error on signature help:`, e)
}
}
}, null, this.disposables)
events.on('InsertLeave', async bufnr => {
await wait(30)
if (workspace.insertMode) return
await this.onCharacterType('\n', bufnr, true)
}, null, this.disposables)
events.on('BufUnload', async bufnr => {
this.clearHighlight(bufnr)
}, null, this.disposables)
events.on('InsertEnter', async bufnr => {
this.clearHighlight(bufnr)
}, null, this.disposables)
events.on('CursorMoved', debounce((bufnr: number, cursor: [number, number]) => {
if (!this.preferences.previewAutoClose || !this.hoverPosition) return
if (this.preferences.hoverTarget == 'float') return
let arr = [bufnr, cursor[0], cursor[1]]
if (equals(arr, this.hoverPosition)) return
let doc = workspace.documents.find(doc => doc.uri.startsWith('coc://'))
if (doc && doc.bufnr != bufnr) {
nvim.command('pclose', true)
}
}, 100), null, this.disposables)
if (this.preferences.currentFunctionSymbolAutoUpdate) {
events.on('CursorHold', async () => {
await this.getCurrentFunctionSymbol()
}, null, this.disposables)
}
let provider: TextDocumentContentProvider = {
onDidChange: null,
provideTextDocumentContent: async () => {
nvim.pauseNotification()
nvim.command('setlocal conceallevel=2 nospell nofoldenable wrap', true)
nvim.command('setlocal bufhidden=wipe nobuflisted', true)
nvim.command('setfiletype markdown', true)
nvim.command(`exe "normal! z${this.documentLines.length}\\<cr>"`, true)
await nvim.resumeNotification()
return this.documentLines.join('\n')
}
}
this.disposables.push(workspace.registerTextDocumentContentProvider('coc', provider))
this.codeLensManager = new CodeLensManager(nvim)
this.colors = new Colors(nvim)
}
public async getCurrentFunctionSymbol(): Promise<string> {
let { position } = await workspace.getCurrentState()
const buffer = await this.nvim.buffer
let symbols = await this.getDocumentSymbols()
if (!symbols || symbols.length === 0) {
buffer.setVar('coc_current_function', '', true)
return ''
}
symbols = symbols.filter(s => [
'Class',
'Method',
'Function',
'Interface',
'Enum',
'Constructor',
].some(k => s.kind === k))
// If the current line is the same as the range.start of a symbol,
// `binarySearch` will return the index of that symbol is the array.
//
// If the current line number does not match the range.start of a symbol,
// `binarySearch` will return a negative index, which is 2 indices offset to the closest symbol.
let symbolPosition = binarySearch(symbols, position.line + 1, (e, n) => e.lnum - n)
if (symbolPosition < 0) {
symbolPosition *= -1
symbolPosition -= 2
}
const currentFunctionName = (() => {
const sym = symbols[symbolPosition]
const range = sym && (sym.range || sym.selectionRange)
if (!sym || !range || (position.line > range.end.line)) {
return ''
} else {
return sym.text
}
})()
buffer.setVar('coc_current_function', currentFunctionName, true)
return currentFunctionName
}
public async onHover(): Promise<void> {
if (this.hoverFactory.creating) return
let { document, position } = await workspace.getCurrentState()
let hovers = await languages.getHover(document, position)
if (hovers && hovers.length) {
await this.previewHover(hovers)
} else {
let target = this.preferences.hoverTarget
if (target == 'float') {
this.hoverFactory.close()
} else if (target == 'preview') {
this.nvim.command('pclose', true)
}
}
}
public async gotoDefinition(openCommand?: string): Promise<void> {
let { document, position } = await workspace.getCurrentState()
let definition = await languages.getDefinition(document, position)
if (definition && definition.length != 0) {
await this.handleLocations(definition, openCommand)
} else {
workspace.showMessage('Definition not found', 'warning')
}
}
public async gotoDeclaration(openCommand?: string): Promise<void> {
let { document, position } = await workspace.getCurrentState()
let definition = await languages.getDeclaration(document, position)
if (!definition) return workspace.showMessage('Declaration not found', 'warning')
await this.handleLocations(definition, openCommand)
}
public async gotoTypeDefinition(openCommand?: string): Promise<void> {
let { document, position } = await workspace.getCurrentState()
let definition = await languages.getTypeDefinition(document, position)
if (definition && definition.length != 0) {
await this.handleLocations(definition, openCommand)
} else {
workspace.showMessage('Type definition not found', 'warning')
}
}
public async gotoImplementation(openCommand?: string): Promise<void> {
let { document, position } = await workspace.getCurrentState()
let definition = await languages.getImplementation(document, position)
if (definition && definition.length != 0) {
await this.handleLocations(definition, openCommand)
} else {
workspace.showMessage('Implementation not found', 'warning')
}
}
public async gotoReferences(openCommand?: string): Promise<void> {
let { document, position } = await workspace.getCurrentState()
let locs = await languages.getReferences(document, { includeDeclaration: false }, position)
if (locs && locs.length) {
await this.handleLocations(locs, openCommand)
} else {
workspace.showMessage('References not found', 'warning')
}
}
public async getDocumentSymbols(): Promise<SymbolInfo[]> {
let document = await workspace.document
if (!document) return []
let symbols = await languages.getDocumentSymbol(document.textDocument)
if (!symbols) return null
if (symbols.length == 0) return []
let level = 0
let res: SymbolInfo[] = []
let pre = null
if (isDocumentSymbols(symbols)) {
symbols.sort(sortDocumentSymbols)
symbols.forEach(s => addDoucmentSymbol(res, s, level))
} else {
symbols.sort(sortSymbolInformations)
for (let sym of symbols) {
let { name, kind, location, containerName } = sym as SymbolInformation
if (!containerName || !pre) {
level = 0
} else {
if (pre.containerName == containerName) {
level = pre.level || 0
} else {
let container = getPreviousContainer(containerName, res)
level = container ? container.level + 1 : 0
}
}
let { start } = location.range
let o: SymbolInfo = {
col: start.character + 1,
lnum: start.line + 1,
text: name,
level,
kind: getSymbolKind(kind),
selectionRange: location.range,
containerName
}
res.push(o)
pre = o
}
}
return res
}
public async getWorkspaceSymbols(): Promise<SymbolInfo[]> {
let document = await workspace.document
if (!document) return
let cword = await this.nvim.call('expand', '<cword>')
let query = await this.nvim.call('input', ['Query:', cword])
let symbols = await languages.getWorkspaceSymbols(document.textDocument, query)
if (!symbols) {
workspace.showMessage('service does not support workspace symbols', 'error')
return []
}
this.currentSymbols = symbols
let res: SymbolInfo[] = []
for (let s of symbols) {
if (!this.validWorkspaceSymbol(s)) continue
let { name, kind, location } = s
let { start } = location.range
res.push({
filepath: Uri.parse(location.uri).fsPath,
col: start.character + 1,
lnum: start.line + 1,
text: name,
kind: getSymbolKind(kind),
selectionRange: location.range
})
}
return res
}
public async resolveWorkspaceSymbol(symbolIndex: number): Promise<SymbolInformation> {
if (!this.currentSymbols) return null
let symbol = this.currentSymbols[symbolIndex]
if (!symbol) return null
return await languages.resolveWorkspaceSymbol(symbol)
}
public async rename(): Promise<void> {
let { nvim } = this
let { document, position } = await workspace.getCurrentState()
if (!document) return
let res = await languages.prepareRename(document, position)
if (res === false) {
workspace.showMessage('Invalid position for rename', 'error')
return
}
let doc = workspace.getDocument(document.uri)
if (!doc) return
doc.forceSync()
let curname: string
if (res == null) {
let range = doc.getWordRangeAtPosition(position)
if (range) curname = document.getText(range)
} else {
if (Range.is(res)) {
let line = doc.getline(res.start.line)
curname = line.slice(res.start.character, res.end.character)
} else {
curname = res.placeholder
}
}
if (!curname) {
workspace.showMessage('Invalid position', 'warning')
return
}
let newName = await nvim.call('input', ['new name:', curname])
nvim.command('normal! :<C-u>', true)
if (!newName) {
workspace.showMessage('Empty word, canceled', 'warning')
return
}
let edit = await languages.provideRenameEdits(document, position, newName)
if (!edit) {
workspace.showMessage('Server return empty response for rename', 'warning')
return
}
await workspace.applyEdit(edit)
}
public async documentFormatting(): Promise<void> {
let document = await workspace.document
if (!document) return
let options = await workspace.getFormatOptions(document.uri)
let textEdits = await languages.provideDocumentFormattingEdits(document.textDocument, options)
if (!textEdits || textEdits.length == 0) return
await document.applyEdits(this.nvim, textEdits)
}
public async documentRangeFormatting(mode: string): Promise<number> {
let document = await workspace.document
if (!document) return -1
let range: Range
if (mode) {
range = await workspace.getSelectedRange(mode, document.textDocument)
if (!range) return -1
} else {
let lnum = await this.nvim.getVvar('lnum') as number
let count = await this.nvim.getVvar('count') as number
let mode = await this.nvim.call('mode')
// we can't handle
if (count == 0 || mode == 'i' || mode == 'R') return -1
range = Range.create(lnum - 1, 0, lnum - 1 + count, 0)
}
let options = await workspace.getFormatOptions(document.uri)
let textEdits = await languages.provideDocumentRangeFormattingEdits(document.textDocument, range, options)
if (!textEdits) return - 1
await document.applyEdits(this.nvim, textEdits)
return 0
}
public async runCommand(id?: string, ...args: any[]): Promise<void> {
if (id) {
await events.fire('Command', [id])
await commandManager.executeCommand(id, ...args)
} else {
this.nvim.command(`CocList commands`, true)
}
}
public async doCodeAction(mode: string | null, only?: CodeActionKind[]): Promise<void> {
let document = await workspace.document
if (!document) return
let range: Range
if (mode) {
range = await workspace.getSelectedRange(mode, document.textDocument)
} else {
let lnum = await this.nvim.call('line', ['.'])
range = {
start: { line: lnum - 1, character: 0 },
end: { line: lnum, character: 0 }
}
}
let diagnostics = diagnosticManager.getDiagnosticsInRange(document.textDocument, range)
let context: CodeActionContext = { diagnostics }
if (only) context.only = only
let codeActionsMap = await languages.getCodeActions(document.textDocument, range, context)
if (!codeActionsMap) return workspace.showMessage('No action available', 'warning')
let codeActions: CodeAction[] = []
for (let clientId of codeActionsMap.keys()) {
let actions = codeActionsMap.get(clientId)
for (let action of actions) {
(action as any).clientId = clientId
codeActions.push(action)
}
}
let idx = await workspace.showQuickpick(codeActions.map(o => o.title))
if (idx == -1) return
let action = codeActions[idx]
if (action) await this.applyCodeAction(action)
}
/**
* Get all quickfix actions of current buffer
*
* @public
* @returns {Promise<CodeAction[]>}
*/
public async getQuickfixActions(range?: Range): Promise<CodeAction[]> {
let document = await workspace.document
if (!document) return []
range = range || Range.create(0, 0, document.lineCount, 0)
let diagnostics = diagnosticManager.getDiagnosticsInRange(document.textDocument, range)
let context: CodeActionContext = { diagnostics, only: [CodeActionKind.QuickFix] }
let codeActionsMap = await languages.getCodeActions(document.textDocument, range, context, true)
if (!codeActionsMap) return []
let codeActions: CodeAction[] = []
for (let clientId of codeActionsMap.keys()) {
let actions = codeActionsMap.get(clientId)
for (let action of actions) {
if (action.kind !== CodeActionKind.QuickFix) continue
(action as any).clientId = clientId
codeActions.push(action)
}
}
return codeActions
}
public async doQuickfix(): Promise<void> {
let lnum = await this.nvim.call('line', ['.'])
let range: Range = {
start: { line: lnum - 1, character: 0 },
end: { line: lnum, character: 0 }
}
let actions = await this.getQuickfixActions(range)
if (!actions || actions.length == 0) {
return workspace.showMessage('No action available', 'warning')
}
await this.applyCodeAction(actions[0])
}
public async applyCodeAction(action: CodeAction): Promise<void> {
let { command, edit } = action
if (edit) await workspace.applyEdit(edit)
if (command) {
if (commandManager.has(command.command)) {
commandManager.execute(command)
} else {
let clientId = (action as any).clientId
let service = services.getService(clientId)
let params: ExecuteCommandParams = {
command: command.command,
arguments: command.arguments
}
if (service.client) {
let { client } = service
client
.sendRequest(ExecuteCommandRequest.type, params)
.then(undefined, error => {
workspace.showMessage(`Execute '${command.command} error: ${error}'`, 'error')
})
}
}
}
}
public async doCodeLensAction(): Promise<void> {
await this.codeLensManager.doAction()
}
public async fold(kind?: string): Promise<void> {
let document = await workspace.document
let win = await this.nvim.window
let foldmethod = await win.getOption('foldmethod')
if (foldmethod != 'manual') {
workspace.showMessage('foldmethod option should be manual!', 'error')
return
}
let ranges = await languages.provideFoldingRanges(document.textDocument, {})
if (!ranges || ranges.length == 0) {
workspace.showMessage('no range found', 'warning')
return
}
if (kind) {
ranges = ranges.filter(o => o.kind == kind)
}
if (ranges && ranges.length) {
await win.setOption('foldenable', true)
for (let range of ranges.reverse()) {
let { startLine, endLine } = range
let cmd = `${startLine + 1}, ${endLine + 1}fold`
this.nvim.command(cmd, true)
}
}
}
public async pickColor(): Promise<void> {
await this.colors.pickColor()
}
public async pickPresentation(): Promise<void> {
await this.colors.pickPresentation()
}
private async highlightDocument(document: Document): Promise<void> {
let position = await workspace.getCursorPosition()
let line = document.getline(position.line)
let ch = line[position.character]
if (!ch || !document.isWord(ch)) {
this.clearHighlight(document.bufnr)
return
}
let highlightNamespace = workspace.createNameSpace('coc-highlight')
if (this.colors.hasColorAtPostion(document.bufnr, position)) return
let highlights: DocumentHighlight[] = await languages.getDocumentHighLight(document.textDocument, position)
let newPosition = await workspace.getCursorPosition()
if (position.line != newPosition.line || position.character != newPosition.character) {
return
}
let ids = this.highlightsMap.get(document.bufnr)
if (workspace.isVim && workspace.bufnr != document.bufnr) return
this.nvim.pauseNotification()
if (ids && ids.length) {
this.clearHighlight(document.bufnr)
}
if (highlights && highlights.length) {
let groups: { [index: string]: Range[] } = {}
for (let hl of highlights) {
let hlGroup = hl.kind == DocumentHighlightKind.Text
? 'CocHighlightText'
: hl.kind == DocumentHighlightKind.Read ? 'CocHighlightRead' : 'CocHighlightWrite'
groups[hlGroup] = groups[hlGroup] || []
groups[hlGroup].push(hl.range)
}
let ids = []
for (let hlGroup of Object.keys(groups)) {
let ranges = groups[hlGroup]
let arr = document.highlightRanges(ranges, hlGroup, highlightNamespace)
ids.push(...arr)
this.highlightsMap.set(document.bufnr, ids)
}
}
this.nvim.resumeNotification().catch(_e => {
// noop
})
}
public async highlight(): Promise<void> {
let document = workspace.getDocument(workspace.bufnr)
if (!document) return
await this.highlightDocument(document)
}
public async links(): Promise<DocumentLink[]> {
let doc = await workspace.document
let links = await languages.getDocumentLinks(doc.textDocument)
links = links || []
let res: DocumentLink[] = []
for (let link of links) {
if (link.target) {
res.push(link)
} else {
link = await languages.resolveDocumentLink(link)
res.push(link)
}
}
return links
}
public async openLink(): Promise<boolean> {
let { document, position } = await workspace.getCurrentState()
let links = await languages.getDocumentLinks(document)
if (!links || links.length == 0) return false
for (let link of links) {
if (positionInRange(position, link.range)) {
let { target } = link
if (!target) {
link = await languages.resolveDocumentLink(link)
target = link.target
}
if (target) {
await workspace.openResource(target)
return true
}
return false
}
}
}
private validWorkspaceSymbol(symbol: SymbolInformation): boolean {
switch (symbol.kind) {
case SymbolKind.Namespace:
case SymbolKind.Class:
case SymbolKind.Module:
case SymbolKind.Method:
case SymbolKind.Package:
case SymbolKind.Interface:
case SymbolKind.Function:
case SymbolKind.Constant:
return true
default:
return false
}
}
public async getCommands(): Promise<CommandItem[]> {
let list = commandManager.commandList
let res: CommandItem[] = []
let document = await workspace.document
if (!document) return []
let { commands } = extensions
for (let key of Object.keys(commands)) {
res.push({
id: key,
title: commands[key] || ''
})
}
for (let o of list) {
if (commands[o.id] == null) {
res.push({ id: o.id, title: '' })
}
}
return res
}
private async onCharacterType(ch: string, bufnr: number, insertLeave = false): Promise<void> {
if (!ch || isWord(ch) || !this.preferences.formatOnType) return
if (snippetManager.getSession(bufnr) != null) return
let doc = workspace.getDocument(bufnr)
if (!doc || doc.paused) return
if (!languages.hasOnTypeProvider(ch, doc.textDocument)) return
let position = await workspace.getCursorPosition()
let origLine = doc.getline(position.line)
let { changedtick, dirty } = doc
if (dirty) {
doc.forceSync()
await wait(50)
}
let pos: Position = insertLeave ? { line: position.line + 1, character: 0 } : position
try {
let edits = await languages.provideDocumentOntTypeEdits(ch, doc.textDocument, pos)
// changed by other process
if (doc.changedtick != changedtick) return
if (insertLeave) {
edits = edits.filter(edit => {
return edit.range.start.line < position.line + 1
})
}
if (edits && edits.length) {
await doc.applyEdits(this.nvim, edits)
let newLine = doc.getline(position.line)
if (newLine.length > origLine.length) {
let character = position.character + (newLine.length - origLine.length)
await workspace.moveTo(Position.create(position.line, character))
}
}
} catch (e) {
if (!/timeout\s/.test(e.message)) {
console.error(`Error on formatOnType: ${e.message}`) // tslint:disable-line
}
}
}
public async showSignatureHelp(): Promise<void> {
if (this.signatureTokenSource) {
this.signatureTokenSource.cancel()
this.signatureTokenSource = null
}
let document = workspace.getDocument(workspace.bufnr)
if (!document) return
let position = await workspace.getCursorPosition()
let part = document.getline(position.line).slice(0, position.character)
if (/\)\s*$/.test(part)) return
let idx = Math.max(part.lastIndexOf(','), part.lastIndexOf('('))
if (idx != -1) position.character = idx + 1
let tokenSource = this.signatureTokenSource = new CancellationTokenSource()
let token = tokenSource.token
let timer = setTimeout(() => {
if (!token.isCancellationRequested) {
tokenSource.cancel()
}
}, 3000)
let signatureHelp = await languages.getSignatureHelp(document.textDocument, position, token)
clearTimeout(timer)
if (token.isCancellationRequested || !signatureHelp) {
this.signatureFactory.close()
return
}
let { activeParameter, activeSignature, signatures } = signatureHelp
if (activeSignature) {
// make active first
let [active] = signatures.splice(activeSignature, 1)
if (active) signatures.unshift(active)
}
if (this.preferences.signatureHelpTarget == 'float') {
let paramDoc: string | MarkupContent = null
let docs: Documentation[] = signatures.reduce((p: Documentation[], c, idx) => {
let activeIndexes: [number, number] = null
if (idx == 0 && activeParameter != null) {
let nameIndex = c.label.indexOf('(')
let active = c.parameters[activeParameter]
if (active) {
let after = c.label.slice(nameIndex == -1 ? 0 : nameIndex)
paramDoc = active.documentation
if (typeof active.label === 'string') {
let startIndex = activeParameter == 0 ? 0 : indexOf(after, ',', activeParameter)
startIndex = startIndex == -1 ? 0 : startIndex
let str = after.slice(startIndex)
let ms = str.match(new RegExp('\\b' + active.label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b'))
let index = ms ? ms.index : str.indexOf(active.label)
if (index != -1) {
activeIndexes = [
index + startIndex + nameIndex,
index + startIndex + active.label.length + nameIndex
]
}
} else {
activeIndexes = active.label
}
}
}
p.push({
content: c.label,
filetype: document.filetype,
active: activeIndexes
})
if (paramDoc) {
let content = typeof paramDoc === 'string' ? paramDoc : paramDoc.value
if (content.trim().length) {
p.push({
content,
filetype: MarkupContent.is(c.documentation) ? 'markdown' : 'txt'
})
}
}
if (idx == 0 && c.documentation) {
let { documentation } = c
let content = typeof documentation === 'string' ? documentation : documentation.value
if (content.trim().length) {
p.push({
content,
filetype: MarkupContent.is(c.documentation) ? 'markdown' : 'txt'
})
}
}
return p
}, [])
await this.signatureFactory.create(docs, true)
// show float
} else {
let columns = workspace.env.columns
signatures = signatures.slice(0, workspace.env.cmdheight)
let signatureList: SignaturePart[][] = []
for (let signature of signatures) {
let parts: SignaturePart[] = []
let { label } = signature
label = label.replace(/\n/g, ' ')
if (label.length >= columns - 16) {
label = label.slice(0, columns - 16) + '...'
}
let nameIndex = label.indexOf('(')
if (nameIndex == -1) {
parts = [{ text: label, type: 'Normal' }]
} else {
parts.push({
text: label.slice(0, nameIndex),
type: 'Label'
})
let after = label.slice(nameIndex)
if (signatureList.length == 0 && activeParameter != null) {
let active = signature.parameters[activeParameter]
if (active) {
let start: number
let end: number
if (typeof active.label === 'string') {
let startIndex = activeParameter == 0 ? 0 : indexOf(after, ',', activeParameter)
startIndex = startIndex == -1 ? 0 : startIndex
let str = after.slice(startIndex)
let ms = str.match(new RegExp('\\b' + active.label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b'))
let idx = ms ? ms.index : str.indexOf(active.label)
if (idx == -1) {
parts.push({ text: after, type: 'Normal' })
continue
}
start = idx + startIndex
end = idx + startIndex + active.label.length
} else {
[start, end] = active.label
start = start - nameIndex
end = end - nameIndex
}
parts.push({ text: after.slice(0, start), type: 'Normal' })
parts.push({ text: after.slice(start, end), type: 'MoreMsg' })
parts.push({ text: after.slice(end), type: 'Normal' })
}
} else {
parts.push({
text: after,
type: 'Normal'
})
}
}
signatureList.push(parts)
}
this.nvim.callTimer('coc#util#echo_signatures', [signatureList], true)
}
}
public async handleLocations(definition: Definition | LocationLink[], openCommand?: string): Promise<void> {
if (!definition) return
if (Array.isArray(definition)) {
let len = definition.length
if (len == 0) return
if (len == 1) {
let location = definition[0] as Location
if (LocationLink.is(definition[0])) {
let link = definition[0] as LocationLink
location = Location.create(link.targetUri, link.targetRange)
}
let { uri, range } = location
await workspace.jumpTo(uri, range.start, openCommand)
} else {
await workspace.showLocations(definition as Location[])
}
} else {
let { uri, range } = definition as Location
await workspace.jumpTo(uri, range.start, openCommand)
}
}
public async getSelectionRanges(): Promise<SelectionRange[] | null> {
let { document, position } = await workspace.getCurrentState()
let selectionRanges: SelectionRange[][] = await languages.getSelectionRanges(document, [position])
if (selectionRanges && selectionRanges.length) return selectionRanges[0]
return null
}
private async previewHover(hovers: Hover[]): Promise<void> {
let lines: string[] = []
let target = this.preferences.hoverTarget
let i = 0
let docs: Documentation[] = []
for (let hover of hovers) {
let { contents } = hover
if (i > 0) lines.push('---')
if (Array.isArray(contents)) {
for (let item of contents) {
if (typeof item === 'string') {
if (item.trim().length) {
lines.push(...item.split('\n'))
docs.push({ content: item, filetype: 'markdown' })
}
} else {
let content = item.value.trim()
if (target == 'preview') {
content = '``` ' + item.language + '\n' + content + '\n```'
}
lines.push(...content.trim().split('\n'))
docs.push({ filetype: item.language, content: item.value })
}
}
} else if (typeof contents == 'string') {
lines.push(...contents.split('\n'))
docs.push({ content: contents, filetype: 'markdown' })
} else if (MarkedString.is(contents)) { // tslint:disable-line
let content = contents.value.trim()
if (target == 'preview') {
content = '``` ' + contents.language + '\n' + content + '\n```'
}
lines.push(...content.split('\n'))
docs.push({ filetype: contents.language, content: contents.value })
} else if (MarkupContent.is(contents)) {
lines.push(...contents.value.split('\n'))
docs.push({ filetype: contents.kind == 'markdown' ? 'markdown' : 'txt', content: contents.value })
}
i++
}
if (target == 'echo') {
await this.nvim.call('coc#util#echo_hover', lines.join('\n').trim())
} else if (target == 'float') {
diagnosticManager.hideFloat()
await this.hoverFactory.create(docs)
} else {
this.documentLines = lines
let arr = await this.nvim.call('getcurpos') as number[]
this.hoverPosition = [workspace.bufnr, arr[1], arr[2]]
await this.nvim.command(`pedit coc://document`)
}
}
private clearHighlight(bufnr: number): void {
let doc = workspace.getDocument(bufnr)
let ids = this.highlightsMap.get(bufnr)
if (ids && ids.length) {
this.highlightsMap.delete(bufnr)
if (doc) doc.clearMatchIds(ids)
}
}