youcompleteme.vim 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. " Copyright (C) 2011-2018 YouCompleteMe contributors
  2. "
  3. " This file is part of YouCompleteMe.
  4. "
  5. " YouCompleteMe is free software: you can redistribute it and/or modify
  6. " it under the terms of the GNU General Public License as published by
  7. " the Free Software Foundation, either version 3 of the License, or
  8. " (at your option) any later version.
  9. "
  10. " YouCompleteMe is distributed in the hope that it will be useful,
  11. " but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. " GNU General Public License for more details.
  14. "
  15. " You should have received a copy of the GNU General Public License
  16. " along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. " This is basic vim plugin boilerplate
  18. let s:save_cpo = &cpo
  19. set cpo&vim
  20. " NOTE: Noevim reports v:version as 800, which is garbage. For some features
  21. " that are supporetd by our minimum Vim version, we have to guard them against
  22. " neovim, which doesn't implement them.
  23. let s:is_neovim = has( 'nvim' )
  24. " Only useful in neovim, for handling text properties... I mean extmarks.
  25. let g:ycm_neovim_ns_id = s:is_neovim ? nvim_create_namespace( 'ycm_id' ) : -1
  26. " This needs to be called outside of a function
  27. let s:script_folder_path = escape( expand( '<sfile>:p:h' ), '\' )
  28. let s:force_semantic = 0
  29. let s:force_manual = 0
  30. let s:completion_stopped = 0
  31. " These two variables are initialized in youcompleteme#Enable.
  32. let s:default_completion = {}
  33. let s:completion = s:default_completion
  34. let s:default_signature_help = {}
  35. let s:signature_help = s:default_completion
  36. let s:previous_allowed_buffer_number = 0
  37. let s:pollers = {
  38. \ 'completion': {
  39. \ 'id': -1,
  40. \ 'wait_milliseconds': 10,
  41. \ },
  42. \ 'signature_help': {
  43. \ 'id': -1,
  44. \ 'wait_milliseconds': 10,
  45. \ },
  46. \ 'file_parse_response': {
  47. \ 'id': -1,
  48. \ 'wait_milliseconds': 100,
  49. \ },
  50. \ 'server_ready': {
  51. \ 'id': -1,
  52. \ 'wait_milliseconds': 100,
  53. \ },
  54. \ 'receive_messages': {
  55. \ 'id': -1,
  56. \ 'wait_milliseconds': 100,
  57. \ },
  58. \ 'command': {
  59. \ 'id': -1,
  60. \ 'wait_milliseconds': 100,
  61. \ 'requests': {},
  62. \ },
  63. \ 'semantic_highlighting': {
  64. \ 'id': -1,
  65. \ 'wait_milliseconds': 100,
  66. \ },
  67. \ 'inlay_hints': {
  68. \ 'id': -1,
  69. \ 'wait_milliseconds': 100,
  70. \ },
  71. \ }
  72. let s:buftype_blacklist = {
  73. \ 'help': 1,
  74. \ 'terminal': 1,
  75. \ 'quickfix': 1,
  76. \ 'popup': 1,
  77. \ 'nofile': 1,
  78. \ }
  79. let s:last_char_inserted_by_user = v:true
  80. let s:enable_hover = 0
  81. let s:cursorhold_popup = -1
  82. let s:enable_inlay_hints = 0
  83. let s:force_preview_popup = 0
  84. let s:RESOLVE_NONE = 0
  85. let s:RESOLVE_UP_FRONT = 1
  86. let s:RESOLVE_ON_DEMAND = 2
  87. let s:resolve_completions = s:RESOLVE_NONE
  88. function! s:StartMessagePoll()
  89. if s:pollers.receive_messages.id < 0
  90. let s:pollers.receive_messages.id = timer_start(
  91. \ s:pollers.receive_messages.wait_milliseconds,
  92. \ function( 's:ReceiveMessages' ) )
  93. endif
  94. endfunction
  95. function! s:ReceiveMessages( timer_id )
  96. let poll_again = v:false
  97. if s:AllowedToCompleteInCurrentBuffer()
  98. let poll_again = py3eval( 'ycm_state.OnPeriodicTick()' )
  99. endif
  100. if poll_again
  101. let s:pollers.receive_messages.id = timer_start(
  102. \ s:pollers.receive_messages.wait_milliseconds,
  103. \ function( 's:ReceiveMessages' ) )
  104. else
  105. " Don't poll again until we open another buffer
  106. let s:pollers.receive_messages.id = -1
  107. endif
  108. endfunction
  109. function! s:SetUpOptions()
  110. call s:SetUpCommands()
  111. call s:SetUpCpoptions()
  112. call s:SetUpCompleteopt()
  113. call s:SetUpKeyMappings()
  114. if g:ycm_show_diagnostics_ui
  115. call s:TurnOffSyntasticForCFamily()
  116. endif
  117. call s:SetUpSigns()
  118. call s:SetUpSyntaxHighlighting()
  119. endfunction
  120. function! youcompleteme#Enable()
  121. call s:SetUpBackwardsCompatibility()
  122. let completeopt = split( &completeopt, ',' )
  123. " Will we add 'popup' to the 'completeopt' (later)
  124. let s:force_preview_popup =
  125. \ type( g:ycm_add_preview_to_completeopt ) == v:t_string &&
  126. \ g:ycm_add_preview_to_completeopt ==# 'popup' &&
  127. \ !s:is_neovim
  128. " Will we add 'preview' to the 'completeopt' (later)
  129. let force_preview =
  130. \ type( g:ycm_add_preview_to_completeopt ) != v:t_string &&
  131. \ g:ycm_add_preview_to_completeopt
  132. " Will we be using the preview popup ? That is either the user set it in their
  133. " compelteopt or we're going to add it later.
  134. let use_preview_popup =
  135. \ s:force_preview_popup ||
  136. \ index( completeopt, 'popup' ) >= 0
  137. " We should only ask the server to resolve completion items upfront if we're
  138. " going to display them - that is either:
  139. " - popup is (or will be) in completeopt
  140. " - preview is (or will be) in completeopt, or
  141. let require_resolve =
  142. \ use_preview_popup ||
  143. \ force_preview ||
  144. \ index( completeopt, 'preview' ) >= 0
  145. if use_preview_popup && exists( '*popup_findinfo' )
  146. " If the preview popup is going to be used, and on-demand resolve can be
  147. " supported, enable it.
  148. let s:resolve_completions = s:RESOLVE_ON_DEMAND
  149. elseif require_resolve
  150. " The preview window or info popup is enalbed - request the server
  151. " pre-resolves completion items
  152. let s:resolve_completions = s:RESOLVE_UP_FRONT
  153. else
  154. " Otherwise, there's no point in resolving completions - they'll never be
  155. " displayed.
  156. endif
  157. if !s:SetUpPython()
  158. return
  159. endif
  160. call s:SetUpOptions()
  161. py3 ycm_semantic_highlighting.Initialise()
  162. let s:enable_inlay_hints = py3eval( 'ycm_inlay_hints.Initialise()' ) ? 1 : 0
  163. call youcompleteme#EnableCursorMovedAutocommands()
  164. augroup youcompleteme
  165. autocmd!
  166. " Note that these events will NOT trigger for the file vim is started with;
  167. " so if you do "vim foo.cc", these events will not trigger when that buffer
  168. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  169. " that happens *after* FileType has already triggered for the initial file.
  170. " We don't parse the buffer on the BufRead event since it would only be
  171. " useful if the buffer filetype is set (we ignore the buffer if there is no
  172. " filetype) and if so, the FileType event has triggered before and thus the
  173. " buffer is already parsed.
  174. autocmd BufWritePost,FileWritePost * call s:OnFileSave()
  175. autocmd FileType * call s:OnFileTypeSet()
  176. autocmd BufEnter,CmdwinEnter,WinEnter * call s:OnBufferEnter()
  177. autocmd BufUnload * call s:OnBufferUnload()
  178. autocmd InsertLeave * call s:OnInsertLeave()
  179. autocmd VimLeave * call s:OnVimLeave()
  180. autocmd CompleteDone * call s:OnCompleteDone()
  181. autocmd CompleteChanged * call s:OnCompleteChanged()
  182. augroup END
  183. " The FileType event is not triggered for the first loaded file. We wait until
  184. " the server is ready to manually run the s:OnFileTypeSet function.
  185. let s:pollers.server_ready.id = timer_start(
  186. \ s:pollers.server_ready.wait_milliseconds,
  187. \ function( 's:PollServerReady' ) )
  188. let s:default_completion = py3eval( 'vimsupport.NO_COMPLETIONS' )
  189. let s:completion = s:default_completion
  190. if s:PropertyTypeNotDefined( 'YCM-signature-help-current-argument' )
  191. hi default YCMInverse term=reverse cterm=reverse gui=reverse
  192. call prop_type_add( 'YCM-signature-help-current-argument', {
  193. \ 'highlight': 'YCMInverse',
  194. \ 'combine': 1,
  195. \ 'priority': 50,
  196. \ } )
  197. endif
  198. nnoremap <silent> <plug>(YCMFindSymbolInWorkspace)
  199. \ :call youcompleteme#finder#FindSymbol( 'workspace' )<CR>
  200. nnoremap <silent> <plug>(YCMFindSymbolInDocument)
  201. \ :call youcompleteme#finder#FindSymbol( 'document' )<CR>
  202. endfunction
  203. function! youcompleteme#EnableCursorMovedAutocommands()
  204. augroup ycmcompletemecursormove
  205. autocmd!
  206. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  207. autocmd CursorMovedI * let s:current_cursor_position = getpos( '.' )
  208. autocmd InsertEnter * call s:OnInsertEnter()
  209. autocmd TextChanged * call s:OnTextChangedNormalMode()
  210. autocmd TextChangedI * call s:OnTextChangedInsertMode( v:false )
  211. autocmd TextChangedP * call s:OnTextChangedInsertMode( v:true )
  212. autocmd InsertCharPre * call s:OnInsertChar()
  213. if exists( '##WinScrolled' )
  214. autocmd WinScrolled * call s:OnWinScrolled()
  215. endif
  216. augroup END
  217. endfunction
  218. function! youcompleteme#DisableCursorMovedAutocommands()
  219. autocmd! ycmcompletemecursormove
  220. endfunction
  221. function! youcompleteme#GetErrorCount()
  222. return py3eval( 'ycm_state.GetErrorCount()' )
  223. endfunction
  224. function! youcompleteme#GetWarningCount()
  225. return py3eval( 'ycm_state.GetWarningCount()' )
  226. endfunction
  227. function! s:SetUpPython() abort
  228. py3 << EOF
  229. import os.path as p
  230. import sys
  231. import traceback
  232. import vim
  233. root_folder = p.normpath( p.join( vim.eval( 's:script_folder_path' ), '..' ) )
  234. third_party_folder = p.join( root_folder, 'third_party' )
  235. # Add dependencies to Python path.
  236. sys.path[ 0:0 ] = [ p.join( root_folder, 'python' ),
  237. p.join( third_party_folder, 'ycmd' ) ]
  238. # We enclose this code in a try/except block to avoid backtraces in Vim.
  239. try:
  240. # Import the modules used in this file.
  241. from ycm import base, vimsupport, youcompleteme
  242. from ycm import semantic_highlighting as ycm_semantic_highlighting
  243. from ycm import inlay_hints as ycm_inlay_hints
  244. if 'ycm_state' in globals():
  245. # If re-initializing, pretend that we shut down
  246. ycm_state.OnVimLeave()
  247. del ycm_state
  248. # If we're able to resolve completion details asynchronously, set the option
  249. # which enables this in the server.
  250. if int( vim.eval( 's:resolve_completions == s:RESOLVE_ON_DEMAND' ) ):
  251. # resovle a small number upfront, the rest on demand
  252. default_options = {
  253. 'max_num_candidates_to_detail': 10
  254. }
  255. elif int( vim.eval( 's:resolve_completions == s:RESOLVE_NONE' ) ):
  256. # don't reasolve any
  257. default_options = {
  258. 'max_num_candidates_to_detail': 0
  259. }
  260. else:
  261. # i.e. s:resolve_completions == s:RESOLVE_UP_FRONT
  262. # The server will decide - i.e. resovle everything upfront
  263. default_options = {}
  264. ycm_state = youcompleteme.YouCompleteMe( default_options )
  265. except Exception as error:
  266. # We don't use PostVimMessage or EchoText from the vimsupport module because
  267. # importing this module may fail.
  268. vim.command( 'redraw | echohl WarningMsg' )
  269. for line in traceback.format_exc().splitlines():
  270. vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) )
  271. vim.command( "echo 'YouCompleteMe unavailable: {0}'"
  272. .format( str( error ).replace( "'", "''" ) ) )
  273. vim.command( 'echohl None' )
  274. vim.command( 'return 0' )
  275. else:
  276. vim.command( 'return 1' )
  277. EOF
  278. endfunction
  279. function! s:SetUpKeyMappings()
  280. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  281. " exist and are now here purely for the sake of backwards compatibility; we
  282. " don't want to break users if we can avoid it.
  283. if exists('g:ycm_key_select_completion') &&
  284. \ index(g:ycm_key_list_select_completion,
  285. \ g:ycm_key_select_completion) == -1
  286. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  287. endif
  288. if exists('g:ycm_key_previous_completion') &&
  289. \ index(g:ycm_key_list_previous_completion,
  290. \ g:ycm_key_previous_completion) == -1
  291. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  292. endif
  293. for key in g:ycm_key_list_select_completion
  294. " With this command, when the completion window is visible, the tab key
  295. " (default) will select the next candidate in the window. In vim, this also
  296. " changes the typed-in text to that of the candidate completion.
  297. exe 'inoremap <expr>' . key . ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  298. endfor
  299. for key in g:ycm_key_list_previous_completion
  300. " This selects the previous candidate for shift-tab (default)
  301. exe 'inoremap <expr>' . key . ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  302. endfor
  303. for key in g:ycm_key_list_stop_completion
  304. " When selecting a candidate and closing the completion menu with the <C-y>
  305. " key, the menu will automatically be reopened because of the TextChangedI
  306. " event. We define a command to prevent that.
  307. exe 'inoremap <expr>' . key . ' <SID>StopCompletion( "\' . key . '" )'
  308. endfor
  309. if !empty( g:ycm_key_invoke_completion )
  310. let invoke_key = g:ycm_key_invoke_completion
  311. " Inside the console, <C-Space> is passed as <Nul> to Vim
  312. if invoke_key ==# '<C-Space>'
  313. imap <Nul> <C-Space>
  314. endif
  315. silent! exe 'inoremap <unique> <silent> ' . invoke_key .
  316. \ ' <C-R>=<SID>RequestSemanticCompletion()<CR>'
  317. endif
  318. if !empty( g:ycm_key_detailed_diagnostics )
  319. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  320. \ ' :YcmShowDetailedDiagnostic<CR>'
  321. endif
  322. endfunction
  323. function! s:SetUpSigns()
  324. " We try to ensure backwards compatibility with Syntastic if the user has
  325. " already defined styling for Syntastic highlight groups.
  326. if !hlexists( 'YcmErrorSign' )
  327. if hlexists( 'SyntasticErrorSign')
  328. highlight default link YcmErrorSign SyntasticErrorSign
  329. else
  330. highlight default link YcmErrorSign error
  331. endif
  332. endif
  333. if !hlexists( 'YcmWarningSign' )
  334. if hlexists( 'SyntasticWarningSign')
  335. highlight default link YcmWarningSign SyntasticWarningSign
  336. else
  337. highlight default link YcmWarningSign todo
  338. endif
  339. endif
  340. if !hlexists( 'YcmErrorLine' )
  341. highlight default link YcmErrorLine SyntasticErrorLine
  342. endif
  343. if !hlexists( 'YcmWarningLine' )
  344. highlight default link YcmWarningLine SyntasticWarningLine
  345. endif
  346. call sign_define( [
  347. \ { 'name': 'YcmError',
  348. \ 'text': g:ycm_error_symbol,
  349. \ 'texthl': 'YcmErrorSign',
  350. \ 'linehl': 'YcmErrorLine',
  351. \ 'group': 'ycm_signs' },
  352. \ { 'name': 'YcmWarning',
  353. \ 'text': g:ycm_warning_symbol,
  354. \ 'texthl': 'YcmWarningSign',
  355. \ 'linehl': 'YcmWarningLine',
  356. \ 'group': 'ycm_signs' }
  357. \ ] )
  358. endfunction
  359. function! s:SetUpSyntaxHighlighting()
  360. " We try to ensure backwards compatibility with Syntastic if the user has
  361. " already defined styling for Syntastic highlight groups.
  362. if !hlexists( 'YcmErrorSection' )
  363. if hlexists( 'SyntasticError' )
  364. highlight default link YcmErrorSection SyntasticError
  365. else
  366. highlight default link YcmErrorSection SpellBad
  367. endif
  368. endif
  369. if s:PropertyTypeNotDefined( 'YcmErrorProperty' )
  370. call prop_type_add( 'YcmErrorProperty', {
  371. \ 'highlight': 'YcmErrorSection',
  372. \ 'priority': 30,
  373. \ 'combine': 0,
  374. \ 'override': 1 } )
  375. endif
  376. " Used for virtual text
  377. if !hlexists( 'YcmInvisible' )
  378. highlight default link YcmInvisible Normal
  379. endif
  380. if !hlexists( 'YcmInlayHint' )
  381. highlight default link YcmInlayHint NonText
  382. endif
  383. if !hlexists( 'YcmErrorText' )
  384. if exists( '*hlget' )
  385. let YcmErrorText = hlget( 'SpellBad', v:true )[ 0 ]
  386. let YcmErrorText.name = 'YcmErrorText'
  387. let YcmErrorText.cterm = {}
  388. let YcmErrorText.gui = {}
  389. let YcmErrorText.term = {}
  390. call hlset( [ YcmErrorText ] )
  391. else
  392. " approximation
  393. hi default link YcmErrorText WarningMsg
  394. endif
  395. endif
  396. if !hlexists( 'YcmWarningText' )
  397. if exists( '*hlget' )
  398. let YcmWarningText = hlget( 'SpellCap', v:true )[ 0 ]
  399. let YcmWarningText.name = 'YcmWarningText'
  400. let YcmWarningText.cterm = {}
  401. let YcmWarningText.gui = {}
  402. let YcmWarningText.term = {}
  403. call hlset( [ YcmWarningText] )
  404. else
  405. " Lame approximation
  406. hi default link YcmWarningText Conceal
  407. endif
  408. endif
  409. if s:PropertyTypeNotDefined( 'YcmVirtDiagError' )
  410. call prop_type_add( 'YcmVirtDiagError', {
  411. \ 'highlight': 'YcmErrorText',
  412. \ 'priority': 20,
  413. \ 'combine': 0 } )
  414. endif
  415. if s:PropertyTypeNotDefined( 'YcmVirtDiagWarning' )
  416. call prop_type_add( 'YcmVirtDiagWarning', {
  417. \ 'highlight': 'YcmWarningText',
  418. \ 'priority': 19,
  419. \ 'combine': 0 } )
  420. endif
  421. if s:PropertyTypeNotDefined( 'YcmVirtDiagPadding' )
  422. call prop_type_add( 'YcmVirtDiagPadding', {
  423. \ 'highlight': 'YcmInvisible',
  424. \ 'priority': 100,
  425. \ 'combine': 1 } )
  426. endif
  427. if !hlexists( 'YcmWarningSection' )
  428. if hlexists( 'SyntasticWarning' )
  429. highlight default link YcmWarningSection SyntasticWarning
  430. else
  431. highlight default link YcmWarningSection SpellCap
  432. endif
  433. endif
  434. if s:PropertyTypeNotDefined( 'YcmWarningProperty' )
  435. call prop_type_add( 'YcmWarningProperty', {
  436. \ 'highlight': 'YcmWarningSection',
  437. \ 'priority': 29,
  438. \ 'combine': 0,
  439. \ 'override': 1 } )
  440. endif
  441. if !hlexists( 'YcmErrorPopup' )
  442. highlight default link YcmErrorPopup ErrorMsg
  443. endif
  444. endfunction
  445. function! s:SetUpBackwardsCompatibility()
  446. let complete_in_comments_and_strings =
  447. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  448. if complete_in_comments_and_strings
  449. let g:ycm_complete_in_strings = 1
  450. let g:ycm_complete_in_comments = 1
  451. endif
  452. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  453. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  454. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  455. endif
  456. endfunction
  457. " Needed so that YCM is used instead of Syntastic
  458. function! s:TurnOffSyntasticForCFamily()
  459. let g:syntastic_cpp_checkers = []
  460. let g:syntastic_c_checkers = []
  461. let g:syntastic_objc_checkers = []
  462. let g:syntastic_objcpp_checkers = []
  463. let g:syntastic_cuda_checkers = []
  464. endfunction
  465. function! s:DisableOnLargeFile( buffer )
  466. if exists( 'b:ycm_largefile' )
  467. return b:ycm_largefile
  468. endif
  469. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  470. let b:ycm_largefile =
  471. \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold
  472. if b:ycm_largefile
  473. py3 vimsupport.PostVimMessage( 'YouCompleteMe is disabled in this buffer;' +
  474. \ ' the file exceeded the max size (see YCM options).' )
  475. endif
  476. return b:ycm_largefile
  477. endfunction
  478. function! s:PropertyTypeNotDefined( type )
  479. return exists( '*prop_type_add' ) &&
  480. \ index( prop_type_list(), a:type ) == -1
  481. endfunction
  482. function! s:AllowedToCompleteInBuffer( buffer )
  483. let buftype = getbufvar( a:buffer, '&buftype' )
  484. if has_key( s:buftype_blacklist, buftype )
  485. return 0
  486. endif
  487. let filetype = getbufvar( a:buffer, '&filetype' )
  488. if empty( filetype )
  489. let filetype = 'ycm_nofiletype'
  490. endif
  491. let allowed = youcompleteme#filetypes#AllowedForFiletype( filetype )
  492. if !allowed || s:DisableOnLargeFile( a:buffer )
  493. return 0
  494. endif
  495. let s:previous_allowed_buffer_number = bufnr( a:buffer )
  496. return allowed
  497. endfunction
  498. function! s:AllowedToCompleteInCurrentBuffer()
  499. return s:AllowedToCompleteInBuffer( '%' )
  500. endfunction
  501. function! s:VisitedBufferRequiresReparse()
  502. if bufnr( '%' ) ==# s:previous_allowed_buffer_number
  503. return 0
  504. endif
  505. return s:AllowedToCompleteInCurrentBuffer()
  506. endfunction
  507. function! s:SetUpCpoptions()
  508. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  509. " no way to not have this and have YCM working, so force the flag.
  510. set cpoptions+=B
  511. " This prevents the display of "Pattern not found" & similar messages during
  512. " completion.
  513. set shortmess+=c
  514. endfunction
  515. function! s:SetUpCompleteopt()
  516. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  517. " instance adding 'longest'. This breaks YCM. So we force our settings.
  518. " There's no two ways about this: if you want to use YCM then you have to
  519. " have these completeopt settings, otherwise YCM won't work at all.
  520. " We need menuone in completeopt, otherwise when there's only one candidate
  521. " for completion, the menu doesn't show up.
  522. set completeopt-=menu
  523. set completeopt+=menuone
  524. " This is unnecessary with our features. People use this option to insert
  525. " the common prefix of all the matches and then add more differentiating chars
  526. " so that they can select a more specific match. With our features, they
  527. " don't need to insert the prefix; they just type the differentiating chars.
  528. " Also, having this option set breaks the plugin.
  529. set completeopt-=longest
  530. if s:resolve_completions == s:RESOLVE_ON_DEMAND
  531. set completeopt+=popuphidden
  532. endif
  533. if s:force_preview_popup
  534. set completeopt+=popup
  535. elseif g:ycm_add_preview_to_completeopt
  536. set completeopt+=preview
  537. endif
  538. endfunction
  539. function! s:EnableCompletingInCurrentBuffer()
  540. if !g:ycm_auto_trigger
  541. call s:SetCompleteFunc()
  542. endif
  543. let b:ycm_completing = 1
  544. endfunction
  545. function s:StopPoller( poller ) abort
  546. call timer_stop( a:poller.id )
  547. let a:poller.id = -1
  548. endfunction
  549. function! s:OnVimLeave()
  550. " Workaround a NeoVim issue - not shutting down timers correctly
  551. " https://github.com/neovim/neovim/issues/6840
  552. for poller in values( s:pollers )
  553. call s:StopPoller( poller )
  554. endfor
  555. py3 ycm_state.OnVimLeave()
  556. endfunction
  557. function! s:OnCompleteDone()
  558. if !s:AllowedToCompleteInCurrentBuffer()
  559. return
  560. endif
  561. let s:last_char_inserted_by_user = v:false
  562. py3 ycm_state.OnCompleteDone()
  563. call s:UpdateSignatureHelp()
  564. endfunction
  565. function! s:OnCompleteChanged()
  566. if !s:AllowedToCompleteInCurrentBuffer()
  567. return
  568. endif
  569. if ! empty( v:event.completed_item )
  570. let s:last_char_inserted_by_user = v:false
  571. call s:ResolveCompletionItem( v:event.completed_item )
  572. endif
  573. call s:UpdateSignatureHelp()
  574. endfunction
  575. function! s:ResolveCompletionItem( item )
  576. if s:resolve_completions != s:RESOLVE_ON_DEMAND
  577. return
  578. endif
  579. let complete_mode = complete_info( [ 'mode' ] ).mode
  580. if complete_mode !=# 'eval' && complete_mode !=# 'function'
  581. return
  582. endif
  583. if py3eval( 'ycm_state.ResolveCompletionItem( vim.eval( "a:item" ) )' )
  584. call s:StopPoller( s:pollers.completion )
  585. call timer_start( 0, function( 's:PollResolve', [ a:item ] ) )
  586. else
  587. call s:ShowInfoPopup( a:item )
  588. endif
  589. endfunction
  590. function! s:EnableAutoHover()
  591. if g:ycm_auto_hover ==# 'CursorHold' && s:enable_hover
  592. augroup YcmBufHover
  593. autocmd! * <buffer>
  594. autocmd CursorHold <buffer> call s:Hover()
  595. augroup END
  596. endif
  597. endfunction
  598. function! s:DisableAutoHover()
  599. augroup YcmBufHover
  600. autocmd! * <buffer>
  601. augroup END
  602. endfunction
  603. function! s:OnFileTypeSet()
  604. " The contents of the command-line window are empty when the filetype is set
  605. " for the first time. Users should never change its filetype so we only rely
  606. " on the CmdwinEnter event for that window.
  607. if !empty( getcmdwintype() )
  608. return
  609. endif
  610. if !s:AllowedToCompleteInCurrentBuffer()
  611. return
  612. endif
  613. call s:SetUpCompleteopt()
  614. call s:EnableCompletingInCurrentBuffer()
  615. call s:StartMessagePoll()
  616. call s:EnableAutoHover()
  617. py3 ycm_state.OnFileTypeSet()
  618. call s:OnFileReadyToParse( 1 )
  619. endfunction
  620. function! s:OnFileSave()
  621. let buffer_number = str2nr( expand( '<abuf>' ) )
  622. if !s:AllowedToCompleteInBuffer( buffer_number )
  623. return
  624. endif
  625. py3 ycm_state.OnFileSave( vimsupport.GetIntValue( 'buffer_number' ) )
  626. endfunction
  627. function! s:OnBufferEnter()
  628. call s:StartMessagePoll()
  629. if !s:VisitedBufferRequiresReparse()
  630. return
  631. endif
  632. call s:SetUpCompleteopt()
  633. call s:EnableCompletingInCurrentBuffer()
  634. py3 ycm_state.UpdateMatches()
  635. py3 ycm_state.OnBufferVisit()
  636. " Last parse may be outdated because of changes from other buffers. Force a
  637. " new parse.
  638. call s:OnFileReadyToParse( 1 )
  639. endfunction
  640. function! s:OnBufferUnload()
  641. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  642. " it as a true number for the getbufvar function.
  643. let buffer_number = str2nr( expand( '<abuf>' ) )
  644. if !s:AllowedToCompleteInBuffer( buffer_number )
  645. return
  646. endif
  647. py3 ycm_state.OnBufferUnload( vimsupport.GetIntValue( 'buffer_number' ) )
  648. endfunction
  649. function! s:PollServerReady( timer_id )
  650. if !py3eval( 'ycm_state.IsServerAlive()' )
  651. py3 ycm_state.NotifyUserIfServerCrashed()
  652. " Server crashed. Don't poll it again.
  653. return
  654. endif
  655. if !py3eval( 'ycm_state.CheckIfServerIsReady()' )
  656. let s:pollers.server_ready.id = timer_start(
  657. \ s:pollers.server_ready.wait_milliseconds,
  658. \ function( 's:PollServerReady' ) )
  659. return
  660. endif
  661. call s:OnFileTypeSet()
  662. endfunction
  663. function! s:OnFileReadyToParse( ... )
  664. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  665. " FileReadyToParse event notification, whether the buffer has changed or not;
  666. " effectively forcing a parse of the buffer. Default is 0.
  667. let force_parsing = a:0 > 0 && a:1
  668. " We only want to send a new FileReadyToParse event notification if the buffer
  669. " has changed since the last time we sent one, or if forced.
  670. if force_parsing || py3eval( "ycm_state.NeedsReparse()" )
  671. " We switched buffers or somethuing, so claer.
  672. " FIXME: sig hekp should be buffer local?
  673. call s:ClearSignatureHelp()
  674. py3 ycm_state.OnFileReadyToParse()
  675. call s:StopPoller( s:pollers.file_parse_response )
  676. let s:pollers.file_parse_response.id = timer_start(
  677. \ s:pollers.file_parse_response.wait_milliseconds,
  678. \ function( 's:PollFileParseResponse' ) )
  679. call s:UpdateSemanticHighlighting( bufnr(), 1, 0 )
  680. call s:UpdateInlayHints( bufnr(), 1, 0 )
  681. endif
  682. endfunction
  683. function! s:UpdateSemanticHighlighting( bufnr, force, redraw_anyway ) abort
  684. call s:StopPoller( s:pollers.semantic_highlighting )
  685. if !s:is_neovim &&
  686. \ get( b:, 'ycm_enable_semantic_highlighting',
  687. \ get( g:, 'ycm_enable_semantic_highlighting', 0 ) )
  688. if py3eval(
  689. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).'
  690. \ . 'semantic_highlighting.Request( '
  691. \ . ' force=int( vim.eval( "a:force" ) ) )' )
  692. let s:pollers.semantic_highlighting.id = timer_start(
  693. \ s:pollers.semantic_highlighting.wait_milliseconds,
  694. \ function( 's:PollSemanticHighlighting', [ a:bufnr ] ) )
  695. elseif a:redraw_anyway
  696. py3 ycm_state.Buffer(
  697. \ int( vim.eval( "a:bufnr" ) ) ).semantic_highlighting.Refresh()
  698. endif
  699. endif
  700. endfunction
  701. function s:ShouldUseInlayHintsNow( bufnr )
  702. return s:enable_inlay_hints &&
  703. \ getbufvar( a:bufnr, 'ycm_enable_inlay_hints',
  704. \ get( g:, 'ycm_enable_inlay_hints', 0 ) )
  705. endfunction
  706. function! s:UpdateInlayHints( bufnr, force, redraw_anyway ) abort
  707. call s:StopPoller( s:pollers.inlay_hints )
  708. if s:ShouldUseInlayHintsNow( a:bufnr )
  709. if py3eval(
  710. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).'
  711. \ . 'inlay_hints.Request( force=int( vim.eval( "a:force" ) ) )' )
  712. let s:pollers.inlay_hints.id = timer_start(
  713. \ s:pollers.inlay_hints.wait_milliseconds,
  714. \ function( 's:PollInlayHints', [ a:bufnr ] ) )
  715. elseif a:redraw_anyway
  716. py3 ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).inlay_hints.Refresh()
  717. endif
  718. endif
  719. endfunction
  720. function! s:PollFileParseResponse( ... )
  721. if !py3eval( "ycm_state.FileParseRequestReady()" )
  722. let s:pollers.file_parse_response.id = timer_start(
  723. \ s:pollers.file_parse_response.wait_milliseconds,
  724. \ function( 's:PollFileParseResponse' ) )
  725. return
  726. endif
  727. py3 ycm_state.HandleFileParseRequest()
  728. if py3eval( "ycm_state.ShouldResendFileParseRequest()" )
  729. call s:OnFileReadyToParse( 1 )
  730. endif
  731. endfunction
  732. function! s:PollSemanticHighlighting( bufnr, ... ) abort
  733. return s:PollScrollable( a:bufnr, 'semantic_highlighting' )
  734. endfunction
  735. function! s:PollInlayHints( bufnr, ... ) abort
  736. return s:PollScrollable( a:bufnr, 'inlay_hints' )
  737. endfunction
  738. function! s:PollScrollable( bufnr, scrollable, ... ) abort
  739. if !py3eval(
  740. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )'
  741. \ . '.' . a:scrollable . '.Ready()' )
  742. let s:pollers[a:scrollable].id = timer_start(
  743. \ s:pollers[a:scrollable].wait_milliseconds,
  744. \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) )
  745. elseif ! py3eval(
  746. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )'
  747. \ . '.' . a:scrollable . '.Update()' )
  748. let s:pollers[ a:scrollable ].id = timer_start(
  749. \ s:pollers[ a:scrollable ].wait_milliseconds,
  750. \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) )
  751. endif
  752. endfunction
  753. function! s:SendKeys( keys )
  754. " By default keys are added to the end of the typeahead buffer. If there are
  755. " already keys in the buffer, they will be processed first and may change
  756. " the state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in
  757. " normal mode instead of insert mode or <C-e> outside of completion mode).
  758. " We avoid that by inserting the keys at the start of the typeahead buffer
  759. " with the 'i' option. Also, we don't want the keys to be remapped to
  760. " something else so we add the 'n' option.
  761. call feedkeys( a:keys, 'in' )
  762. endfunction
  763. function! s:CloseCompletionMenu()
  764. if pumvisible()
  765. call s:SendKeys( "\<C-e>" )
  766. endif
  767. endfunction
  768. function! s:OnInsertChar()
  769. if !s:AllowedToCompleteInCurrentBuffer()
  770. return
  771. endif
  772. let s:last_char_inserted_by_user = v:true
  773. endfunction
  774. function! s:StopCompletion( key )
  775. call s:StopPoller( s:pollers.completion )
  776. call s:ClearSignatureHelp()
  777. if pumvisible()
  778. let s:completion_stopped = 1
  779. return "\<C-y>"
  780. endif
  781. return a:key
  782. endfunction
  783. function! s:OnCursorMovedNormalMode()
  784. if !s:AllowedToCompleteInCurrentBuffer()
  785. return
  786. endif
  787. py3 ycm_state.OnCursorMoved()
  788. endfunction
  789. function! s:OnWinScrolled()
  790. if !s:AllowedToCompleteInCurrentBuffer()
  791. return
  792. endif
  793. let bufnr = winbufnr( expand( '<afile>' ) )
  794. call s:UpdateSemanticHighlighting( bufnr, 0, 0 )
  795. call s:UpdateInlayHints( bufnr, 0, 0 )
  796. endfunction
  797. function! s:OnTextChangedNormalMode()
  798. if !s:AllowedToCompleteInCurrentBuffer()
  799. return
  800. endif
  801. call s:OnFileReadyToParse()
  802. endfunction
  803. function! s:OnTextChangedInsertMode( popup_is_visible )
  804. if !s:AllowedToCompleteInCurrentBuffer()
  805. return
  806. endif
  807. if a:popup_is_visible && !s:last_char_inserted_by_user
  808. " If the last "input" wasn't from a user typing (i.e. didn't come from
  809. " InsertCharPre, then ignore this change in the text. This prevents ctrl-n
  810. " or tab from causing us to re-filter the list based on the now-selected
  811. " item.
  812. return
  813. endif
  814. let s:current_cursor_position = getpos( '.' )
  815. if s:completion_stopped
  816. let s:completion_stopped = 0
  817. let s:completion = s:default_completion
  818. return
  819. endif
  820. call s:IdentifierFinishedOperations()
  821. " We have to make sure we correctly leave semantic mode even when the user
  822. " inserts something like a "operator[]" candidate string which fails
  823. " CurrentIdentifierFinished check.
  824. if s:force_semantic && !py3eval( 'base.LastEnteredCharIsIdentifierChar()' )
  825. let s:force_semantic = 0
  826. let s:force_manual = 0
  827. endif
  828. if get( b:, 'ycm_completing' ) &&
  829. \ ( g:ycm_auto_trigger || s:force_semantic || s:force_manual ) &&
  830. \ !s:InsideCommentOrStringAndShouldStop() &&
  831. \ !s:OnBlankLine()
  832. call s:RequestCompletion()
  833. call s:RequestSignatureHelp()
  834. endif
  835. py3 ycm_state.OnCursorMoved()
  836. if g:ycm_autoclose_preview_window_after_completion
  837. call s:ClosePreviewWindowIfNeeded()
  838. endif
  839. endfunction
  840. function! s:OnInsertEnter() abort
  841. let s:current_cursor_position = getpos( '.' )
  842. py3 ycm_state.OnInsertEnter()
  843. if s:ShouldUseInlayHintsNow( bufnr() ) &&
  844. \ get(g:, 'ycm_clear_inlay_hints_in_insert_mode' )
  845. py3 ycm_state.CurrentBuffer().inlay_hints.Clear()
  846. endif
  847. endfunction
  848. function! s:OnInsertLeave()
  849. if !s:AllowedToCompleteInCurrentBuffer()
  850. return
  851. endif
  852. let s:last_char_inserted_by_user = v:false
  853. call s:StopPoller( s:pollers.completion )
  854. let s:force_semantic = 0
  855. let s:force_manual = 0
  856. let s:completion = s:default_completion
  857. call s:OnFileReadyToParse()
  858. py3 ycm_state.OnInsertLeave()
  859. if g:ycm_autoclose_preview_window_after_completion ||
  860. \ g:ycm_autoclose_preview_window_after_insertion
  861. call s:ClosePreviewWindowIfNeeded()
  862. endif
  863. call s:ClearSignatureHelp()
  864. if s:ShouldUseInlayHintsNow( bufnr() )
  865. \ && get( g:, 'ycm_clear_inlay_hints_in_insert_mode' )
  866. " We cleared inlay hints on insert enter
  867. py3 ycm_state.CurrentBuffer().inlay_hints.Refresh()
  868. endif
  869. endfunction
  870. function! s:ClosePreviewWindowIfNeeded()
  871. let current_buffer_name = bufname('')
  872. " We don't want to try to close the preview window in special buffers like
  873. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  874. " with '['.
  875. if current_buffer_name[ 0 ] == '['
  876. return
  877. endif
  878. " This command does the actual closing of the preview window. If no preview
  879. " window is shown, nothing happens.
  880. pclose
  881. endfunction
  882. function! s:IdentifierFinishedOperations()
  883. if !py3eval( 'base.CurrentIdentifierFinished()' )
  884. return
  885. endif
  886. py3 ycm_state.OnCurrentIdentifierFinished()
  887. let s:force_semantic = 0
  888. let s:force_manual = 0
  889. let s:completion = s:default_completion
  890. endfunction
  891. " Returns 1 when inside comment and 2 when inside string
  892. function! s:InsideCommentOrString()
  893. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  894. " in insert mode when this func is called.
  895. let syntax_group = synIDattr(
  896. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  897. if stridx(syntax_group, 'Comment') > -1
  898. return 1
  899. endif
  900. if stridx(syntax_group, 'String') > -1
  901. return 2
  902. endif
  903. return 0
  904. endfunction
  905. function! s:InsideCommentOrStringAndShouldStop()
  906. let retval = s:InsideCommentOrString()
  907. let inside_comment = retval == 1
  908. let inside_string = retval == 2
  909. if inside_comment && g:ycm_complete_in_comments ||
  910. \ inside_string && g:ycm_complete_in_strings
  911. return 0
  912. endif
  913. return retval
  914. endfunction
  915. function! s:OnBlankLine()
  916. return py3eval( 'not vim.current.line or vim.current.line.isspace()' )
  917. endfunction
  918. function! s:RequestCompletion()
  919. call s:StopPoller( s:pollers.completion )
  920. py3 ycm_state.SendCompletionRequest(
  921. \ vimsupport.GetBoolValue( 's:force_semantic' ) )
  922. if py3eval( 'ycm_state.CompletionRequestReady()' )
  923. " We can't call complete() syncrhounsouly in the TextChangedI/TextChangedP
  924. " autocommmands (it's designed to be used async only completion). The result
  925. " (somewhat oddly) is that the completion menu is shown, but ctrl-n doesn't
  926. " actually select anything.
  927. " When the request is satisfied synchronously (e.g. the omnicompleter), we
  928. " must return to the main loop before triggering completion, so we use a 0ms
  929. " timer for that.
  930. let s:pollers.completion.id = timer_start( 0,
  931. \ function( 's:PollCompletion' ) )
  932. else
  933. " Otherwise, use our usual poll timeout
  934. call s:PollCompletion()
  935. endif
  936. endfunction
  937. function! s:ManuallyRequestCompletion() abort
  938. " Since this function is called in a mapping through the expression register
  939. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  940. " insert anything so we return an empty string.
  941. if !s:AllowedToCompleteInCurrentBuffer()
  942. return ''
  943. endif
  944. if get( b:, 'ycm_completing' )
  945. let s:force_manual = 0
  946. call s:RequestCompletion()
  947. call s:RequestSignatureHelp()
  948. endif
  949. return ''
  950. endfunction
  951. function! s:SetCompleteFunc()
  952. let &completefunc = 'youcompleteme#CompleteFunc'
  953. endfunction
  954. function! youcompleteme#CompleteFunc( findstart, base ) abort
  955. call s:ManuallyRequestCompletion()
  956. " Cancel, but silently stay in completion mode.
  957. return -2
  958. endfunction
  959. inoremap <silent> <plug>(YCMComplete) <C-r>=<SID>ManuallyRequestCompletion()<CR>
  960. function! s:RequestSemanticCompletion() abort
  961. if !s:AllowedToCompleteInCurrentBuffer()
  962. return ''
  963. endif
  964. if get( b:, 'ycm_completing' )
  965. let s:force_semantic = 1
  966. call s:StopPoller( s:pollers.completion )
  967. py3 ycm_state.SendCompletionRequest( True )
  968. if py3eval( 'ycm_state.CompletionRequestReady()' )
  969. " We can't call complete() syncrhounsouly in the TextChangedI/TextChangedP
  970. " autocommmands (it's designed to be used async only completion). The
  971. " result (somewhat oddly) is that the completion menu is shown, but ctrl-n
  972. " doesn't actually select anything. When the request is satisfied
  973. " synchronously (e.g. the omnicompleter), we must return to the main loop
  974. " before triggering completion, so we use a 0ms timer for that.
  975. let s:pollers.completion.id = timer_start(
  976. \ 0,
  977. \ function( 's:PollCompletion' ) )
  978. else
  979. " Otherwise, use our usual poll timeout
  980. call s:PollCompletion()
  981. endif
  982. endif
  983. " Since this function is called in a mapping through the expression register
  984. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  985. " insert anything so we return an empty string.
  986. return ''
  987. endfunction
  988. function! s:PollCompletion( ... )
  989. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  990. let s:pollers.completion.id = timer_start(
  991. \ s:pollers.completion.wait_milliseconds,
  992. \ function( 's:PollCompletion' ) )
  993. return
  994. endif
  995. let s:completion = py3eval( 'ycm_state.GetCompletionResponse()' )
  996. if s:current_cursor_position == getpos( '.' )
  997. call s:Complete()
  998. endif
  999. endfunction
  1000. function! s:PollResolve( item, ... )
  1001. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  1002. let s:pollers.completion.id = timer_start(
  1003. \ s:pollers.completion.wait_milliseconds,
  1004. \ function( 's:PollResolve', [ a:item ] ) )
  1005. return
  1006. endif
  1007. " Note we re-use the 'completion' request for resolves. This prevents us
  1008. " sending a completion request and a resolve request at the same time, as
  1009. " resolve requests re-use the requset data from the last completion request
  1010. " and it must not change.
  1011. " We also re-use the poller, so that any new completion request effectively
  1012. " cancels this poller.
  1013. let completion_item =
  1014. \ py3eval( 'ycm_state.GetCompletionResponse()[ "completion" ]' )
  1015. if empty( completion_item ) || empty( completion_item.info )
  1016. return
  1017. endif
  1018. call s:ShowInfoPopup( completion_item )
  1019. endfunction
  1020. function! s:ShowInfoPopup( completion_item )
  1021. let id = popup_findinfo()
  1022. if id
  1023. call popup_settext( id, split( a:completion_item.info, '\n' ) )
  1024. call popup_show( id )
  1025. endif
  1026. endfunction
  1027. function! s:ShouldUseSignatureHelp()
  1028. return py3eval( 'vimsupport.VimSupportsPopupWindows()' )
  1029. endfunction
  1030. function! s:RequestSignatureHelp()
  1031. if !s:ShouldUseSignatureHelp()
  1032. return
  1033. endif
  1034. call s:StopPoller( s:pollers.signature_help )
  1035. if py3eval( 'ycm_state.SendSignatureHelpRequest()' )
  1036. call s:PollSignatureHelp()
  1037. endif
  1038. endfunction
  1039. function! s:PollSignatureHelp( ... )
  1040. if !s:ShouldUseSignatureHelp()
  1041. return
  1042. endif
  1043. if a:0 == 0 && s:pollers.signature_help.id >= 0
  1044. " OK this is a bug. We have tried to poll for a response while the timer is
  1045. " already running. Just return and wait for the timer to fire.
  1046. return
  1047. endif
  1048. if !py3eval( 'ycm_state.SignatureHelpRequestReady()' )
  1049. let s:pollers.signature_help.id = timer_start(
  1050. \ s:pollers.signature_help.wait_milliseconds,
  1051. \ function( 's:PollSignatureHelp' ) )
  1052. return
  1053. endif
  1054. let s:signature_help = py3eval( 'ycm_state.GetSignatureHelpResponse()' )
  1055. call s:UpdateSignatureHelp()
  1056. endfunction
  1057. function! s:Complete()
  1058. " It's possible for us to be called (by our timer) when we're not _strictly_
  1059. " in insert mode. This can happen when mode is temporarily switched, e.g.
  1060. " due to Ctrl-r or Ctrl-o or a timer or something. If we're not in insert
  1061. " mode _now_ do nothing (FIXME: or should we queue a timer ?)
  1062. if count( [ 'i', 'R' ], mode() ) == 0
  1063. return
  1064. endif
  1065. if s:completion.line != line( '.' )
  1066. " Given
  1067. " scb: column where the completion starts before auto-wrapping
  1068. " cb: cursor column before auto-wrapping
  1069. " sca: column where the completion starts after auto-wrapping
  1070. " ca: cursor column after auto-wrapping
  1071. " we have
  1072. " ca - sca = cb - scb
  1073. " sca = scb + ca - cb
  1074. let s:completion.completion_start_column +=
  1075. \ col( '.' ) - s:completion.column
  1076. endif
  1077. if len( s:completion.completions )
  1078. let old_completeopt = &completeopt
  1079. set completeopt+=noselect
  1080. call complete( s:completion.completion_start_column,
  1081. \ s:completion.completions )
  1082. let &completeopt = old_completeopt
  1083. elseif pumvisible()
  1084. call s:CloseCompletionMenu()
  1085. endif
  1086. endfunction
  1087. function! s:UpdateSignatureHelp()
  1088. if !s:ShouldUseSignatureHelp()
  1089. return
  1090. endif
  1091. call py3eval(
  1092. \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' )
  1093. endfunction
  1094. function! s:ClearSignatureHelp()
  1095. if !s:ShouldUseSignatureHelp()
  1096. return
  1097. endif
  1098. call s:StopPoller( s:pollers.signature_help )
  1099. let s:signature_help = s:default_signature_help
  1100. call py3eval( 'ycm_state.ClearSignatureHelp()' )
  1101. endfunction
  1102. function! youcompleteme#ServerPid()
  1103. return py3eval( 'ycm_state.ServerPid()' )
  1104. endfunction
  1105. function! s:SetUpCommands()
  1106. command! YcmRestartServer call s:RestartServer()
  1107. command! YcmDebugInfo call s:DebugInfo()
  1108. command! -nargs=* -complete=custom,youcompleteme#LogsComplete -count=0
  1109. \ YcmToggleLogs call s:ToggleLogs( <f-count>,
  1110. \ <f-mods>,
  1111. \ <f-args>)
  1112. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  1113. \ YcmCompleter call s:CompleterCommand(<q-mods>,
  1114. \ <count>,
  1115. \ <line1>,
  1116. \ <line2>,
  1117. \ <f-args>)
  1118. command! YcmDiags call s:ShowDiagnostics()
  1119. command! -nargs=? YcmShowDetailedDiagnostic
  1120. \ call s:ShowDetailedDiagnostic( <f-args> )
  1121. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  1122. endfunction
  1123. function! s:RestartServer()
  1124. call s:SetUpOptions()
  1125. py3 ycm_state.RestartServer()
  1126. call s:StopPoller( s:pollers.receive_messages )
  1127. call s:StopPoller( s:pollers.command )
  1128. call s:ClearSignatureHelp()
  1129. call s:StopPoller( s:pollers.server_ready )
  1130. let s:pollers.server_ready.id = timer_start(
  1131. \ s:pollers.server_ready.wait_milliseconds,
  1132. \ function( 's:PollServerReady' ) )
  1133. endfunction
  1134. function! s:DebugInfo()
  1135. echom "Printing YouCompleteMe debug information..."
  1136. let debug_info = py3eval( 'ycm_state.DebugInfo()' )
  1137. echom '-- Resolve completions:'
  1138. \ ( s:resolve_completions == s:RESOLVE_ON_DEMAND ? 'On demand' :
  1139. \ s:resolve_completions == s:RESOLVE_UP_FRONT ? 'Up front' :
  1140. \ 'Never' )
  1141. for line in split( debug_info, "\n" )
  1142. echom '-- ' . line
  1143. endfor
  1144. endfunction
  1145. function! s:ToggleLogs( count, ... )
  1146. py3 ycm_state.ToggleLogs( vimsupport.GetIntValue( 'a:count' ),
  1147. \ *vim.eval( 'a:000' ) )
  1148. endfunction
  1149. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  1150. return join( py3eval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  1151. endfunction
  1152. function! youcompleteme#GetCommandResponse( ... ) abort
  1153. if !s:AllowedToCompleteInCurrentBuffer()
  1154. return ''
  1155. endif
  1156. if !get( b:, 'ycm_completing' )
  1157. return ''
  1158. endif
  1159. return py3eval( 'ycm_state.GetCommandResponse( vim.eval( "a:000" ) )' )
  1160. endfunction
  1161. function! youcompleteme#GetCommandResponseAsync( callback, ... ) abort
  1162. if !s:AllowedToCompleteInCurrentBuffer()
  1163. eval a:callback( '' )
  1164. return
  1165. endif
  1166. if !get( b:, 'ycm_completing' )
  1167. eval a:callback( '' )
  1168. return
  1169. endif
  1170. let request_id = py3eval(
  1171. \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' )
  1172. let s:pollers.command.requests[ request_id ] = {
  1173. \ 'response_func': 'StringResponse',
  1174. \ 'callback': a:callback
  1175. \ }
  1176. if s:pollers.command.id == -1
  1177. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1178. \ function( 's:PollCommands' ) )
  1179. endif
  1180. endfunction
  1181. function! youcompleteme#GetRawCommandResponseAsync( callback, ... ) abort
  1182. if !s:AllowedToCompleteInCurrentBuffer()
  1183. eval a:callback( { 'error': 'ycm not allowed in buffer' } )
  1184. return
  1185. endif
  1186. if !get( b:, 'ycm_completing' )
  1187. eval a:callback( { 'error': 'ycm disabled in buffer' } )
  1188. return
  1189. endif
  1190. let request_id = py3eval(
  1191. \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' )
  1192. let s:pollers.command.requests[ request_id ] = {
  1193. \ 'response_func': 'Response',
  1194. \ 'callback': a:callback
  1195. \ }
  1196. if s:pollers.command.id == -1
  1197. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1198. \ function( 's:PollCommands' ) )
  1199. endif
  1200. endfunction
  1201. function! s:PollCommands( timer_id ) abort
  1202. " Clear the timer id before calling the callback, as the callback might fire
  1203. " more requests
  1204. call s:StopPoller( s:pollers.command )
  1205. " Must copy the requests because this loop is likely to modify it
  1206. let requests = copy( s:pollers.command.requests )
  1207. let poll_again = 0
  1208. for request_id in keys( requests )
  1209. let request = requests[ request_id ]
  1210. if py3eval( 'ycm_state.GetCommandRequest( int( vim.eval( "request_id" ) ) )'
  1211. \ . 'is None' )
  1212. " Possible in case of race conditions and things like RestartServer
  1213. " But particualrly in the tests
  1214. let result = v:none
  1215. elseif !py3eval( 'ycm_state.GetCommandRequest( '
  1216. \ . 'int( vim.eval( "request_id" ) ) ).Done()' )
  1217. " Not ready yet, poll again and skip this one for now
  1218. let poll_again = 1
  1219. continue
  1220. else
  1221. let result = py3eval( 'ycm_state.GetCommandRequest( '
  1222. \ . 'int( vim.eval( "request_id" ) ) ).'
  1223. \ . request.response_func
  1224. \ . '()' )
  1225. endif
  1226. " This request is done
  1227. call remove( s:pollers.command.requests, request_id )
  1228. py3 ycm_state.FlushCommandRequest( vim.eval( "request_id" ) )
  1229. call request[ 'callback' ]( result )
  1230. endfor
  1231. if poll_again && s:pollers.command.id == -1
  1232. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1233. \ function( 's:PollCommands' ) )
  1234. endif
  1235. endfunction
  1236. function! s:CompleterCommand( mods, count, line1, line2, ... )
  1237. py3 ycm_state.SendCommandRequest(
  1238. \ vim.eval( 'a:000' ),
  1239. \ vim.eval( 'a:mods' ),
  1240. \ vimsupport.GetBoolValue( 'a:count != -1' ),
  1241. \ vimsupport.GetIntValue( 'a:line1' ),
  1242. \ vimsupport.GetIntValue( 'a:line2' ) )
  1243. endfunction
  1244. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  1245. return join( py3eval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  1246. endfunction
  1247. function! youcompleteme#GetDefinedSubcommands()
  1248. if !s:AllowedToCompleteInCurrentBuffer()
  1249. return []
  1250. endif
  1251. if !exists( 'b:ycm_completing' )
  1252. return []
  1253. endif
  1254. return py3eval( 'ycm_state.GetDefinedSubcommands()' )
  1255. endfunction
  1256. function! youcompleteme#OpenGoToList()
  1257. py3 vimsupport.PostVimMessage(
  1258. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  1259. \ "Do NOT use it.'" )
  1260. py3 vimsupport.OpenQuickFixList( True, True )
  1261. endfunction
  1262. function! s:ShowDiagnostics()
  1263. py3 ycm_state.ShowDiagnostics()
  1264. endfunction
  1265. function! s:ShowDetailedDiagnostic( ... )
  1266. if ( a:0 && a:1 == 'popup' )
  1267. \ || get( g:, 'ycm_show_detailed_diag_in_popup', 0 )
  1268. py3 ycm_state.ShowDetailedDiagnostic( True )
  1269. else
  1270. py3 ycm_state.ShowDetailedDiagnostic( False )
  1271. endif
  1272. endfunction
  1273. function! s:ForceCompileAndDiagnostics()
  1274. py3 ycm_state.ForceCompileAndDiagnostics()
  1275. endfunction
  1276. if exists( '*popup_atcursor' )
  1277. function s:Hover()
  1278. if !py3eval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  1279. " Cancel the autocommand if it happens to have been set
  1280. call s:DisableAutoHover()
  1281. return
  1282. endif
  1283. if !has_key( b:, 'ycm_hover' )
  1284. let cmds = youcompleteme#GetDefinedSubcommands()
  1285. if index( cmds, 'GetHover' ) >= 0
  1286. let b:ycm_hover = {
  1287. \ 'command': 'GetHover',
  1288. \ 'syntax': 'markdown',
  1289. \ }
  1290. elseif index( cmds, 'GetDoc' ) >= 0
  1291. let b:ycm_hover = {
  1292. \ 'command': 'GetDoc',
  1293. \ 'syntax': '',
  1294. \ }
  1295. elseif index( cmds, 'GetType' ) >= 0
  1296. let b:ycm_hover = {
  1297. \ 'command': 'GetType',
  1298. \ 'syntax': &syntax,
  1299. \ }
  1300. else
  1301. let b:ycm_hover = {}
  1302. endif
  1303. endif
  1304. if empty( b:ycm_hover )
  1305. return
  1306. endif
  1307. call youcompleteme#GetCommandResponseAsync(
  1308. \ function( 's:ShowHoverResult' ),
  1309. \ b:ycm_hover.command )
  1310. endfunction
  1311. function! s:ShowHoverResult( response )
  1312. call popup_hide( s:cursorhold_popup )
  1313. if empty( a:response )
  1314. return
  1315. endif
  1316. " Try to position the popup at the cursor, but avoid wrapping. If the
  1317. " longest line is > screen width (&columns), then we just have to wrap, and
  1318. " place the popup at the leftmost column.
  1319. "
  1320. " Find the longest line (FIXME: probably doesn't work well for multi-byte)
  1321. let lines = split( a:response, "\n" )
  1322. let len = max( map( copy( lines ), "len( v:val )" ) )
  1323. let wrap = 0
  1324. let col = 'cursor'
  1325. " max width is screen columns minus x padding (2)
  1326. if len >= (&columns - 2)
  1327. " There's at least one line > our max - enable word wrap and draw the
  1328. " popup at the leftmost column
  1329. let col = 1
  1330. let wrap = 1
  1331. endif
  1332. let popup_params = {
  1333. \ 'col': col,
  1334. \ 'wrap': wrap,
  1335. \ 'padding': [ 0, 1, 0, 1 ],
  1336. \ 'moved': 'word',
  1337. \ 'maxwidth': &columns,
  1338. \ 'close': 'click',
  1339. \ 'fixed': 0,
  1340. \ }
  1341. if has_key( b:ycm_hover, 'popup_params' )
  1342. let popup_params = extend( copy( popup_params ),
  1343. \ b:ycm_hover.popup_params )
  1344. endif
  1345. let s:cursorhold_popup = popup_atcursor( lines, popup_params )
  1346. call setbufvar( winbufnr( s:cursorhold_popup ),
  1347. \ '&syntax',
  1348. \ b:ycm_hover.syntax )
  1349. endfunction
  1350. function! s:ToggleHover()
  1351. let pos = popup_getpos( s:cursorhold_popup )
  1352. if !empty( pos ) && pos.visible
  1353. call popup_hide( s:cursorhold_popup )
  1354. let s:cursorhold_popup = -1
  1355. " Diable the auto-trigger until the next cursor movement.
  1356. call s:DisableAutoHover()
  1357. augroup YCMHover
  1358. autocmd! CursorMoved <buffer>
  1359. autocmd CursorMoved <buffer> call s:EnableAutoHover()
  1360. augroup END
  1361. else
  1362. call s:Hover()
  1363. endif
  1364. endfunction
  1365. let s:enable_hover = 1
  1366. nnoremap <silent> <plug>(YCMHover) :<C-u>call <SID>ToggleHover()<CR>
  1367. else
  1368. " Don't break people's mappings if this feature is disabled, just do nothing.
  1369. nnoremap <silent> <plug>(YCMHover) <Nop>
  1370. endif
  1371. function! youcompleteme#Test_GetPollers()
  1372. return s:pollers
  1373. endfunction
  1374. function! s:ToggleSignatureHelp()
  1375. call py3eval( 'ycm_state.ToggleSignatureHelp()' )
  1376. " Because we do this in a insert-mode mapping, we return empty string to
  1377. " insert/type nothing
  1378. return ''
  1379. endfunction
  1380. silent! inoremap <silent> <plug>(YCMToggleSignatureHelp)
  1381. \ <C-r>=<SID>ToggleSignatureHelp()<CR>
  1382. function! s:ToggleInlayHints()
  1383. let b:ycm_enable_inlay_hints =
  1384. \ !get( b:,
  1385. \ 'ycm_enable_inlay_hints',
  1386. \ get( g:, 'ycm_enable_inlay_hints' ) )
  1387. if !b:ycm_enable_inlay_hints && s:enable_inlay_hints
  1388. py3 ycm_state.CurrentBuffer().inlay_hints.Clear()
  1389. else
  1390. call s:UpdateInlayHints( bufnr(), 0, 1 )
  1391. endif
  1392. endfunction
  1393. silent! nnoremap <silent> <plug>(YCMToggleInlayHints)
  1394. \ <cmd>call <SID>ToggleInlayHints()<CR>
  1395. " This is basic vim plugin boilerplate
  1396. let &cpo = s:save_cpo
  1397. unlet s:save_cpo