youcompleteme.vim 24 KB

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