youcompleteme.vim 27 KB

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