youcompleteme.vim 25 KB

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