youcompleteme.vim 25 KB

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