youcompleteme.vim 24 KB

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