coc.vim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. scriptencoding utf-8
  2. if exists('g:did_coc_loaded') || v:version < 800
  3. finish
  4. endif
  5. function! s:checkVersion() abort
  6. let l:unsupported = 0
  7. if get(g:, 'coc_disable_startup_warning', 0) != 1
  8. if has('nvim')
  9. let l:unsupported = !has('nvim-0.4.0')
  10. else
  11. let l:unsupported = !has('patch-8.1.1719')
  12. endif
  13. if l:unsupported == 1
  14. echohl Error
  15. echom "coc.nvim requires at least Vim 8.1.1719 or Neovim 0.4.0, but you're using an older version."
  16. echom "Please upgrade your (neo)vim."
  17. echom "You can add this to your vimrc to avoid this message:"
  18. echom " let g:coc_disable_startup_warning = 1"
  19. echom "Note that some features may error out or behave incorrectly."
  20. echom "Please do not report bugs unless you're using at least Vim 8.1.1719 or Neovim 0.4.0."
  21. echohl None
  22. sleep 2
  23. else
  24. if !has('nvim-0.5.0') && !has('patch-8.2.0750')
  25. echohl WarningMsg
  26. echom "coc.nvim works best on vim >= 8.2.0750 and neovim >= 0.5.0, consider upgrade your vim."
  27. echom "You can add this to your vimrc to avoid this message:"
  28. echom " let g:coc_disable_startup_warning = 1"
  29. echom "Note that some features may behave incorrectly."
  30. echohl None
  31. sleep 2
  32. endif
  33. endif
  34. endif
  35. endfunction
  36. call s:checkVersion()
  37. let g:did_coc_loaded = 1
  38. let g:coc_service_initialized = 0
  39. let s:is_win = has('win32') || has('win64')
  40. let s:root = expand('<sfile>:h:h')
  41. let s:is_vim = !has('nvim')
  42. let s:is_gvim = s:is_vim && has("gui_running")
  43. if get(g:, 'coc_start_at_startup', 1) && !s:is_gvim
  44. call coc#rpc#start_server()
  45. endif
  46. function! CocTagFunc(pattern, flags, info) abort
  47. if a:flags !=# 'c'
  48. " use standard tag search
  49. return v:null
  50. endif
  51. return coc#rpc#request('getTagList', [])
  52. endfunction
  53. function! CocPopupCallback(bufnr, arglist) abort
  54. if len(a:arglist) == 2
  55. if a:arglist[0] == 'confirm'
  56. call coc#rpc#notify('PromptInsert', [a:arglist[1], a:bufnr])
  57. elseif a:arglist[0] == 'exit'
  58. execute 'silent! bd! '.a:bufnr
  59. "call coc#rpc#notify('PromptUpdate', [a:arglist[1]])
  60. elseif a:arglist[0] == 'change'
  61. let text = a:arglist[1]
  62. let current = getbufvar(a:bufnr, 'current', '')
  63. if text !=# current
  64. call setbufvar(a:bufnr, 'current', text)
  65. let cursor = term_getcursor(a:bufnr)
  66. let info = {
  67. \ 'lnum': cursor[0],
  68. \ 'col': cursor[1],
  69. \ 'line': text,
  70. \ 'changedtick': 0
  71. \ }
  72. call coc#rpc#notify('CocAutocmd', ['TextChangedI', a:bufnr, info])
  73. endif
  74. elseif a:arglist[0] == 'send'
  75. let key = a:arglist[1]
  76. let escaped = strcharpart(key, 1, strchars(key) - 2)
  77. call coc#rpc#notify('PromptKeyPress', [a:bufnr, escaped])
  78. endif
  79. endif
  80. endfunction
  81. function! CocAction(name, ...) abort
  82. if !get(g:, 'coc_service_initialized', 0)
  83. throw 'coc.nvim not ready when invoke CocAction "'.a:name.'"'
  84. endif
  85. return coc#rpc#request(a:name, a:000)
  86. endfunction
  87. function! CocHasProvider(name) abort
  88. return coc#rpc#request('hasProvider', [a:name])
  89. endfunction
  90. function! CocActionAsync(name, ...) abort
  91. return s:AsyncRequest(a:name, a:000)
  92. endfunction
  93. function! CocRequest(...) abort
  94. return coc#rpc#request('sendRequest', a:000)
  95. endfunction
  96. function! CocNotify(...) abort
  97. return coc#rpc#request('sendNotification', a:000)
  98. endfunction
  99. function! CocRegistNotification(id, method, cb) abort
  100. call coc#on_notify(a:id, a:method, a:cb)
  101. endfunction
  102. function! CocLocations(id, method, ...) abort
  103. let args = [a:id, a:method] + copy(a:000)
  104. return coc#rpc#request('findLocations', args)
  105. endfunction
  106. function! CocLocationsAsync(id, method, ...) abort
  107. let args = [a:id, a:method] + copy(a:000)
  108. return s:AsyncRequest('findLocations', args)
  109. endfunction
  110. function! CocRequestAsync(...)
  111. return s:AsyncRequest('sendRequest', a:000)
  112. endfunction
  113. function! s:AsyncRequest(name, args) abort
  114. let Cb = empty(a:args)? v:null : a:args[len(a:args) - 1]
  115. if type(Cb) == 2
  116. if !coc#rpc#ready()
  117. call Cb('service not started', v:null)
  118. else
  119. call coc#rpc#request_async(a:name, a:args[0:-2], Cb)
  120. endif
  121. return ''
  122. endif
  123. call coc#rpc#notify(a:name, a:args)
  124. return ''
  125. endfunction
  126. function! s:CommandList(...) abort
  127. let list = coc#rpc#request('commandList', a:000)
  128. return join(list, "\n")
  129. endfunction
  130. function! s:ExtensionList(...) abort
  131. let stats = CocAction('extensionStats')
  132. call filter(stats, 'v:val["isLocal"] == v:false')
  133. let list = map(stats, 'v:val["id"]')
  134. return join(list, "\n")
  135. endfunction
  136. function! s:SearchOptions(...) abort
  137. let list = ['-e', '--regexp', '-F', '--fixed-strings', '-L', '--follow',
  138. \ '-g', '--glob', '--hidden', '--no-hidden', '--no-ignore-vcs',
  139. \ '--word-regexp', '-w', '--smart-case', '-S', '--no-config',
  140. \ '--line-regexp', '--no-ignore', '-x']
  141. return join(list, "\n")
  142. endfunction
  143. function! s:LoadedExtensions(...) abort
  144. let list = CocAction('loadedExtensions')
  145. return join(list, "\n")
  146. endfunction
  147. function! s:InstallOptions(...)abort
  148. let list = ['-terminal', '-sync']
  149. return join(list, "\n")
  150. endfunction
  151. function! s:OpenConfig()
  152. let home = coc#util#get_config_home()
  153. if !isdirectory(home)
  154. echohl MoreMsg
  155. echom 'Config directory "'.home.'" does not exist, create? (y/n)'
  156. echohl None
  157. let confirm = nr2char(getchar())
  158. redraw!
  159. if !(confirm ==? "y" || confirm ==? "\r")
  160. return
  161. else
  162. call mkdir(home, 'p')
  163. end
  164. endif
  165. execute 'edit '.home.'/coc-settings.json'
  166. call coc#rpc#notify('checkJsonExtension', [])
  167. endfunction
  168. function! s:get_color(item, fallback) abort
  169. let t = type(a:item)
  170. if t == 1
  171. return a:item
  172. endif
  173. if t == 4
  174. let item = get(a:item, 'gui', {})
  175. let color = get(item, &background, a:fallback)
  176. return type(color) == 1 ? color : a:fallback
  177. endif
  178. return a:fallback
  179. endfunction
  180. function! s:AddAnsiGroups() abort
  181. let color_map = {}
  182. let colors = ['#282828', '#cc241d', '#98971a', '#d79921', '#458588', '#b16286', '#689d6a', '#a89984', '#928374']
  183. let names = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'grey']
  184. for i in range(0, len(names) - 1)
  185. let name = names[i]
  186. if exists('g:terminal_ansi_colors')
  187. let color_map[name] = s:get_color(get(g:terminal_ansi_colors, i, colors[i]), colors[i])
  188. else
  189. let color_map[name] = get(g:, 'terminal_color_'.i, colors[i])
  190. endif
  191. endfor
  192. try
  193. for name in keys(color_map)
  194. let foreground = toupper(name[0]).name[1:]
  195. let foregroundColor = color_map[name]
  196. for key in keys(color_map)
  197. let background = toupper(key[0]).key[1:]
  198. let backgroundColor = color_map[key]
  199. exe 'hi default CocList'.foreground.background.' guifg='.foregroundColor.' guibg='.backgroundColor
  200. endfor
  201. exe 'hi default CocListFg'.foreground. ' guifg='.foregroundColor. ' ctermfg='.foreground
  202. exe 'hi default CocListBg'.foreground. ' guibg='.foregroundColor. ' ctermbg='.foreground
  203. endfor
  204. catch /.*/
  205. " ignore invalid color
  206. endtry
  207. endfunction
  208. function! s:CursorRangeFromSelected(type, ...) abort
  209. " add range by operator
  210. call coc#rpc#request('cursorsSelect', [bufnr('%'), 'operator', a:type])
  211. endfunction
  212. function! s:OpenDiagnostics(...) abort
  213. let height = get(a:, 1, 0)
  214. call coc#rpc#request('fillDiagnostics', [bufnr('%')])
  215. if height
  216. execute ':lopen '.height
  217. else
  218. lopen
  219. endif
  220. endfunction
  221. function! s:Disable() abort
  222. if get(g:, 'coc_enabled', 0) == 0
  223. return
  224. endif
  225. augroup coc_nvim
  226. autocmd!
  227. augroup end
  228. call coc#rpc#request('detach', [])
  229. echohl MoreMsg
  230. echom '[coc.nvim] Event disabled'
  231. echohl None
  232. let g:coc_enabled = 0
  233. endfunction
  234. function! s:Autocmd(...) abort
  235. if !get(g:, 'coc_workspace_initialized', 0)
  236. return
  237. endif
  238. call coc#rpc#notify('CocAutocmd', a:000)
  239. endfunction
  240. function! s:HandleCharInsert(char, bufnr) abort
  241. if get(g:, 'coc_disable_space_report', 0)
  242. let g:coc_disable_space_report = 0
  243. if a:char ==# ' '
  244. return
  245. endif
  246. endif
  247. call s:Autocmd('InsertCharPre', a:char, a:bufnr)
  248. endfunction
  249. function! s:HandleWinScrolled(winid) abort
  250. if getwinvar(a:winid, 'float', 0)
  251. call coc#float#nvim_scrollbar(a:winid)
  252. endif
  253. call s:Autocmd('WinScrolled', a:winid)
  254. endfunction
  255. function! s:SyncAutocmd(...)
  256. if !get(g:, 'coc_workspace_initialized', 0)
  257. return
  258. endif
  259. call coc#rpc#request('CocAutocmd', a:000)
  260. endfunction
  261. function! s:Enable(initialize)
  262. if get(g:, 'coc_enabled', 0) == 1
  263. return
  264. endif
  265. let g:coc_enabled = 1
  266. augroup coc_nvim
  267. autocmd!
  268. if coc#rpc#started()
  269. autocmd VimEnter * call coc#rpc#notify('VimEnter', [])
  270. elseif get(g:, 'coc_start_at_startup', 1)
  271. autocmd VimEnter * call coc#rpc#start_server()
  272. endif
  273. if s:is_vim
  274. if exists('##DirChanged')
  275. autocmd DirChanged * call s:Autocmd('DirChanged', getcwd())
  276. endif
  277. if exists('##TerminalOpen')
  278. autocmd TerminalOpen * call s:Autocmd('TermOpen', +expand('<abuf>'))
  279. endif
  280. else
  281. autocmd DirChanged * call s:Autocmd('DirChanged', get(v:event, 'cwd', ''))
  282. autocmd TermOpen * call s:Autocmd('TermOpen', +expand('<abuf>'))
  283. autocmd WinEnter * call coc#float#nvim_win_enter(win_getid())
  284. endif
  285. autocmd CursorMoved list:///* call coc#list#select(bufnr('%'), line('.'))
  286. if exists('##WinClosed')
  287. autocmd WinClosed * call coc#float#on_close(+expand('<amatch>'))
  288. autocmd WinClosed * call coc#notify#on_close(+expand('<amatch>'))
  289. elseif exists('##TabEnter')
  290. autocmd TabEnter * call coc#notify#reflow()
  291. endif
  292. if has('nvim-0.4.0') || has('patch-8.1.1719')
  293. autocmd CursorHold * call coc#float#check_related()
  294. endif
  295. if exists('##WinScrolled')
  296. autocmd WinScrolled * call s:HandleWinScrolled(+expand('<amatch>'))
  297. endif
  298. autocmd TabNew * call s:Autocmd('TabNew', tabpagenr())
  299. autocmd TabClosed * call s:Autocmd('TabClosed', +expand('<afile>'))
  300. autocmd WinLeave * call s:Autocmd('WinLeave', win_getid())
  301. autocmd WinEnter * call s:Autocmd('WinEnter', win_getid())
  302. autocmd BufWinLeave * call s:Autocmd('BufWinLeave', +expand('<abuf>'), bufwinid(+expand('<abuf>')))
  303. autocmd BufWinEnter * call s:Autocmd('BufWinEnter', +expand('<abuf>'), win_getid())
  304. autocmd FileType * call s:Autocmd('FileType', expand('<amatch>'), +expand('<abuf>'))
  305. autocmd InsertCharPre * call s:HandleCharInsert(v:char, bufnr('%'))
  306. if exists('##TextChangedP')
  307. autocmd TextChangedP * call s:Autocmd('TextChangedP', +expand('<abuf>'), coc#util#change_info())
  308. endif
  309. autocmd TextChangedI * call s:Autocmd('TextChangedI', +expand('<abuf>'), coc#util#change_info())
  310. autocmd InsertLeave * call s:Autocmd('InsertLeave', +expand('<abuf>'))
  311. autocmd InsertEnter * call s:Autocmd('InsertEnter', +expand('<abuf>'))
  312. autocmd BufHidden * call s:Autocmd('BufHidden', +expand('<abuf>'))
  313. autocmd BufEnter * call s:Autocmd('BufEnter', +expand('<abuf>'))
  314. autocmd TextChanged * call s:Autocmd('TextChanged', +expand('<abuf>'), getbufvar(+expand('<abuf>'), 'changedtick'))
  315. autocmd BufWritePost * call s:Autocmd('BufWritePost', +expand('<abuf>'), getbufvar(+expand('<abuf>'), 'changedtick'))
  316. autocmd CursorMoved * call s:Autocmd('CursorMoved', +expand('<abuf>'), [line('.'), col('.')])
  317. autocmd CursorMovedI * call s:Autocmd('CursorMovedI', +expand('<abuf>'), [line('.'), col('.')])
  318. autocmd CursorHold * call s:Autocmd('CursorHold', +expand('<abuf>'), [line('.'), col('.')])
  319. autocmd CursorHoldI * call s:Autocmd('CursorHoldI', +expand('<abuf>'), [line('.'), col('.')])
  320. autocmd BufNewFile,BufReadPost * call s:Autocmd('BufCreate', +expand('<abuf>'))
  321. autocmd BufUnload * call s:Autocmd('BufUnload', +expand('<abuf>'))
  322. autocmd BufWritePre * call s:SyncAutocmd('BufWritePre', +expand('<abuf>'), bufname(+expand('<abuf>')), getbufvar(+expand('<abuf>'), 'changedtick'))
  323. autocmd FocusGained * if mode() !~# '^c' | call s:Autocmd('FocusGained') | endif
  324. autocmd FocusLost * call s:Autocmd('FocusLost')
  325. autocmd VimResized * call s:Autocmd('VimResized', &columns, &lines)
  326. autocmd VimLeavePre * let g:coc_vim_leaving = 1
  327. autocmd VimLeavePre * call s:Autocmd('VimLeavePre')
  328. autocmd BufReadCmd,FileReadCmd,SourceCmd list://* call coc#list#setup(expand('<amatch>'))
  329. autocmd BufWriteCmd __coc_refactor__* :call coc#rpc#notify('saveRefactor', [+expand('<abuf>')])
  330. autocmd ColorScheme * call s:Hi()
  331. augroup end
  332. if a:initialize == 0
  333. call coc#rpc#request('attach', [])
  334. echohl MoreMsg
  335. echom '[coc.nvim] Event enabled'
  336. echohl None
  337. endif
  338. endfunction
  339. function! s:FgColor(hlGroup) abort
  340. let fgId = synIDtrans(hlID(a:hlGroup))
  341. let ctermfg = synIDattr(fgId, 'reverse', 'cterm') ==# '1' ? synIDattr(fgId, 'bg', 'cterm') : synIDattr(fgId, 'fg', 'cterm')
  342. let guifg = synIDattr(fgId, 'reverse', 'gui') ==# '1' ? synIDattr(fgId, 'bg', 'gui') : synIDattr(fgId, 'fg', 'gui')
  343. let cmd = ' ctermfg=' . (empty(ctermfg) ? '223' : ctermfg)
  344. let cmd .= ' guifg=' . (empty(guifg) ? '#ebdbb2' : guifg)
  345. return cmd
  346. endfunction
  347. function! s:Hi() abort
  348. hi default CocErrorSign ctermfg=Red guifg=#ff0000 guibg=NONE
  349. hi default CocWarningSign ctermfg=Brown guifg=#ff922b guibg=NONE
  350. hi default CocInfoSign ctermfg=Yellow guifg=#fab005 guibg=NONE
  351. hi default CocHintSign ctermfg=Blue guifg=#15aabf guibg=NONE
  352. hi default CocSelectedText ctermfg=Red guifg=#fb4934 guibg=NONE
  353. hi default CocCodeLens ctermfg=Gray guifg=#999999 guibg=NONE
  354. hi default CocUnderline term=underline cterm=underline gui=underline
  355. hi default CocBold term=bold cterm=bold gui=bold
  356. hi default CocItalic term=italic cterm=italic gui=italic
  357. if s:is_vim || has('nvim-0.4.0')
  358. hi default CocStrikeThrough term=strikethrough cterm=strikethrough gui=strikethrough
  359. else
  360. hi default CocStrikeThrough guifg=#989898 ctermfg=gray
  361. endif
  362. hi default CocMarkdownLink ctermfg=Blue guifg=#15aabf guibg=NONE
  363. hi default CocDisabled guifg=#999999 ctermfg=gray
  364. hi default CocSearch ctermfg=Blue guifg=#15aabf guibg=NONE
  365. hi default link CocFadeOut Conceal
  366. hi default link CocMarkdownCode markdownCode
  367. hi default link CocMarkdownHeader markdownH1
  368. hi default link CocMenuSel CursorLine
  369. hi default link CocErrorFloat CocErrorSign
  370. hi default link CocWarningFloat CocWarningSign
  371. hi default link CocInfoFloat CocInfoSign
  372. hi default link CocHintFloat CocHintSign
  373. hi default link CocErrorHighlight CocUnderline
  374. hi default link CocWarningHighlight CocUnderline
  375. hi default link CocInfoHighlight CocUnderline
  376. hi default link CocHintHighlight CocUnderline
  377. hi default link CocDeprecatedHighlight CocStrikeThrough
  378. hi default link CocUnusedHighlight CocFadeOut
  379. hi default link CocListLine CursorLine
  380. hi default link CocListSearch CocSearch
  381. hi default link CocListMode ModeMsg
  382. hi default link CocListPath Comment
  383. hi default link CocHighlightText CursorColumn
  384. hi default link CocHoverRange Search
  385. hi default link CocCursorRange Search
  386. hi default link CocLinkedEditing CocCursorRange
  387. hi default link CocHighlightRead CocHighlightText
  388. hi default link CocHighlightWrite CocHighlightText
  389. hi default link CocInlayHint CocHintSign
  390. " Notification
  391. hi default CocNotificationProgress ctermfg=Blue guifg=#15aabf guibg=NONE
  392. hi default link CocNotificationButton CocUnderline
  393. hi default link CocNotificationError CocErrorFloat
  394. hi default link CocNotificationWarning CocWarningFloat
  395. hi default link CocNotificationInfo CocInfoFloat
  396. " Snippet
  397. hi default link CocSnippetVisual Visual
  398. " Tree view highlights
  399. hi default link CocTreeTitle Title
  400. hi default link CocTreeDescription Comment
  401. hi default link CocTreeOpenClose CocBold
  402. hi default link CocTreeSelected CursorLine
  403. hi default link CocSelectedRange CocHighlightText
  404. " Symbol highlights
  405. hi default link CocSymbolDefault MoreMsg
  406. "Pum
  407. hi default link CocPumSearch CocSearch
  408. hi default link CocPumMenu Normal
  409. hi default link CocPumShortcut Comment
  410. hi default link CocPumDeprecated CocStrikeThrough
  411. hi default CocPumVirtualText ctermfg=239 guifg=#504945
  412. if has('nvim')
  413. hi default link CocFloating NormalFloat
  414. else
  415. hi default link CocFloating Pmenu
  416. endif
  417. if !exists('*sign_getdefined') || empty(sign_getdefined('CocCurrentLine'))
  418. sign define CocCurrentLine linehl=CocMenuSel
  419. endif
  420. if !exists('*sign_getdefined') || empty(sign_getdefined('CocListCurrent'))
  421. sign define CocListCurrent linehl=CocListLine
  422. endif
  423. if !exists('*sign_getdefined') || empty(sign_getdefined('CocTreeSelected'))
  424. sign define CocTreeSelected linehl=CocTreeSelected
  425. endif
  426. if has('nvim-0.5.0')
  427. hi default CocCursorTransparent gui=strikethrough blend=100
  428. endif
  429. if has('nvim')
  430. let names = ['Error', 'Warning', 'Info', 'Hint']
  431. for name in names
  432. if !hlexists('Coc'.name.'VirtualText')
  433. let suffix = name ==# 'Warning' ? 'Warn' : name
  434. if hlexists('DiagnosticVirtualText'.suffix)
  435. exe 'hi default link Coc'.name.'VirtualText DiagnosticVirtualText'.suffix
  436. else
  437. exe 'hi default link Coc'.name.'VirtualText Coc'.name.'Sign'
  438. endif
  439. endif
  440. endfor
  441. endif
  442. call s:AddAnsiGroups()
  443. if get(g:, 'coc_default_semantic_highlight_groups', 1)
  444. let hlMap = {
  445. \ 'Namespace': ['TSNamespace', 'Include'],
  446. \ 'Type': ['TSType', 'Type'],
  447. \ 'Class': ['TSConstructor', 'Special'],
  448. \ 'Enum': ['TSEnum', 'Type'],
  449. \ 'Interface': ['TSInterface', 'Type'],
  450. \ 'Struct': ['TSStruct', 'Identifier'],
  451. \ 'TypeParameter': ['TSParameter', 'Identifier'],
  452. \ 'Parameter': ['TSParameter', 'Identifier'],
  453. \ 'Variable': ['TSSymbol', 'Identifier'],
  454. \ 'Property': ['TSProperty', 'Identifier'],
  455. \ 'EnumMember': ['TSEnumMember', 'Constant'],
  456. \ 'Event': ['TSEvent', 'Keyword'],
  457. \ 'Function': ['TSFunction', 'Function'],
  458. \ 'Method': ['TSMethod', 'Function'],
  459. \ 'Macro': ['TSConstMacro', 'Define'],
  460. \ 'Keyword': ['TSKeyword', 'Keyword'],
  461. \ 'Modifier': ['TSModifier', 'StorageClass'],
  462. \ 'Comment': ['TSComment', 'Comment'],
  463. \ 'String': ['TSString', 'String'],
  464. \ 'Number': ['TSNumber', 'Number'],
  465. \ 'Boolean': ['TSBoolean', 'Boolean'],
  466. \ 'Regexp': ['TSStringRegex', 'String'],
  467. \ 'Operator': ['TSOperator', 'Operator'],
  468. \ 'Decorator': ['TSSymbol', 'Identifier'],
  469. \ 'Deprecated': ['TSStrike', 'CocDeprecatedHighlight']
  470. \ }
  471. for [key, value] in items(hlMap)
  472. let ts = get(value, 0, '')
  473. let fallback = get(value, 1, '')
  474. execute 'hi default link CocSem'.key.' '.(hlexists(ts) ? ts : fallback)
  475. endfor
  476. endif
  477. let symbolMap = {
  478. \ 'Keyword': ['TSKeyword', 'Keyword'],
  479. \ 'Namespace': ['TSNamespace', 'Include'],
  480. \ 'Class': ['TSConstructor', 'Special'],
  481. \ 'Method': ['TSMethod', 'Function'],
  482. \ 'Property': ['TSProperty', 'Identifier'],
  483. \ 'Text': ['TSText', 'CocSymbolDefault'],
  484. \ 'Unit': ['TSUnit', 'CocSymbolDefault'],
  485. \ 'Value': ['TSValue', 'CocSymbolDefault'],
  486. \ 'Snippet': ['TSSnippet', 'CocSymbolDefault'],
  487. \ 'Color': ['TSColor', 'Float'],
  488. \ 'Reference': ['TSTextReference', 'Constant'],
  489. \ 'Folder': ['TSFolder', 'CocSymbolDefault'],
  490. \ 'File': ['TSFile', 'Statement'],
  491. \ 'Module': ['TSModule', 'Statement'],
  492. \ 'Package': ['TSPackage', 'Statement'],
  493. \ 'Field': ['TSField', 'Identifier'],
  494. \ 'Constructor': ['TSConstructor', 'Special'],
  495. \ 'Enum': ['TSEnum', 'CocSymbolDefault'],
  496. \ 'Interface': ['TSInterface', 'CocSymbolDefault'],
  497. \ 'Function': ['TSFunction', 'Function'],
  498. \ 'Variable': ['TSVariableBuiltin', 'Special'],
  499. \ 'Constant': ['TSConstant', 'Constant'],
  500. \ 'String': ['TSString', 'String'],
  501. \ 'Number': ['TSNumber', 'Number'],
  502. \ 'Boolean': ['TSBoolean', 'Boolean'],
  503. \ 'Array': ['TSArray', 'CocSymbolDefault'],
  504. \ 'Object': ['TSObject', 'CocSymbolDefault'],
  505. \ 'Key': ['TSKey', 'Identifier'],
  506. \ 'Null': ['TSNull', 'Type'],
  507. \ 'EnumMember': ['TSEnumMember', 'Identifier'],
  508. \ 'Struct': ['TSStruct', 'Keyword'],
  509. \ 'Event': ['TSEvent', 'Constant'],
  510. \ 'Operator': ['TSOperator', 'Operator'],
  511. \ 'TypeParameter': ['TSParameter', 'Identifier'],
  512. \ }
  513. for [key, value] in items(symbolMap)
  514. let hlGroup = hlexists(value[0]) ? value[0] : get(value, 1, 'CocSymbolDefault')
  515. if hlexists(hlGroup)
  516. execute 'hi default CocSymbol'.key.' '.s:FgColor(hlGroup)
  517. endif
  518. endfor
  519. endfunction
  520. function! s:FormatFromSelected(type)
  521. call CocActionAsync('formatSelected', a:type)
  522. endfunction
  523. function! s:CodeActionFromSelected(type)
  524. call CocActionAsync('codeAction', a:type)
  525. endfunction
  526. function! s:ShowInfo()
  527. if coc#rpc#ready()
  528. call coc#rpc#notify('showInfo', [])
  529. else
  530. let lines = []
  531. echomsg 'coc.nvim service not started, checking environment...'
  532. let node = get(g:, 'coc_node_path', $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH)
  533. if !executable(node)
  534. call add(lines, 'Error: '.node.' is not executable!')
  535. else
  536. let output = trim(system(node . ' --version'))
  537. let ms = matchlist(output, 'v\(\d\+\).\(\d\+\).\(\d\+\)')
  538. if empty(ms) || str2nr(ms[1]) < 12 || (str2nr(ms[1]) == 12 && str2nr(ms[2]) < 12)
  539. call add(lines, 'Error: Node version '.output.' < 12.12.0, please upgrade node.js')
  540. endif
  541. endif
  542. " check bundle
  543. let file = s:root.'/build/index.js'
  544. if !filereadable(file)
  545. call add(lines, 'Error: javascript bundle not found, please compile code of coc.nvim by esbuild.')
  546. endif
  547. if !empty(lines)
  548. botright vnew
  549. setl filetype=nofile
  550. call setline(1, lines)
  551. else
  552. if get(g:, 'coc_start_at_startup',1)
  553. echohl MoreMsg | echon 'Service stopped for some unknown reason, try :CocStart' | echohl None
  554. else
  555. echohl MoreMsg | echon 'Start on startup is disabled, try :CocStart' | echohl None
  556. endif
  557. endif
  558. endif
  559. endfunction
  560. command! -nargs=0 CocOutline :call coc#rpc#notify('showOutline', [])
  561. command! -nargs=? CocDiagnostics :call s:OpenDiagnostics(<f-args>)
  562. command! -nargs=0 CocInfo :call s:ShowInfo()
  563. command! -nargs=0 CocOpenLog :call coc#rpc#notify('openLog', [])
  564. command! -nargs=0 CocDisable :call s:Disable()
  565. command! -nargs=0 CocEnable :call s:Enable(0)
  566. command! -nargs=0 CocConfig :call s:OpenConfig()
  567. command! -nargs=0 CocLocalConfig :call coc#rpc#notify('openLocalConfig', [])
  568. command! -nargs=0 CocRestart :call coc#rpc#restart()
  569. command! -nargs=0 CocStart :call coc#rpc#start_server()
  570. command! -nargs=0 CocRebuild :call coc#util#rebuild()
  571. command! -nargs=1 -complete=custom,s:LoadedExtensions CocWatch :call coc#rpc#notify('watchExtension', [<f-args>])
  572. command! -nargs=+ -complete=custom,s:SearchOptions CocSearch :call coc#rpc#notify('search', [<f-args>])
  573. command! -nargs=+ -complete=custom,s:ExtensionList CocUninstall :call CocActionAsync('uninstallExtension', <f-args>)
  574. command! -nargs=* -complete=custom,s:CommandList -range CocCommand :call coc#rpc#notify('runCommand', [<f-args>])
  575. command! -nargs=* -complete=custom,coc#list#options CocList :call coc#rpc#notify('openList', [<f-args>])
  576. command! -nargs=? -complete=custom,coc#list#names CocListResume :call coc#rpc#notify('listResume', [<f-args>])
  577. command! -nargs=? -complete=custom,coc#list#names CocListCancel :call coc#rpc#notify('listCancel', [])
  578. command! -nargs=? -complete=custom,coc#list#names CocPrev :call coc#rpc#notify('listPrev', [<f-args>])
  579. command! -nargs=? -complete=custom,coc#list#names CocNext :call coc#rpc#notify('listNext', [<f-args>])
  580. command! -nargs=? -complete=custom,coc#list#names CocFirst :call coc#rpc#notify('listFirst', [<f-args>])
  581. command! -nargs=? -complete=custom,coc#list#names CocLast :call coc#rpc#notify('listLast', [<f-args>])
  582. command! -nargs=0 CocUpdate :call coc#util#update_extensions(1)
  583. command! -nargs=0 -bar CocUpdateSync :call coc#util#update_extensions()
  584. command! -nargs=* -bar -complete=custom,s:InstallOptions CocInstall :call coc#util#install_extension([<f-args>])
  585. call s:Enable(1)
  586. call s:Hi()
  587. " Default key-mappings for completion
  588. if empty(mapcheck("\<C-n>", 'i'))
  589. inoremap <silent><expr> <C-n> coc#pum#visible() ? coc#pum#next(1) : "\<C-n>"
  590. endif
  591. if empty(mapcheck("\<C-p>", 'i'))
  592. inoremap <silent><expr> <C-p> coc#pum#visible() ? coc#pum#prev(1) : "\<C-p>"
  593. endif
  594. if empty(mapcheck("\<down>", 'i'))
  595. inoremap <silent><expr> <down> coc#pum#visible() ? coc#pum#next(0) : "\<down>"
  596. endif
  597. if empty(mapcheck("\<up>", 'i'))
  598. inoremap <silent><expr> <up> coc#pum#visible() ? coc#pum#prev(0) : "\<up>"
  599. endif
  600. if empty(mapcheck("\<C-e>", 'i'))
  601. inoremap <silent><expr> <C-e> coc#pum#visible() ? coc#pum#cancel() : "\<C-e>"
  602. endif
  603. if empty(mapcheck("\<C-y>", 'i'))
  604. inoremap <silent><expr> <C-y> coc#pum#visible() ? coc#pum#confirm() : "\<C-y>"
  605. endif
  606. if empty(mapcheck("\<PageDown>", 'i'))
  607. inoremap <silent><expr> <PageDown> coc#pum#visible() ? coc#pum#scroll(1) : "\<PageDown>"
  608. endif
  609. if empty(mapcheck("\<PageUp>", 'i'))
  610. inoremap <silent><expr> <PageUp> coc#pum#visible() ? coc#pum#scroll(0) : "\<PageUp>"
  611. endif
  612. vnoremap <silent> <Plug>(coc-range-select) :<C-u>call CocActionAsync('rangeSelect', visualmode(), v:true)<CR>
  613. vnoremap <silent> <Plug>(coc-range-select-backward) :<C-u>call CocActionAsync('rangeSelect', visualmode(), v:false)<CR>
  614. nnoremap <Plug>(coc-range-select) :<C-u>call CocActionAsync('rangeSelect', '', v:true)<CR>
  615. nnoremap <Plug>(coc-codelens-action) :<C-u>call CocActionAsync('codeLensAction')<CR>
  616. vnoremap <silent> <Plug>(coc-format-selected) :<C-u>call CocActionAsync('formatSelected', visualmode())<CR>
  617. vnoremap <silent> <Plug>(coc-codeaction-selected) :<C-u>call CocActionAsync('codeAction', visualmode())<CR>
  618. nnoremap <Plug>(coc-codeaction-selected) :<C-u>set operatorfunc=<SID>CodeActionFromSelected<CR>g@
  619. nnoremap <Plug>(coc-codeaction) :<C-u>call CocActionAsync('codeAction', '')<CR>
  620. nnoremap <Plug>(coc-codeaction-line) :<C-u>call CocActionAsync('codeAction', 'line')<CR>
  621. nnoremap <Plug>(coc-codeaction-cursor) :<C-u>call CocActionAsync('codeAction', 'cursor')<CR>
  622. nnoremap <silent> <Plug>(coc-rename) :<C-u>call CocActionAsync('rename')<CR>
  623. nnoremap <silent> <Plug>(coc-format-selected) :<C-u>set operatorfunc=<SID>FormatFromSelected<CR>g@
  624. nnoremap <silent> <Plug>(coc-format) :<C-u>call CocActionAsync('format')<CR>
  625. nnoremap <silent> <Plug>(coc-diagnostic-info) :<C-u>call CocActionAsync('diagnosticInfo')<CR>
  626. nnoremap <silent> <Plug>(coc-diagnostic-next) :<C-u>call CocActionAsync('diagnosticNext')<CR>
  627. nnoremap <silent> <Plug>(coc-diagnostic-prev) :<C-u>call CocActionAsync('diagnosticPrevious')<CR>
  628. nnoremap <silent> <Plug>(coc-diagnostic-next-error) :<C-u>call CocActionAsync('diagnosticNext', 'error')<CR>
  629. nnoremap <silent> <Plug>(coc-diagnostic-prev-error) :<C-u>call CocActionAsync('diagnosticPrevious', 'error')<CR>
  630. nnoremap <silent> <Plug>(coc-definition) :<C-u>call CocActionAsync('jumpDefinition')<CR>
  631. nnoremap <silent> <Plug>(coc-declaration) :<C-u>call CocActionAsync('jumpDeclaration')<CR>
  632. nnoremap <silent> <Plug>(coc-implementation) :<C-u>call CocActionAsync('jumpImplementation')<CR>
  633. nnoremap <silent> <Plug>(coc-type-definition) :<C-u>call CocActionAsync('jumpTypeDefinition')<CR>
  634. nnoremap <silent> <Plug>(coc-references) :<C-u>call CocActionAsync('jumpReferences')<CR>
  635. nnoremap <silent> <Plug>(coc-references-used) :<C-u>call CocActionAsync('jumpUsed')<CR>
  636. nnoremap <silent> <Plug>(coc-openlink) :<C-u>call CocActionAsync('openLink')<CR>
  637. nnoremap <silent> <Plug>(coc-fix-current) :<C-u>call CocActionAsync('doQuickfix')<CR>
  638. nnoremap <silent> <Plug>(coc-float-hide) :<C-u>call coc#float#close_all()<CR>
  639. nnoremap <silent> <Plug>(coc-float-jump) :<c-u>call coc#float#jump()<cr>
  640. nnoremap <silent> <Plug>(coc-command-repeat) :<C-u>call CocAction('repeatCommand')<CR>
  641. nnoremap <silent> <Plug>(coc-refactor) :<C-u>call CocActionAsync('refactor')<CR>
  642. nnoremap <silent> <Plug>(coc-cursors-operator) :<C-u>set operatorfunc=<SID>CursorRangeFromSelected<CR>g@
  643. vnoremap <silent> <Plug>(coc-cursors-range) :<C-u>call CocAction('cursorsSelect', bufnr('%'), 'range', visualmode())<CR>
  644. nnoremap <silent> <Plug>(coc-cursors-word) :<C-u>call CocAction('cursorsSelect', bufnr('%'), 'word', 'n')<CR>
  645. nnoremap <silent> <Plug>(coc-cursors-position) :<C-u>call CocAction('cursorsSelect', bufnr('%'), 'position', 'n')<CR>
  646. vnoremap <silent> <Plug>(coc-funcobj-i) :<C-U>call CocAction('selectSymbolRange', v:true, visualmode(), ['Method', 'Function'])<CR>
  647. vnoremap <silent> <Plug>(coc-funcobj-a) :<C-U>call CocAction('selectSymbolRange', v:false, visualmode(), ['Method', 'Function'])<CR>
  648. onoremap <silent> <Plug>(coc-funcobj-i) :<C-U>call CocAction('selectSymbolRange', v:true, '', ['Method', 'Function'])<CR>
  649. onoremap <silent> <Plug>(coc-funcobj-a) :<C-U>call CocAction('selectSymbolRange', v:false, '', ['Method', 'Function'])<CR>
  650. vnoremap <silent> <Plug>(coc-classobj-i) :<C-U>call CocAction('selectSymbolRange', v:true, visualmode(), ['Interface', 'Struct', 'Class'])<CR>
  651. vnoremap <silent> <Plug>(coc-classobj-a) :<C-U>call CocAction('selectSymbolRange', v:false, visualmode(), ['Interface', 'Struct', 'Class'])<CR>
  652. onoremap <silent> <Plug>(coc-classobj-i) :<C-U>call CocAction('selectSymbolRange', v:true, '', ['Interface', 'Struct', 'Class'])<CR>
  653. onoremap <silent> <Plug>(coc-classobj-a) :<C-U>call CocAction('selectSymbolRange', v:false, '', ['Interface', 'Struct', 'Class'])<CR>