youcompleteme.vim 26 KB

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