youcompleteme.vim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. " This needs to be called outside of a function
  21. let s:script_folder_path = escape( expand( '<sfile>:p:h' ), '\' )
  22. let s:force_semantic = 0
  23. let s:completion_stopped = 0
  24. let s:default_completion = {
  25. \ 'start_column': -1,
  26. \ 'candidates': []
  27. \ }
  28. let s:completion = s:default_completion
  29. let s:previous_allowed_buffer_number = 0
  30. let s:pollers = {
  31. \ 'completion': {
  32. \ 'id': -1,
  33. \ 'wait_milliseconds': 10
  34. \ },
  35. \ 'file_parse_response': {
  36. \ 'id': -1,
  37. \ 'wait_milliseconds': 100
  38. \ },
  39. \ 'server_ready': {
  40. \ 'id': -1,
  41. \ 'wait_milliseconds': 100
  42. \ },
  43. \ 'receive_messages': {
  44. \ 'id': -1,
  45. \ 'wait_milliseconds': 100
  46. \ }
  47. \ }
  48. " When both versions are available, we prefer Python 3 over Python 2:
  49. " - faster startup (no monkey-patching from python-future);
  50. " - better Windows support (e.g. temporary paths are not returned in all
  51. " lowercase);
  52. " - Python 2 support will eventually be dropped.
  53. function! s:UsingPython3()
  54. if has('python3')
  55. return 1
  56. endif
  57. return 0
  58. endfunction
  59. let s:using_python3 = s:UsingPython3()
  60. let s:python_until_eof = s:using_python3 ? "python3 << EOF" : "python << EOF"
  61. let s:python_command = s:using_python3 ? "py3 " : "py "
  62. function! s:Pyeval( eval_string )
  63. if s:using_python3
  64. return py3eval( a:eval_string )
  65. endif
  66. return pyeval( a:eval_string )
  67. endfunction
  68. function! s:StartMessagePoll()
  69. if s:pollers.receive_messages.id < 0
  70. let s:pollers.receive_messages.id = timer_start(
  71. \ s:pollers.receive_messages.wait_milliseconds,
  72. \ function( 's:ReceiveMessages' ) )
  73. endif
  74. endfunction
  75. function! s:ReceiveMessages( timer_id )
  76. let poll_again = s:Pyeval( 'ycm_state.OnPeriodicTick()' )
  77. if poll_again
  78. let s:pollers.receive_messages.id = timer_start(
  79. \ s:pollers.receive_messages.wait_milliseconds,
  80. \ function( 's:ReceiveMessages' ) )
  81. else
  82. " Don't poll again until we open another buffer
  83. let s:pollers.receive_messages.id = -1
  84. endif
  85. endfunction
  86. function! youcompleteme#Enable()
  87. call s:SetUpBackwardsCompatibility()
  88. " This can be 0 if YCM libs are old or -1 if an exception occured while
  89. " executing the function.
  90. if s:SetUpPython() != 1
  91. return
  92. endif
  93. call s:SetUpCommands()
  94. call s:SetUpCpoptions()
  95. call s:SetUpCompleteopt()
  96. call s:SetUpKeyMappings()
  97. if g:ycm_show_diagnostics_ui
  98. call s:TurnOffSyntasticForCFamily()
  99. endif
  100. call s:SetUpSigns()
  101. call s:SetUpSyntaxHighlighting()
  102. call youcompleteme#EnableCursorMovedAutocommands()
  103. augroup youcompleteme
  104. autocmd!
  105. " Note that these events will NOT trigger for the file vim is started with;
  106. " so if you do "vim foo.cc", these events will not trigger when that buffer
  107. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  108. " that happens *after* FileType has already triggered for the initial file.
  109. " We don't parse the buffer on the BufRead event since it would only be
  110. " useful if the buffer filetype is set (we ignore the buffer if there is no
  111. " filetype) and if so, the FileType event has triggered before and thus the
  112. " buffer is already parsed.
  113. autocmd FileType * call s:OnFileTypeSet()
  114. autocmd BufEnter * call s:OnBufferEnter()
  115. autocmd BufUnload * call s:OnBufferUnload()
  116. autocmd InsertLeave * call s:OnInsertLeave()
  117. autocmd VimLeave * call s:OnVimLeave()
  118. autocmd CompleteDone * call s:OnCompleteDone()
  119. autocmd BufEnter,WinEnter * call s:UpdateMatches()
  120. augroup END
  121. " The FileType event is not triggered for the first loaded file. We wait until
  122. " the server is ready to manually run the s:OnFileTypeSet function.
  123. let s:pollers.server_ready.id = timer_start(
  124. \ s:pollers.server_ready.wait_milliseconds,
  125. \ function( 's:PollServerReady' ) )
  126. endfunction
  127. function! youcompleteme#EnableCursorMovedAutocommands()
  128. augroup ycmcompletemecursormove
  129. autocmd!
  130. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  131. autocmd TextChanged * call s:OnTextChangedNormalMode()
  132. autocmd TextChangedI * call s:OnTextChangedInsertMode()
  133. " The TextChangedI event is not triggered when inserting a character while
  134. " the completion menu is open. We handle this by closing the completion menu
  135. " just before inserting a character.
  136. autocmd InsertCharPre * call s:OnInsertChar()
  137. augroup END
  138. endfunction
  139. function! youcompleteme#DisableCursorMovedAutocommands()
  140. autocmd! ycmcompletemecursormove
  141. endfunction
  142. function! youcompleteme#GetErrorCount()
  143. return s:Pyeval( 'ycm_state.GetErrorCount()' )
  144. endfunction
  145. function! youcompleteme#GetWarningCount()
  146. return s:Pyeval( 'ycm_state.GetWarningCount()' )
  147. endfunction
  148. function! s:SetUpPython() abort
  149. exec s:python_until_eof
  150. from __future__ import unicode_literals
  151. from __future__ import print_function
  152. from __future__ import division
  153. from __future__ import absolute_import
  154. import os
  155. import sys
  156. import traceback
  157. import vim
  158. # Add python sources folder to the system path.
  159. script_folder = vim.eval( 's:script_folder_path' )
  160. sys.path.insert( 0, os.path.join( script_folder, '..', 'python' ) )
  161. from ycm.setup import SetUpSystemPaths, SetUpYCM
  162. # We enclose this code in a try/except block to avoid backtraces in Vim.
  163. try:
  164. SetUpSystemPaths()
  165. # Import the modules used in this file.
  166. from ycm import base, vimsupport
  167. ycm_state = SetUpYCM()
  168. except Exception as error:
  169. # We don't use PostVimMessage or EchoText from the vimsupport module because
  170. # importing this module may fail.
  171. vim.command( 'redraw | echohl WarningMsg' )
  172. for line in traceback.format_exc().splitlines():
  173. vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) )
  174. vim.command( "echo 'YouCompleteMe unavailable: {0}'"
  175. .format( str( error ).replace( "'", "''" ) ) )
  176. vim.command( 'echohl None' )
  177. vim.command( 'return 0' )
  178. else:
  179. vim.command( 'return 1' )
  180. EOF
  181. endfunction
  182. function! s:SetUpKeyMappings()
  183. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  184. " exist and are now here purely for the sake of backwards compatibility; we
  185. " don't want to break users if we can avoid it.
  186. if exists('g:ycm_key_select_completion') &&
  187. \ index(g:ycm_key_list_select_completion,
  188. \ g:ycm_key_select_completion) == -1
  189. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  190. endif
  191. if exists('g:ycm_key_previous_completion') &&
  192. \ index(g:ycm_key_list_previous_completion,
  193. \ g:ycm_key_previous_completion) == -1
  194. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  195. endif
  196. for key in g:ycm_key_list_select_completion
  197. " With this command, when the completion window is visible, the tab key
  198. " (default) will select the next candidate in the window. In vim, this also
  199. " changes the typed-in text to that of the candidate completion.
  200. exe 'inoremap <expr>' . key .
  201. \ ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  202. endfor
  203. for key in g:ycm_key_list_previous_completion
  204. " This selects the previous candidate for shift-tab (default)
  205. exe 'inoremap <expr>' . key .
  206. \ ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  207. endfor
  208. for key in g:ycm_key_list_stop_completion
  209. " When selecting a candidate and closing the completion menu with the <C-y>
  210. " key, the menu will automatically be reopened because of the TextChangedI
  211. " event. We define a command to prevent that.
  212. exe 'inoremap <expr>' . key . ' <SID>StopCompletion( "\' . key . '" )'
  213. endfor
  214. if !empty( g:ycm_key_invoke_completion )
  215. let invoke_key = g:ycm_key_invoke_completion
  216. " Inside the console, <C-Space> is passed as <Nul> to Vim
  217. if invoke_key ==# '<C-Space>'
  218. imap <Nul> <C-Space>
  219. endif
  220. silent! exe 'inoremap <unique> <silent> ' . invoke_key .
  221. \ ' <C-R>=<SID>InvokeSemanticCompletion()<CR>'
  222. endif
  223. if !empty( g:ycm_key_detailed_diagnostics )
  224. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  225. \ ' :YcmShowDetailedDiagnostic<CR>'
  226. endif
  227. " The TextChangedI event is not triggered when deleting a character while the
  228. " completion menu is open. We handle this by closing the completion menu on
  229. " the keys that delete a character in insert mode.
  230. for key in [ "<BS>", "<C-h>" ]
  231. silent! exe 'inoremap <unique> <expr> ' . key .
  232. \ ' <SID>OnDeleteChar( "\' . key . '" )'
  233. endfor
  234. endfunction
  235. function! s:SetUpSigns()
  236. " We try to ensure backwards compatibility with Syntastic if the user has
  237. " already defined styling for Syntastic highlight groups.
  238. if !hlexists( 'YcmErrorSign' )
  239. if hlexists( 'SyntasticErrorSign')
  240. highlight link YcmErrorSign SyntasticErrorSign
  241. else
  242. highlight link YcmErrorSign error
  243. endif
  244. endif
  245. if !hlexists( 'YcmWarningSign' )
  246. if hlexists( 'SyntasticWarningSign')
  247. highlight link YcmWarningSign SyntasticWarningSign
  248. else
  249. highlight link YcmWarningSign todo
  250. endif
  251. endif
  252. if !hlexists( 'YcmErrorLine' )
  253. highlight link YcmErrorLine SyntasticErrorLine
  254. endif
  255. if !hlexists( 'YcmWarningLine' )
  256. highlight link YcmWarningLine SyntasticWarningLine
  257. endif
  258. exe 'sign define YcmError text=' . g:ycm_error_symbol .
  259. \ ' texthl=YcmErrorSign linehl=YcmErrorLine'
  260. exe 'sign define YcmWarning text=' . g:ycm_warning_symbol .
  261. \ ' texthl=YcmWarningSign linehl=YcmWarningLine'
  262. endfunction
  263. function! s:SetUpSyntaxHighlighting()
  264. " We try to ensure backwards compatibility with Syntastic if the user has
  265. " already defined styling for Syntastic highlight groups.
  266. if !hlexists( 'YcmErrorSection' )
  267. if hlexists( 'SyntasticError' )
  268. highlight link YcmErrorSection SyntasticError
  269. else
  270. highlight link YcmErrorSection SpellBad
  271. endif
  272. endif
  273. if !hlexists( 'YcmWarningSection' )
  274. if hlexists( 'SyntasticWarning' )
  275. highlight link YcmWarningSection SyntasticWarning
  276. else
  277. highlight link YcmWarningSection SpellCap
  278. endif
  279. endif
  280. endfunction
  281. function! s:SetUpBackwardsCompatibility()
  282. let complete_in_comments_and_strings =
  283. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  284. if complete_in_comments_and_strings
  285. let g:ycm_complete_in_strings = 1
  286. let g:ycm_complete_in_comments = 1
  287. endif
  288. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  289. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  290. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  291. endif
  292. endfunction
  293. " Needed so that YCM is used instead of Syntastic
  294. function! s:TurnOffSyntasticForCFamily()
  295. let g:syntastic_cpp_checkers = []
  296. let g:syntastic_c_checkers = []
  297. let g:syntastic_objc_checkers = []
  298. let g:syntastic_objcpp_checkers = []
  299. endfunction
  300. function! s:DisableOnLargeFile( buffer )
  301. if exists( 'b:ycm_largefile' )
  302. return b:ycm_largefile
  303. endif
  304. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  305. let b:ycm_largefile =
  306. \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold
  307. if b:ycm_largefile
  308. exec s:python_command "vimsupport.PostVimMessage(" .
  309. \ "'YouCompleteMe is disabled in this buffer; " .
  310. \ "the file exceeded the max size (see YCM options).' )"
  311. endif
  312. return b:ycm_largefile
  313. endfunction
  314. function! s:AllowedToCompleteInBuffer( buffer )
  315. let buffer_filetype = getbufvar( a:buffer, '&filetype' )
  316. if empty( buffer_filetype ) ||
  317. \ getbufvar( a:buffer, '&buftype' ) ==# 'nofile' ||
  318. \ buffer_filetype ==# 'qf'
  319. return 0
  320. endif
  321. if s:DisableOnLargeFile( a:buffer )
  322. return 0
  323. endif
  324. let whitelist_allows = has_key( g:ycm_filetype_whitelist, '*' ) ||
  325. \ has_key( g:ycm_filetype_whitelist, buffer_filetype )
  326. let blacklist_allows = !has_key( g:ycm_filetype_blacklist, buffer_filetype )
  327. let allowed = whitelist_allows && blacklist_allows
  328. if allowed
  329. let s:previous_allowed_buffer_number = bufnr( a:buffer )
  330. endif
  331. return allowed
  332. endfunction
  333. function! s:AllowedToCompleteInCurrentBuffer()
  334. return s:AllowedToCompleteInBuffer( '%' )
  335. endfunction
  336. function! s:VisitedBufferRequiresReparse()
  337. if bufnr( '%' ) ==# s:previous_allowed_buffer_number
  338. return 0
  339. endif
  340. return s:AllowedToCompleteInCurrentBuffer()
  341. endfunction
  342. function! s:SetUpCpoptions()
  343. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  344. " no way to not have this and have YCM working, so force the flag.
  345. set cpoptions+=B
  346. " This prevents the display of "Pattern not found" & similar messages during
  347. " completion.
  348. set shortmess+=c
  349. endfunction
  350. function! s:SetUpCompleteopt()
  351. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  352. " instance adding 'longest'. This breaks YCM. So we force our settings.
  353. " There's no two ways about this: if you want to use YCM then you have to
  354. " have these completeopt settings, otherwise YCM won't work at all.
  355. " We need menuone in completeopt, otherwise when there's only one candidate
  356. " for completion, the menu doesn't show up.
  357. set completeopt-=menu
  358. set completeopt+=menuone
  359. " This is unnecessary with our features. People use this option to insert
  360. " the common prefix of all the matches and then add more differentiating chars
  361. " so that they can select a more specific match. With our features, they
  362. " don't need to insert the prefix; they just type the differentiating chars.
  363. " Also, having this option set breaks the plugin.
  364. set completeopt-=longest
  365. if g:ycm_add_preview_to_completeopt
  366. set completeopt+=preview
  367. endif
  368. endfunction
  369. function! s:SetCompleteFunc()
  370. let &completefunc = 'youcompleteme#CompleteFunc'
  371. endfunction
  372. function! s:OnVimLeave()
  373. exec s:python_command "ycm_state.OnVimLeave()"
  374. endfunction
  375. function! s:OnCompleteDone()
  376. exec s:python_command "ycm_state.OnCompleteDone()"
  377. endfunction
  378. function! s:OnFileTypeSet()
  379. if !s:AllowedToCompleteInCurrentBuffer()
  380. return
  381. endif
  382. call s:SetUpCompleteopt()
  383. call s:SetCompleteFunc()
  384. call s:StartMessagePoll()
  385. exec s:python_command "ycm_state.OnBufferVisit()"
  386. call s:OnFileReadyToParse( 1 )
  387. endfunction
  388. function! s:OnBufferEnter()
  389. if !s:VisitedBufferRequiresReparse()
  390. return
  391. endif
  392. call s:SetUpCompleteopt()
  393. call s:SetCompleteFunc()
  394. call s:StartMessagePoll()
  395. exec s:python_command "ycm_state.OnBufferVisit()"
  396. " Last parse may be outdated because of changes from other buffers. Force a
  397. " new parse.
  398. call s:OnFileReadyToParse( 1 )
  399. endfunction
  400. function! s:OnBufferUnload()
  401. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  402. " it as a true number for the getbufvar function.
  403. let buffer_number = str2nr( expand( '<abuf>' ) )
  404. if !s:AllowedToCompleteInBuffer( buffer_number )
  405. return
  406. endif
  407. exec s:python_command "ycm_state.OnBufferUnload( " . buffer_number . " )"
  408. endfunction
  409. function! s:UpdateMatches()
  410. exec s:python_command "ycm_state.UpdateMatches()"
  411. endfunction
  412. function! s:PollServerReady( timer_id )
  413. if !s:Pyeval( 'ycm_state.IsServerAlive()' )
  414. exec s:python_command "ycm_state.NotifyUserIfServerCrashed()"
  415. " Server crashed. Don't poll it again.
  416. return
  417. endif
  418. if !s:Pyeval( 'ycm_state.CheckIfServerIsReady()' )
  419. let s:pollers.server_ready.id = timer_start(
  420. \ s:pollers.server_ready.wait_milliseconds,
  421. \ function( 's:PollServerReady' ) )
  422. return
  423. endif
  424. call s:OnFileTypeSet()
  425. endfunction
  426. function! s:OnFileReadyToParse( ... )
  427. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  428. " FileReadyToParse event notification, whether the buffer has changed or not;
  429. " effectively forcing a parse of the buffer. Default is 0.
  430. let force_parsing = a:0 > 0 && a:1
  431. " We only want to send a new FileReadyToParse event notification if the buffer
  432. " has changed since the last time we sent one, or if forced.
  433. if force_parsing || s:Pyeval( "ycm_state.NeedsReparse()" )
  434. exec s:python_command "ycm_state.OnFileReadyToParse()"
  435. call timer_stop( s:pollers.file_parse_response.id )
  436. let s:pollers.file_parse_response.id = timer_start(
  437. \ s:pollers.file_parse_response.wait_milliseconds,
  438. \ function( 's:PollFileParseResponse' ) )
  439. endif
  440. endfunction
  441. function! s:PollFileParseResponse( ... )
  442. if !s:Pyeval( "ycm_state.FileParseRequestReady()" )
  443. let s:pollers.file_parse_response.id = timer_start(
  444. \ s:pollers.file_parse_response.wait_milliseconds,
  445. \ function( 's:PollFileParseResponse' ) )
  446. return
  447. endif
  448. exec s:python_command "ycm_state.HandleFileParseRequest()"
  449. if s:Pyeval( "ycm_state.ShouldResendFileParseRequest()" )
  450. call s:OnFileReadyToParse( 1 )
  451. endif
  452. endfunction
  453. function! s:SendKeys( keys )
  454. " By default keys are added to the end of the typeahead buffer. If there are
  455. " already keys in the buffer, they will be processed first and may change the
  456. " state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in normal
  457. " mode instead of insert mode or <C-e> outside of completion mode). We avoid
  458. " that by inserting the keys at the start of the typeahead buffer with the 'i'
  459. " option. Also, we don't want the keys to be remapped to something else so we
  460. " add the 'n' option.
  461. call feedkeys( a:keys, 'in' )
  462. endfunction
  463. function! s:CloseCompletionMenu()
  464. if pumvisible()
  465. call s:SendKeys( "\<C-e>" )
  466. endif
  467. endfunction
  468. function! s:OnInsertChar()
  469. if !s:AllowedToCompleteInCurrentBuffer()
  470. return
  471. endif
  472. call timer_stop( s:pollers.completion.id )
  473. call s:CloseCompletionMenu()
  474. endfunction
  475. function! s:OnDeleteChar( key )
  476. if !s:AllowedToCompleteInCurrentBuffer()
  477. return a:key
  478. endif
  479. call timer_stop( s:pollers.completion.id )
  480. if pumvisible()
  481. return "\<C-y>" . a:key
  482. endif
  483. return a:key
  484. endfunction
  485. function! s:StopCompletion( key )
  486. call timer_stop( s:pollers.completion.id )
  487. if pumvisible()
  488. let s:completion_stopped = 1
  489. return "\<C-y>"
  490. endif
  491. return a:key
  492. endfunction
  493. function! s:OnCursorMovedNormalMode()
  494. if !s:AllowedToCompleteInCurrentBuffer()
  495. return
  496. endif
  497. exec s:python_command "ycm_state.OnCursorMoved()"
  498. endfunction
  499. function! s:OnTextChangedNormalMode()
  500. if !s:AllowedToCompleteInCurrentBuffer()
  501. return
  502. endif
  503. call s:OnFileReadyToParse()
  504. endfunction
  505. function! s:OnTextChangedInsertMode()
  506. if !s:AllowedToCompleteInCurrentBuffer()
  507. return
  508. endif
  509. if s:completion_stopped
  510. let s:completion_stopped = 0
  511. let s:completion = s:default_completion
  512. return
  513. endif
  514. call s:IdentifierFinishedOperations()
  515. " We have to make sure we correctly leave semantic mode even when the user
  516. " inserts something like a "operator[]" candidate string which fails
  517. " CurrentIdentifierFinished check.
  518. if s:force_semantic && !s:Pyeval( 'base.LastEnteredCharIsIdentifierChar()' )
  519. let s:force_semantic = 0
  520. endif
  521. if &completefunc == "youcompleteme#CompleteFunc" &&
  522. \ ( g:ycm_auto_trigger || s:force_semantic ) &&
  523. \ !s:InsideCommentOrStringAndShouldStop() &&
  524. \ !s:OnBlankLine()
  525. " Immediately call previous completion to avoid flickers.
  526. call s:Complete()
  527. call s:InvokeCompletion()
  528. endif
  529. exec s:python_command "ycm_state.OnCursorMoved()"
  530. if g:ycm_autoclose_preview_window_after_completion
  531. call s:ClosePreviewWindowIfNeeded()
  532. endif
  533. endfunction
  534. function! s:OnInsertLeave()
  535. if !s:AllowedToCompleteInCurrentBuffer()
  536. return
  537. endif
  538. call timer_stop( s:pollers.completion.id )
  539. let s:force_semantic = 0
  540. let s:completion = s:default_completion
  541. call s:OnFileReadyToParse()
  542. exec s:python_command "ycm_state.OnInsertLeave()"
  543. if g:ycm_autoclose_preview_window_after_completion ||
  544. \ g:ycm_autoclose_preview_window_after_insertion
  545. call s:ClosePreviewWindowIfNeeded()
  546. endif
  547. endfunction
  548. function! s:ClosePreviewWindowIfNeeded()
  549. let current_buffer_name = bufname('')
  550. " We don't want to try to close the preview window in special buffers like
  551. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  552. " with '['.
  553. if current_buffer_name[ 0 ] == '['
  554. return
  555. endif
  556. " This command does the actual closing of the preview window. If no preview
  557. " window is shown, nothing happens.
  558. pclose
  559. endfunction
  560. function! s:IdentifierFinishedOperations()
  561. if !s:Pyeval( 'base.CurrentIdentifierFinished()' )
  562. return
  563. endif
  564. exec s:python_command "ycm_state.OnCurrentIdentifierFinished()"
  565. let s:force_semantic = 0
  566. let s:completion = s:default_completion
  567. endfunction
  568. " Returns 1 when inside comment and 2 when inside string
  569. function! s:InsideCommentOrString()
  570. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  571. " in insert mode when this func is called.
  572. let syntax_group = synIDattr(
  573. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  574. if stridx(syntax_group, 'Comment') > -1
  575. return 1
  576. endif
  577. if stridx(syntax_group, 'String') > -1
  578. return 2
  579. endif
  580. return 0
  581. endfunction
  582. function! s:InsideCommentOrStringAndShouldStop()
  583. let retval = s:InsideCommentOrString()
  584. let inside_comment = retval == 1
  585. let inside_string = retval == 2
  586. if inside_comment && g:ycm_complete_in_comments ||
  587. \ inside_string && g:ycm_complete_in_strings
  588. return 0
  589. endif
  590. return retval
  591. endfunction
  592. function! s:OnBlankLine()
  593. return s:Pyeval( 'not vim.current.line or vim.current.line.isspace()' )
  594. endfunction
  595. function! s:InvokeCompletion()
  596. exec s:python_command "ycm_state.SendCompletionRequest(" .
  597. \ "vimsupport.GetBoolValue( 's:force_semantic' ) )"
  598. call s:PollCompletion()
  599. endfunction
  600. function! s:InvokeSemanticCompletion()
  601. if &completefunc == "youcompleteme#CompleteFunc"
  602. let s:force_semantic = 1
  603. exec s:python_command "ycm_state.SendCompletionRequest( True )"
  604. call s:PollCompletion()
  605. endif
  606. " Since this function is called in a mapping through the expression register
  607. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  608. " insert anything so we return an empty string.
  609. return ''
  610. endfunction
  611. function! s:PollCompletion( ... )
  612. if !s:Pyeval( 'ycm_state.CompletionRequestReady()' )
  613. let s:pollers.completion.id = timer_start(
  614. \ s:pollers.completion.wait_milliseconds,
  615. \ function( 's:PollCompletion' ) )
  616. return
  617. endif
  618. let response = s:Pyeval( 'ycm_state.GetCompletionResponse()' )
  619. let s:completion = {
  620. \ 'start_column': response.completion_start_column,
  621. \ 'candidates': response.completions
  622. \ }
  623. call s:Complete()
  624. endfunction
  625. function! s:Complete()
  626. " Do not call user's completion function if the start column is after the
  627. " current column or if there are no candidates. Close the completion menu
  628. " instead. This avoids keeping the user in completion mode.
  629. if s:completion.start_column > col( '.' ) || empty( s:completion.candidates )
  630. call s:CloseCompletionMenu()
  631. else
  632. " <c-x><c-u> invokes the user's completion function (which we have set to
  633. " youcompleteme#CompleteFunc), and <c-p> tells Vim to select the previous
  634. " completion candidate. This is necessary because by default, Vim selects the
  635. " first candidate when completion is invoked, and selecting a candidate
  636. " automatically replaces the current text with it. Calling <c-p> forces Vim to
  637. " deselect the first candidate and in turn preserve the user's current text
  638. " until he explicitly chooses to replace it with a completion.
  639. call s:SendKeys( "\<C-X>\<C-U>\<C-P>" )
  640. endif
  641. endfunction
  642. function! youcompleteme#CompleteFunc( findstart, base )
  643. if a:findstart
  644. return s:completion.start_column - 1
  645. endif
  646. return s:completion.candidates
  647. endfunction
  648. function! youcompleteme#ServerPid()
  649. return s:Pyeval( 'ycm_state.ServerPid()' )
  650. endfunction
  651. function! s:SetUpCommands()
  652. command! YcmRestartServer call s:RestartServer()
  653. command! YcmDebugInfo call s:DebugInfo()
  654. command! -nargs=* -complete=custom,youcompleteme#LogsComplete
  655. \ YcmToggleLogs call s:ToggleLogs(<f-args>)
  656. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  657. \ YcmCompleter call s:CompleterCommand(<count>,
  658. \ <line1>,
  659. \ <line2>,
  660. \ <f-args>)
  661. command! YcmDiags call s:ShowDiagnostics()
  662. command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic()
  663. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  664. endfunction
  665. function! s:RestartServer()
  666. exec s:python_command "ycm_state.RestartServer()"
  667. call timer_stop( s:pollers.receive_messages.id )
  668. let s:pollers.receive_messages.id = -1
  669. call timer_stop( s:pollers.server_ready.id )
  670. let s:pollers.server_ready.id = timer_start(
  671. \ s:pollers.server_ready.wait_milliseconds,
  672. \ function( 's:PollServerReady' ) )
  673. endfunction
  674. function! s:DebugInfo()
  675. echom "Printing YouCompleteMe debug information..."
  676. let debug_info = s:Pyeval( 'ycm_state.DebugInfo()' )
  677. for line in split( debug_info, "\n" )
  678. echom '-- ' . line
  679. endfor
  680. endfunction
  681. function! s:ToggleLogs(...)
  682. exec s:python_command "ycm_state.ToggleLogs( *vim.eval( 'a:000' ) )"
  683. endfunction
  684. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  685. return join( s:Pyeval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  686. endfunction
  687. function! s:CompleterCommand( count, line1, line2, ... )
  688. " CompleterCommand will call the OnUserCommand function of a completer. If
  689. " the first arguments is of the form "ft=..." it can be used to specify the
  690. " completer to use (for example "ft=cpp"). Else the native filetype completer
  691. " of the current buffer is used. If no native filetype completer is found and
  692. " no completer was specified this throws an error. You can use "ft=ycm:ident"
  693. " to select the identifier completer. The remaining arguments will be passed
  694. " to the completer.
  695. let arguments = copy(a:000)
  696. let completer = ''
  697. if a:0 > 0 && strpart(a:1, 0, 3) == 'ft='
  698. if a:1 == 'ft=ycm:ident'
  699. let completer = 'identifier'
  700. endif
  701. let arguments = arguments[1:]
  702. endif
  703. exec s:python_command "ycm_state.SendCommandRequest(" .
  704. \ "vim.eval( 'l:arguments' )," .
  705. \ "vim.eval( 'l:completer' )," .
  706. \ "vimsupport.GetBoolValue( 'a:count != -1' )," .
  707. \ "vimsupport.GetIntValue( 'a:line1' )," .
  708. \ "vimsupport.GetIntValue( 'a:line2' ) )"
  709. endfunction
  710. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  711. return join( s:Pyeval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  712. endfunction
  713. function! youcompleteme#OpenGoToList()
  714. exec s:python_command "vimsupport.PostVimMessage(" .
  715. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  716. \ "Do NOT use it.' )"
  717. exec s:python_command "vimsupport.OpenQuickFixList( True, True )"
  718. endfunction
  719. function! s:ShowDiagnostics()
  720. exec s:python_command "ycm_state.ShowDiagnostics()"
  721. endfunction
  722. function! s:ShowDetailedDiagnostic()
  723. exec s:python_command "ycm_state.ShowDetailedDiagnostic()"
  724. endfunction
  725. function! s:ForceCompileAndDiagnostics()
  726. exec s:python_command "ycm_state.ForceCompileAndDiagnostics()"
  727. endfunction
  728. " This is basic vim plugin boilerplate
  729. let &cpo = s:save_cpo
  730. unlet s:save_cpo