youcompleteme.vim 25 KB

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