youcompleteme.vim 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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: Neovim reports v:version as 800, which is garbage. For some features
  21. " that are supported 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. " completeopt 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 enabled - 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. # resolve 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 resolve 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. resolve 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. if exists( '##WinResized' )
  596. autocmd WinResized <buffer> call popup_close( s:cursorhold_popup )
  597. endif
  598. if exists( '##WinScrolled' )
  599. autocmd WinScrolled <buffer> call popup_close( s:cursorhold_popup )
  600. endif
  601. augroup END
  602. endif
  603. endfunction
  604. function! s:DisableAutoHover()
  605. augroup YcmBufHover
  606. autocmd! * <buffer>
  607. augroup END
  608. endfunction
  609. function! s:OnFileTypeSet()
  610. " The contents of the command-line window are empty when the filetype is set
  611. " for the first time. Users should never change its filetype so we only rely
  612. " on the CmdwinEnter event for that window.
  613. if !empty( getcmdwintype() )
  614. return
  615. endif
  616. if !s:AllowedToCompleteInCurrentBuffer()
  617. return
  618. endif
  619. call s:SetUpCompleteopt()
  620. call s:EnableCompletingInCurrentBuffer()
  621. call s:StartMessagePoll()
  622. call s:EnableAutoHover()
  623. py3 ycm_state.OnFileTypeSet()
  624. call s:OnFileReadyToParse( 1 )
  625. endfunction
  626. function! s:OnFileSave()
  627. let buffer_number = str2nr( expand( '<abuf>' ) )
  628. if !s:AllowedToCompleteInBuffer( buffer_number )
  629. return
  630. endif
  631. py3 ycm_state.OnFileSave( vimsupport.GetIntValue( 'buffer_number' ) )
  632. endfunction
  633. function! s:AbortAutohoverRequest() abort
  634. if g:ycm_auto_hover ==# 'CursorHold' && s:enable_hover
  635. let requests = copy( s:pollers.command.requests )
  636. for request_id in keys( requests )
  637. let request = requests[ request_id ]
  638. if request.origin == 'autohover'
  639. call remove( s:pollers.command.requests, request_id )
  640. call request.callback( '' )
  641. endif
  642. endfor
  643. endif
  644. endfunction
  645. function! s:OnBufferEnter()
  646. call s:StartMessagePoll()
  647. if !s:VisitedBufferRequiresReparse()
  648. return
  649. endif
  650. call s:AbortAutohoverRequest()
  651. call s:SetUpCompleteopt()
  652. call s:EnableCompletingInCurrentBuffer()
  653. py3 ycm_state.UpdateMatches()
  654. py3 ycm_state.OnBufferVisit()
  655. " Last parse may be outdated because of changes from other buffers. Force a
  656. " new parse.
  657. call s:OnFileReadyToParse( 1 )
  658. endfunction
  659. function! s:OnBufferUnload()
  660. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  661. " it as a true number for the getbufvar function.
  662. let buffer_number = str2nr( expand( '<abuf>' ) )
  663. if !s:AllowedToCompleteInBuffer( buffer_number )
  664. return
  665. endif
  666. py3 ycm_state.OnBufferUnload( vimsupport.GetIntValue( 'buffer_number' ) )
  667. endfunction
  668. function! s:PollServerReady( timer_id )
  669. if !py3eval( 'ycm_state.IsServerAlive()' )
  670. py3 ycm_state.NotifyUserIfServerCrashed()
  671. " Server crashed. Don't poll it again.
  672. return
  673. endif
  674. if !py3eval( 'ycm_state.CheckIfServerIsReady()' )
  675. let s:pollers.server_ready.id = timer_start(
  676. \ s:pollers.server_ready.wait_milliseconds,
  677. \ function( 's:PollServerReady' ) )
  678. return
  679. endif
  680. call s:OnFileTypeSet()
  681. endfunction
  682. function! s:OnFileReadyToParse( ... )
  683. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  684. " FileReadyToParse event notification, whether the buffer has changed or not;
  685. " effectively forcing a parse of the buffer. Default is 0.
  686. let force_parsing = a:0 > 0 && a:1
  687. " We only want to send a new FileReadyToParse event notification if the buffer
  688. " has changed since the last time we sent one, or if forced.
  689. if force_parsing || py3eval( "ycm_state.NeedsReparse()" )
  690. " We switched buffers or something, so clear.
  691. " FIXME: sig help should be buffer local?
  692. call s:ClearSignatureHelp()
  693. py3 ycm_state.OnFileReadyToParse()
  694. call s:StopPoller( s:pollers.file_parse_response )
  695. let s:pollers.file_parse_response.id = timer_start(
  696. \ s:pollers.file_parse_response.wait_milliseconds,
  697. \ function( 's:PollFileParseResponse' ) )
  698. call s:UpdateSemanticHighlighting( bufnr(), 1, 0 )
  699. call s:UpdateInlayHints( bufnr(), 1, 0 )
  700. endif
  701. endfunction
  702. function! s:UpdateSemanticHighlighting( bufnr, force, redraw_anyway ) abort
  703. call s:StopPoller( s:pollers.semantic_highlighting )
  704. if !s:is_neovim &&
  705. \ get( b:, 'ycm_enable_semantic_highlighting',
  706. \ get( g:, 'ycm_enable_semantic_highlighting', 0 ) )
  707. if py3eval(
  708. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).'
  709. \ . 'semantic_highlighting.Request( '
  710. \ . ' force=int( vim.eval( "a:force" ) ) )' )
  711. let s:pollers.semantic_highlighting.id = timer_start(
  712. \ s:pollers.semantic_highlighting.wait_milliseconds,
  713. \ function( 's:PollSemanticHighlighting', [ a:bufnr ] ) )
  714. elseif a:redraw_anyway
  715. py3 ycm_state.Buffer(
  716. \ int( vim.eval( "a:bufnr" ) ) ).semantic_highlighting.Refresh()
  717. endif
  718. endif
  719. endfunction
  720. function s:ShouldUseInlayHintsNow( bufnr )
  721. return s:enable_inlay_hints &&
  722. \ getbufvar( a:bufnr, 'ycm_enable_inlay_hints',
  723. \ get( g:, 'ycm_enable_inlay_hints', 0 ) )
  724. endfunction
  725. function! s:UpdateInlayHints( bufnr, force, redraw_anyway ) abort
  726. call s:StopPoller( s:pollers.inlay_hints )
  727. if s:ShouldUseInlayHintsNow( a:bufnr )
  728. if py3eval(
  729. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).'
  730. \ . 'inlay_hints.Request( force=int( vim.eval( "a:force" ) ) )' )
  731. let s:pollers.inlay_hints.id = timer_start(
  732. \ s:pollers.inlay_hints.wait_milliseconds,
  733. \ function( 's:PollInlayHints', [ a:bufnr ] ) )
  734. elseif a:redraw_anyway
  735. py3 ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) ).inlay_hints.Refresh()
  736. endif
  737. endif
  738. endfunction
  739. function! s:PollFileParseResponse( ... )
  740. if !py3eval( "ycm_state.FileParseRequestReady()" )
  741. let s:pollers.file_parse_response.id = timer_start(
  742. \ s:pollers.file_parse_response.wait_milliseconds,
  743. \ function( 's:PollFileParseResponse' ) )
  744. return
  745. endif
  746. py3 ycm_state.HandleFileParseRequest()
  747. if py3eval( "ycm_state.ShouldResendFileParseRequest()" )
  748. call s:OnFileReadyToParse( 1 )
  749. endif
  750. endfunction
  751. function! s:PollSemanticHighlighting( bufnr, ... ) abort
  752. return s:PollScrollable( a:bufnr, 'semantic_highlighting' )
  753. endfunction
  754. function! s:PollInlayHints( bufnr, ... ) abort
  755. return s:PollScrollable( a:bufnr, 'inlay_hints' )
  756. endfunction
  757. function! s:PollScrollable( bufnr, scrollable, ... ) abort
  758. if !py3eval(
  759. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )'
  760. \ . '.' . a:scrollable . '.Ready()' )
  761. let s:pollers[a:scrollable].id = timer_start(
  762. \ s:pollers[a:scrollable].wait_milliseconds,
  763. \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) )
  764. elseif ! py3eval(
  765. \ 'ycm_state.Buffer( int( vim.eval( "a:bufnr" ) ) )'
  766. \ . '.' . a:scrollable . '.Update()' )
  767. let s:pollers[ a:scrollable ].id = timer_start(
  768. \ s:pollers[ a:scrollable ].wait_milliseconds,
  769. \ function( 's:PollScrollable', [ a:bufnr, a:scrollable ] ) )
  770. endif
  771. endfunction
  772. function! s:SendKeys( keys )
  773. " By default keys are added to the end of the typeahead buffer. If there are
  774. " already keys in the buffer, they will be processed first and may change
  775. " the state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in
  776. " normal mode instead of insert mode or <C-e> outside of completion mode).
  777. " We avoid that by inserting the keys at the start of the typeahead buffer
  778. " with the 'i' option. Also, we don't want the keys to be remapped to
  779. " something else so we add the 'n' option.
  780. call feedkeys( a:keys, 'in' )
  781. endfunction
  782. function! s:CloseCompletionMenu()
  783. if pumvisible()
  784. call s:SendKeys( "\<C-e>" )
  785. endif
  786. endfunction
  787. function! s:OnInsertChar()
  788. if !s:AllowedToCompleteInCurrentBuffer()
  789. return
  790. endif
  791. let s:last_char_inserted_by_user = v:true
  792. endfunction
  793. function! s:StopCompletion( key )
  794. call s:StopPoller( s:pollers.completion )
  795. call s:ClearSignatureHelp()
  796. if pumvisible()
  797. let s:completion_stopped = 1
  798. return "\<C-y>"
  799. endif
  800. return a:key
  801. endfunction
  802. function! s:OnCursorMovedNormalMode()
  803. if !s:AllowedToCompleteInCurrentBuffer()
  804. return
  805. endif
  806. call s:AbortAutohoverRequest()
  807. py3 ycm_state.OnCursorMoved()
  808. endfunction
  809. function! s:OnWinScrolled()
  810. if !s:AllowedToCompleteInCurrentBuffer()
  811. return
  812. endif
  813. let bufnr = winbufnr( expand( '<afile>' ) )
  814. call s:UpdateSemanticHighlighting( bufnr, 0, 0 )
  815. call s:UpdateInlayHints( bufnr, 0, 0 )
  816. endfunction
  817. function! s:OnTextChangedNormalMode()
  818. if !s:AllowedToCompleteInCurrentBuffer()
  819. return
  820. endif
  821. call s:OnFileReadyToParse()
  822. endfunction
  823. function! s:OnTextChangedInsertMode( popup_is_visible )
  824. if !s:AllowedToCompleteInCurrentBuffer()
  825. return
  826. endif
  827. if a:popup_is_visible && !s:last_char_inserted_by_user
  828. " If the last "input" wasn't from a user typing (i.e. didn't come from
  829. " InsertCharPre, then ignore this change in the text. This prevents ctrl-n
  830. " or tab from causing us to re-filter the list based on the now-selected
  831. " item.
  832. return
  833. endif
  834. let s:current_cursor_position = getpos( '.' )
  835. if s:completion_stopped
  836. let s:completion_stopped = 0
  837. let s:completion = s:default_completion
  838. return
  839. endif
  840. call s:IdentifierFinishedOperations()
  841. " We have to make sure we correctly leave semantic mode even when the user
  842. " inserts something like a "operator[]" candidate string which fails
  843. " CurrentIdentifierFinished check.
  844. if s:force_semantic && !py3eval( 'base.LastEnteredCharIsIdentifierChar()' )
  845. let s:force_semantic = 0
  846. let s:force_manual = 0
  847. endif
  848. if get( b:, 'ycm_completing' ) &&
  849. \ ( g:ycm_auto_trigger || s:force_semantic || s:force_manual ) &&
  850. \ !s:InsideCommentOrStringAndShouldStop() &&
  851. \ !s:OnBlankLine()
  852. call s:RequestCompletion()
  853. call s:RequestSignatureHelp()
  854. endif
  855. py3 ycm_state.OnCursorMoved()
  856. if g:ycm_autoclose_preview_window_after_completion
  857. call s:ClosePreviewWindowIfNeeded()
  858. endif
  859. endfunction
  860. function! s:OnInsertEnter() abort
  861. let s:current_cursor_position = getpos( '.' )
  862. py3 ycm_state.OnInsertEnter()
  863. if s:ShouldUseInlayHintsNow( bufnr() ) &&
  864. \ get(g:, 'ycm_clear_inlay_hints_in_insert_mode' )
  865. py3 ycm_state.CurrentBuffer().inlay_hints.Clear()
  866. endif
  867. endfunction
  868. function! s:OnInsertLeave()
  869. if !s:AllowedToCompleteInCurrentBuffer()
  870. return
  871. endif
  872. let s:last_char_inserted_by_user = v:false
  873. call s:StopPoller( s:pollers.completion )
  874. let s:force_semantic = 0
  875. let s:force_manual = 0
  876. let s:completion = s:default_completion
  877. call s:OnFileReadyToParse()
  878. py3 ycm_state.OnInsertLeave()
  879. if g:ycm_autoclose_preview_window_after_completion ||
  880. \ g:ycm_autoclose_preview_window_after_insertion
  881. call s:ClosePreviewWindowIfNeeded()
  882. endif
  883. call s:ClearSignatureHelp()
  884. if s:ShouldUseInlayHintsNow( bufnr() )
  885. \ && get( g:, 'ycm_clear_inlay_hints_in_insert_mode' )
  886. " We cleared inlay hints on insert enter
  887. py3 ycm_state.CurrentBuffer().inlay_hints.Refresh()
  888. endif
  889. endfunction
  890. function! s:ClosePreviewWindowIfNeeded()
  891. let current_buffer_name = bufname('')
  892. " We don't want to try to close the preview window in special buffers like
  893. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  894. " with '['.
  895. if current_buffer_name[ 0 ] == '['
  896. return
  897. endif
  898. " This command does the actual closing of the preview window. If no preview
  899. " window is shown, nothing happens.
  900. pclose
  901. endfunction
  902. function! s:IdentifierFinishedOperations()
  903. if !py3eval( 'base.CurrentIdentifierFinished()' )
  904. return
  905. endif
  906. py3 ycm_state.OnCurrentIdentifierFinished()
  907. let s:force_semantic = 0
  908. let s:force_manual = 0
  909. let s:completion = s:default_completion
  910. endfunction
  911. " Returns 1 when inside comment and 2 when inside string
  912. function! s:InsideCommentOrString()
  913. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  914. " in insert mode when this func is called.
  915. let syntax_group = synIDattr(
  916. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  917. if stridx(syntax_group, 'Comment') > -1
  918. return 1
  919. endif
  920. if stridx(syntax_group, 'String') > -1
  921. return 2
  922. endif
  923. return 0
  924. endfunction
  925. function! s:InsideCommentOrStringAndShouldStop()
  926. let retval = s:InsideCommentOrString()
  927. let inside_comment = retval == 1
  928. let inside_string = retval == 2
  929. if inside_comment && g:ycm_complete_in_comments ||
  930. \ inside_string && g:ycm_complete_in_strings
  931. return 0
  932. endif
  933. return retval
  934. endfunction
  935. function! s:OnBlankLine()
  936. return py3eval( 'not vim.current.line or vim.current.line.isspace()' )
  937. endfunction
  938. function! s:RequestCompletion()
  939. call s:StopPoller( s:pollers.completion )
  940. py3 ycm_state.SendCompletionRequest(
  941. \ vimsupport.GetBoolValue( 's:force_semantic' ) )
  942. if py3eval( 'ycm_state.CompletionRequestReady()' )
  943. " We can't call complete() synchronously in the TextChangedI/TextChangedP
  944. " autocommands (it's designed to be used async only completion). The result
  945. " (somewhat oddly) is that the completion menu is shown, but ctrl-n doesn't
  946. " actually select anything.
  947. " When the request is satisfied synchronously (e.g. the omnicompleter), we
  948. " must return to the main loop before triggering completion, so we use a 0ms
  949. " timer for that.
  950. let s:pollers.completion.id = timer_start( 0,
  951. \ function( 's:PollCompletion' ) )
  952. else
  953. " Otherwise, use our usual poll timeout
  954. call s:PollCompletion()
  955. endif
  956. endfunction
  957. function! s:ManuallyRequestCompletion() abort
  958. " Since this function is called in a mapping through the expression register
  959. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  960. " insert anything so we return an empty string.
  961. if !s:AllowedToCompleteInCurrentBuffer()
  962. return ''
  963. endif
  964. if get( b:, 'ycm_completing' )
  965. let s:force_manual = 0
  966. call s:RequestCompletion()
  967. call s:RequestSignatureHelp()
  968. endif
  969. return ''
  970. endfunction
  971. function! s:SetCompleteFunc()
  972. let &completefunc = 'youcompleteme#CompleteFunc'
  973. endfunction
  974. function! youcompleteme#CompleteFunc( findstart, base ) abort
  975. call s:ManuallyRequestCompletion()
  976. " Cancel, but silently stay in completion mode.
  977. return -2
  978. endfunction
  979. inoremap <silent> <plug>(YCMComplete) <C-r>=<SID>ManuallyRequestCompletion()<CR>
  980. function! s:RequestSemanticCompletion() abort
  981. if !s:AllowedToCompleteInCurrentBuffer()
  982. return ''
  983. endif
  984. if get( b:, 'ycm_completing' )
  985. let s:force_semantic = 1
  986. let s:current_cursor_position = getpos( '.' )
  987. call s:StopPoller( s:pollers.completion )
  988. py3 ycm_state.SendCompletionRequest( True )
  989. if py3eval( 'ycm_state.CompletionRequestReady()' )
  990. " We can't call complete() synchronously in the TextChangedI/TextChangedP
  991. " autocommands (it's designed to be used async only completion). The
  992. " result (somewhat oddly) is that the completion menu is shown, but ctrl-n
  993. " doesn't actually select anything. When the request is satisfied
  994. " synchronously (e.g. the omnicompleter), we must return to the main loop
  995. " before triggering completion, so we use a 0ms timer for that.
  996. let s:pollers.completion.id = timer_start(
  997. \ 0,
  998. \ function( 's:PollCompletion' ) )
  999. else
  1000. " Otherwise, use our usual poll timeout
  1001. call s:PollCompletion()
  1002. endif
  1003. endif
  1004. " Since this function is called in a mapping through the expression register
  1005. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  1006. " insert anything so we return an empty string.
  1007. return ''
  1008. endfunction
  1009. function! s:PollCompletion( ... )
  1010. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  1011. let s:pollers.completion.id = timer_start(
  1012. \ s:pollers.completion.wait_milliseconds,
  1013. \ function( 's:PollCompletion' ) )
  1014. return
  1015. endif
  1016. let s:completion = py3eval( 'ycm_state.GetCompletionResponse()' )
  1017. if s:current_cursor_position == getpos( '.' )
  1018. call s:Complete()
  1019. endif
  1020. endfunction
  1021. function! s:PollResolve( item, ... )
  1022. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  1023. let s:pollers.completion.id = timer_start(
  1024. \ s:pollers.completion.wait_milliseconds,
  1025. \ function( 's:PollResolve', [ a:item ] ) )
  1026. return
  1027. endif
  1028. " Note we re-use the 'completion' request for resolves. This prevents us
  1029. " sending a completion request and a resolve request at the same time, as
  1030. " resolve requests re-use the request data from the last completion request
  1031. " and it must not change.
  1032. " We also re-use the poller, so that any new completion request effectively
  1033. " cancels this poller.
  1034. let completion_item =
  1035. \ py3eval( 'ycm_state.GetCompletionResponse()[ "completion" ]' )
  1036. if empty( completion_item ) || empty( completion_item.info )
  1037. return
  1038. endif
  1039. call s:ShowInfoPopup( completion_item )
  1040. endfunction
  1041. function! s:ShowInfoPopup( completion_item )
  1042. let id = popup_findinfo()
  1043. if id
  1044. call popup_settext( id, split( a:completion_item.info, '\n' ) )
  1045. call popup_show( id )
  1046. endif
  1047. endfunction
  1048. function! s:ShouldUseSignatureHelp()
  1049. return py3eval( 'vimsupport.VimSupportsPopupWindows()' )
  1050. endfunction
  1051. function! s:RequestSignatureHelp()
  1052. if !s:ShouldUseSignatureHelp()
  1053. return
  1054. endif
  1055. call s:StopPoller( s:pollers.signature_help )
  1056. if py3eval( 'ycm_state.SendSignatureHelpRequest()' )
  1057. call s:PollSignatureHelp()
  1058. endif
  1059. endfunction
  1060. function! s:PollSignatureHelp( ... )
  1061. if !s:ShouldUseSignatureHelp()
  1062. return
  1063. endif
  1064. if a:0 == 0 && s:pollers.signature_help.id >= 0
  1065. " OK this is a bug. We have tried to poll for a response while the timer is
  1066. " already running. Just return and wait for the timer to fire.
  1067. return
  1068. endif
  1069. if !py3eval( 'ycm_state.SignatureHelpRequestReady()' )
  1070. let s:pollers.signature_help.id = timer_start(
  1071. \ s:pollers.signature_help.wait_milliseconds,
  1072. \ function( 's:PollSignatureHelp' ) )
  1073. return
  1074. endif
  1075. let s:signature_help = py3eval( 'ycm_state.GetSignatureHelpResponse()' )
  1076. call s:UpdateSignatureHelp()
  1077. endfunction
  1078. function! s:Complete()
  1079. " It's possible for us to be called (by our timer) when we're not _strictly_
  1080. " in insert mode. This can happen when mode is temporarily switched, e.g.
  1081. " due to Ctrl-r or Ctrl-o or a timer or something. If we're not in insert
  1082. " mode _now_ do nothing (FIXME: or should we queue a timer ?)
  1083. if count( [ 'i', 'R' ], mode() ) == 0
  1084. return
  1085. endif
  1086. if s:completion.line != line( '.' )
  1087. " Given
  1088. " scb: column where the completion starts before auto-wrapping
  1089. " cb: cursor column before auto-wrapping
  1090. " sca: column where the completion starts after auto-wrapping
  1091. " ca: cursor column after auto-wrapping
  1092. " we have
  1093. " ca - sca = cb - scb
  1094. " sca = scb + ca - cb
  1095. let s:completion.completion_start_column +=
  1096. \ col( '.' ) - s:completion.column
  1097. endif
  1098. if len( s:completion.completions )
  1099. let old_completeopt = &completeopt
  1100. setlocal completeopt+=noselect
  1101. call complete( s:completion.completion_start_column,
  1102. \ s:completion.completions )
  1103. let &completeopt = old_completeopt
  1104. elseif pumvisible()
  1105. call s:CloseCompletionMenu()
  1106. endif
  1107. endfunction
  1108. function! s:UpdateSignatureHelp()
  1109. if !s:ShouldUseSignatureHelp()
  1110. return
  1111. endif
  1112. call py3eval(
  1113. \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' )
  1114. endfunction
  1115. function! s:ClearSignatureHelp()
  1116. if !s:ShouldUseSignatureHelp()
  1117. return
  1118. endif
  1119. call s:StopPoller( s:pollers.signature_help )
  1120. let s:signature_help = s:default_signature_help
  1121. call py3eval( 'ycm_state.ClearSignatureHelp()' )
  1122. endfunction
  1123. function! youcompleteme#ServerPid()
  1124. return py3eval( 'ycm_state.ServerPid()' )
  1125. endfunction
  1126. function! s:SetUpCommands()
  1127. command! YcmRestartServer call s:RestartServer()
  1128. command! YcmDebugInfo call s:DebugInfo()
  1129. command! -nargs=* -complete=custom,youcompleteme#LogsComplete -count=0
  1130. \ YcmToggleLogs call s:ToggleLogs( <f-count>,
  1131. \ <f-mods>,
  1132. \ <f-args>)
  1133. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  1134. \ YcmCompleter call s:CompleterCommand(<q-mods>,
  1135. \ <count>,
  1136. \ <line1>,
  1137. \ <line2>,
  1138. \ <f-args>)
  1139. command! YcmDiags call s:ShowDiagnostics()
  1140. command! -nargs=? YcmShowDetailedDiagnostic
  1141. \ call s:ShowDetailedDiagnostic( <f-args> )
  1142. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  1143. endfunction
  1144. function! s:RestartServer()
  1145. call s:SetUpOptions()
  1146. py3 ycm_state.RestartServer()
  1147. call s:StopPoller( s:pollers.receive_messages )
  1148. call s:StopPoller( s:pollers.command )
  1149. call s:ClearSignatureHelp()
  1150. call s:StopPoller( s:pollers.server_ready )
  1151. let s:pollers.server_ready.id = timer_start(
  1152. \ s:pollers.server_ready.wait_milliseconds,
  1153. \ function( 's:PollServerReady' ) )
  1154. endfunction
  1155. function! s:DebugInfo()
  1156. echom "Printing YouCompleteMe debug information..."
  1157. let debug_info = py3eval( 'ycm_state.DebugInfo()' )
  1158. echom '-- Resolve completions:'
  1159. \ ( s:resolve_completions == s:RESOLVE_ON_DEMAND ? 'On demand' :
  1160. \ s:resolve_completions == s:RESOLVE_UP_FRONT ? 'Up front' :
  1161. \ 'Never' )
  1162. for line in split( debug_info, "\n" )
  1163. echom '-- ' . line
  1164. endfor
  1165. endfunction
  1166. function! s:ToggleLogs( count, ... )
  1167. py3 ycm_state.ToggleLogs( vimsupport.GetIntValue( 'a:count' ),
  1168. \ *vim.eval( 'a:000' ) )
  1169. endfunction
  1170. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  1171. return join( py3eval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  1172. endfunction
  1173. function! youcompleteme#GetCommandResponse( ... ) abort
  1174. if !s:AllowedToCompleteInCurrentBuffer()
  1175. return ''
  1176. endif
  1177. if !get( b:, 'ycm_completing' )
  1178. return ''
  1179. endif
  1180. return py3eval( 'ycm_state.GetCommandResponse( vim.eval( "a:000" ) )' )
  1181. endfunction
  1182. function! s:GetCommandResponseAsyncImpl( callback, origin, ... ) abort
  1183. let request_id = py3eval(
  1184. \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' )
  1185. let s:pollers.command.requests[ request_id ] = {
  1186. \ 'response_func': 'StringResponse',
  1187. \ 'origin': a:origin,
  1188. \ 'callback': a:callback
  1189. \ }
  1190. if s:pollers.command.id == -1
  1191. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1192. \ function( 's:PollCommands' ) )
  1193. endif
  1194. endfunction
  1195. function! youcompleteme#GetCommandResponseAsync( callback, ... ) abort
  1196. if !s:AllowedToCompleteInCurrentBuffer()
  1197. eval a:callback( '' )
  1198. return
  1199. endif
  1200. if !get( b:, 'ycm_completing' )
  1201. eval a:callback( '' )
  1202. return
  1203. endif
  1204. call s:GetCommandResponseAsyncImpl( callback, 'extern', a:000 )
  1205. endfunction
  1206. function! youcompleteme#GetRawCommandResponseAsync( callback, ... ) abort
  1207. if !s:AllowedToCompleteInCurrentBuffer()
  1208. eval a:callback( { 'error': 'ycm not allowed in buffer' } )
  1209. return
  1210. endif
  1211. if !get( b:, 'ycm_completing' )
  1212. eval a:callback( { 'error': 'ycm disabled in buffer' } )
  1213. return
  1214. endif
  1215. let request_id = py3eval(
  1216. \ 'ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )' )
  1217. let s:pollers.command.requests[ request_id ] = {
  1218. \ 'response_func': 'Response',
  1219. \ 'origin': 'extern_raw',
  1220. \ 'callback': a:callback
  1221. \ }
  1222. if s:pollers.command.id == -1
  1223. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1224. \ function( 's:PollCommands' ) )
  1225. endif
  1226. endfunction
  1227. function! s:PollCommands( timer_id ) abort
  1228. " Clear the timer id before calling the callback, as the callback might fire
  1229. " more requests
  1230. call s:StopPoller( s:pollers.command )
  1231. " Must copy the requests because this loop is likely to modify it
  1232. let requests = copy( s:pollers.command.requests )
  1233. let poll_again = 0
  1234. for request_id in keys( requests )
  1235. let request = requests[ request_id ]
  1236. if py3eval( 'ycm_state.GetCommandRequest( int( vim.eval( "request_id" ) ) )'
  1237. \ . 'is None' )
  1238. " Possible in case of race conditions and things like RestartServer
  1239. " But particularly in the tests
  1240. let result = v:none
  1241. elseif !py3eval( 'ycm_state.GetCommandRequest( '
  1242. \ . 'int( vim.eval( "request_id" ) ) ).Done()' )
  1243. " Not ready yet, poll again and skip this one for now
  1244. let poll_again = 1
  1245. continue
  1246. else
  1247. let result = py3eval( 'ycm_state.GetCommandRequest( '
  1248. \ . 'int( vim.eval( "request_id" ) ) ).'
  1249. \ . request.response_func
  1250. \ . '()' )
  1251. endif
  1252. " This request is done
  1253. call remove( s:pollers.command.requests, request_id )
  1254. py3 ycm_state.FlushCommandRequest( vim.eval( "request_id" ) )
  1255. call request[ 'callback' ]( result )
  1256. endfor
  1257. if poll_again && s:pollers.command.id == -1
  1258. let s:pollers.command.id = timer_start( s:pollers.command.wait_milliseconds,
  1259. \ function( 's:PollCommands' ) )
  1260. endif
  1261. endfunction
  1262. function! s:CompleterCommand( mods, count, line1, line2, ... )
  1263. py3 ycm_state.SendCommandRequest(
  1264. \ vim.eval( 'a:000' ),
  1265. \ vim.eval( 'a:mods' ),
  1266. \ vimsupport.GetBoolValue( 'a:count != -1' ),
  1267. \ vimsupport.GetIntValue( 'a:line1' ),
  1268. \ vimsupport.GetIntValue( 'a:line2' ) )
  1269. endfunction
  1270. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  1271. return join( py3eval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  1272. endfunction
  1273. function! youcompleteme#GetDefinedSubcommands()
  1274. if !s:AllowedToCompleteInCurrentBuffer()
  1275. return []
  1276. endif
  1277. if !exists( 'b:ycm_completing' )
  1278. return []
  1279. endif
  1280. return py3eval( 'ycm_state.GetDefinedSubcommands()' )
  1281. endfunction
  1282. function! youcompleteme#OpenGoToList()
  1283. py3 vimsupport.PostVimMessage(
  1284. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  1285. \ "Do NOT use it.'" )
  1286. py3 vimsupport.OpenQuickFixList( True, True )
  1287. endfunction
  1288. function! s:ShowDiagnostics()
  1289. py3 ycm_state.ShowDiagnostics()
  1290. endfunction
  1291. function! s:ShowDetailedDiagnostic( ... )
  1292. if ( a:0 && a:1 == 'popup' )
  1293. \ || get( g:, 'ycm_show_detailed_diag_in_popup', 0 )
  1294. py3 ycm_state.ShowDetailedDiagnostic( True )
  1295. else
  1296. py3 ycm_state.ShowDetailedDiagnostic( False )
  1297. endif
  1298. endfunction
  1299. function! s:ForceCompileAndDiagnostics()
  1300. py3 ycm_state.ForceCompileAndDiagnostics()
  1301. endfunction
  1302. if exists( '*popup_atcursor' )
  1303. function s:Hover()
  1304. if !py3eval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  1305. " Cancel the autocommand if it happens to have been set
  1306. call s:DisableAutoHover()
  1307. return
  1308. endif
  1309. if !has_key( b:, 'ycm_hover' )
  1310. let cmds = youcompleteme#GetDefinedSubcommands()
  1311. if index( cmds, 'GetHover' ) >= 0
  1312. let b:ycm_hover = {
  1313. \ 'command': 'GetHover',
  1314. \ 'syntax': 'markdown',
  1315. \ }
  1316. elseif index( cmds, 'GetDoc' ) >= 0
  1317. let b:ycm_hover = {
  1318. \ 'command': 'GetDoc',
  1319. \ 'syntax': '',
  1320. \ }
  1321. elseif index( cmds, 'GetType' ) >= 0
  1322. let b:ycm_hover = {
  1323. \ 'command': 'GetType',
  1324. \ 'syntax': &syntax,
  1325. \ }
  1326. else
  1327. let b:ycm_hover = {}
  1328. endif
  1329. endif
  1330. if empty( b:ycm_hover )
  1331. return
  1332. endif
  1333. if empty( popup_getpos( s:cursorhold_popup ) )
  1334. call s:GetCommandResponseAsyncImpl(
  1335. \ function( 's:ShowHoverResult' ),
  1336. \ 'autohover',
  1337. \ b:ycm_hover.command )
  1338. endif
  1339. endfunction
  1340. function! s:ShowHoverResult( response )
  1341. call popup_hide( s:cursorhold_popup )
  1342. if empty( a:response )
  1343. return
  1344. endif
  1345. " Try to position the popup at the cursor, but avoid wrapping. If the
  1346. " longest line is > screen width (&columns), then we just have to wrap, and
  1347. " place the popup at the leftmost column.
  1348. "
  1349. " Find the longest line (FIXME: probably doesn't work well for multi-byte)
  1350. let lines = split( a:response, "\n" )
  1351. let len = max( map( copy( lines ), "len( v:val )" ) )
  1352. let wrap = 0
  1353. let col = 'cursor'
  1354. " max width is screen columns minus x padding (2)
  1355. if len >= (&columns - 2)
  1356. " There's at least one line > our max - enable word wrap and draw the
  1357. " popup at the leftmost column
  1358. let col = 1
  1359. let wrap = 1
  1360. endif
  1361. let popup_params = {
  1362. \ 'col': col,
  1363. \ 'wrap': wrap,
  1364. \ 'padding': [ 0, 1, 0, 1 ],
  1365. \ 'moved': 'word',
  1366. \ 'maxwidth': &columns,
  1367. \ 'close': 'click',
  1368. \ 'fixed': 0,
  1369. \ }
  1370. if has_key( b:ycm_hover, 'popup_params' )
  1371. let popup_params = extend( copy( popup_params ),
  1372. \ b:ycm_hover.popup_params )
  1373. endif
  1374. let s:cursorhold_popup = popup_atcursor( lines, popup_params )
  1375. call setbufvar( winbufnr( s:cursorhold_popup ),
  1376. \ '&syntax',
  1377. \ b:ycm_hover.syntax )
  1378. endfunction
  1379. function! s:ToggleHover()
  1380. let pos = popup_getpos( s:cursorhold_popup )
  1381. if !empty( pos ) && pos.visible
  1382. call popup_hide( s:cursorhold_popup )
  1383. let s:cursorhold_popup = -1
  1384. " Disable the auto-trigger until the next cursor movement.
  1385. call s:DisableAutoHover()
  1386. augroup YCMHover
  1387. autocmd! CursorMoved <buffer>
  1388. autocmd CursorMoved <buffer> call s:EnableAutoHover()
  1389. augroup END
  1390. else
  1391. call s:Hover()
  1392. endif
  1393. endfunction
  1394. let s:enable_hover = 1
  1395. nnoremap <silent> <plug>(YCMHover) :<C-u>call <SID>ToggleHover()<CR>
  1396. else
  1397. " Don't break people's mappings if this feature is disabled, just do nothing.
  1398. nnoremap <silent> <plug>(YCMHover) <Nop>
  1399. endif
  1400. function! youcompleteme#Test_GetPollers()
  1401. return s:pollers
  1402. endfunction
  1403. function! s:ToggleSignatureHelp()
  1404. call py3eval( 'ycm_state.ToggleSignatureHelp()' )
  1405. " Because we do this in a insert-mode mapping, we return empty string to
  1406. " insert/type nothing
  1407. return ''
  1408. endfunction
  1409. silent! inoremap <silent> <plug>(YCMToggleSignatureHelp)
  1410. \ <C-r>=<SID>ToggleSignatureHelp()<CR>
  1411. function! s:ToggleInlayHints()
  1412. let b:ycm_enable_inlay_hints =
  1413. \ !get( b:,
  1414. \ 'ycm_enable_inlay_hints',
  1415. \ get( g:, 'ycm_enable_inlay_hints' ) )
  1416. if !b:ycm_enable_inlay_hints && s:enable_inlay_hints
  1417. py3 ycm_state.CurrentBuffer().inlay_hints.Clear()
  1418. else
  1419. call s:UpdateInlayHints( bufnr(), 0, 1 )
  1420. endif
  1421. endfunction
  1422. silent! nnoremap <silent> <plug>(YCMToggleInlayHints)
  1423. \ <cmd>call <SID>ToggleInlayHints()<CR>
  1424. silent! nnoremap <silent> <plug>(YCMTypeHierarchy)
  1425. \ <cmd>call youcompleteme#hierarchy#StartRequest( 'type' )<cr>
  1426. silent! nnoremap <silent> <plug>(YCMCallHierarchy)
  1427. \ <cmd>call youcompleteme#hierarchy#StartRequest( 'call' )<cr>
  1428. " This is basic vim plugin boilerplate
  1429. let &cpo = s:save_cpo
  1430. unlet s:save_cpo