youcompleteme.vim 25 KB

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