1
0

youcompleteme.vim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. \ }
  32. " When both versions are available, we prefer Python 3 over Python 2:
  33. " - faster startup (no monkey-patching from python-future);
  34. " - better Windows support (e.g. temporary paths are not returned in all
  35. " lowercase);
  36. " - Python 2 support will eventually be dropped.
  37. function! s:UsingPython3()
  38. if has('python3')
  39. return 1
  40. endif
  41. return 0
  42. endfunction
  43. let s:using_python3 = s:UsingPython3()
  44. let s:python_until_eof = s:using_python3 ? "python3 << EOF" : "python << EOF"
  45. let s:python_command = s:using_python3 ? "py3 " : "py "
  46. function! s:Pyeval( eval_string )
  47. if s:using_python3
  48. return py3eval( a:eval_string )
  49. endif
  50. return pyeval( a:eval_string )
  51. endfunction
  52. function! youcompleteme#Enable()
  53. call s:SetUpBackwardsCompatibility()
  54. " This can be 0 if YCM libs are old or -1 if an exception occured while
  55. " executing the function.
  56. if s:SetUpPython() != 1
  57. return
  58. endif
  59. call s:SetUpCommands()
  60. call s:SetUpCpoptions()
  61. call s:SetUpCompleteopt()
  62. call s:SetUpKeyMappings()
  63. if g:ycm_show_diagnostics_ui
  64. call s:TurnOffSyntasticForCFamily()
  65. endif
  66. call s:SetUpSigns()
  67. call s:SetUpSyntaxHighlighting()
  68. call youcompleteme#EnableCursorMovedAutocommands()
  69. augroup youcompleteme
  70. autocmd!
  71. " Note that these events will NOT trigger for the file vim is started with;
  72. " so if you do "vim foo.cc", these events will not trigger when that buffer
  73. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  74. " that happens *after* FileType has already triggered for the initial file.
  75. " We don't parse the buffer on the BufRead event since it would only be
  76. " useful if the buffer filetype is set (we ignore the buffer if there is no
  77. " filetype) and if so, the FileType event has triggered before and thus the
  78. " buffer is already parsed.
  79. autocmd FileType * call s:OnFileTypeSet()
  80. autocmd BufEnter * call s:OnBufferEnter()
  81. autocmd BufUnload * call s:OnBufferUnload()
  82. autocmd InsertLeave * call s:OnInsertLeave()
  83. autocmd InsertEnter * call s:OnInsertEnter()
  84. autocmd VimLeave * call s:OnVimLeave()
  85. autocmd CompleteDone * call s:OnCompleteDone()
  86. augroup END
  87. " The FileType event is not triggered for the first loaded file. However, we
  88. " don't directly call the s:OnFileTypeSet function because it would send
  89. " requests that can't succeed as the server is not ready yet and would slow
  90. " down startup.
  91. if s:AllowedToCompleteInCurrentBuffer()
  92. call s:SetCompleteFunc()
  93. endif
  94. endfunction
  95. function! youcompleteme#EnableCursorMovedAutocommands()
  96. augroup ycmcompletemecursormove
  97. autocmd!
  98. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  99. autocmd TextChanged * call s:OnTextChangedNormalMode()
  100. autocmd TextChangedI * call s:OnTextChangedInsertMode()
  101. augroup END
  102. endfunction
  103. function! youcompleteme#DisableCursorMovedAutocommands()
  104. autocmd! ycmcompletemecursormove
  105. endfunction
  106. function! youcompleteme#GetErrorCount()
  107. return s:Pyeval( 'ycm_state.GetErrorCount()' )
  108. endfunction
  109. function! youcompleteme#GetWarningCount()
  110. return s:Pyeval( 'ycm_state.GetWarningCount()' )
  111. endfunction
  112. function! s:SetUpPython() abort
  113. exec s:python_until_eof
  114. from __future__ import unicode_literals
  115. from __future__ import print_function
  116. from __future__ import division
  117. from __future__ import absolute_import
  118. import os
  119. import sys
  120. import traceback
  121. import vim
  122. # Add python sources folder to the system path.
  123. script_folder = vim.eval( 's:script_folder_path' )
  124. sys.path.insert( 0, os.path.join( script_folder, '..', 'python' ) )
  125. from ycm.setup import SetUpSystemPaths, SetUpYCM
  126. # We enclose this code in a try/except block to avoid backtraces in Vim.
  127. try:
  128. SetUpSystemPaths()
  129. # Import the modules used in this file.
  130. from ycm import base, vimsupport
  131. ycm_state = SetUpYCM()
  132. except Exception as error:
  133. # We don't use PostVimMessage or EchoText from the vimsupport module because
  134. # importing this module may fail.
  135. vim.command( 'redraw | echohl WarningMsg' )
  136. for line in traceback.format_exc().splitlines():
  137. vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) )
  138. vim.command( "echo 'YouCompleteMe unavailable: {0}'"
  139. .format( str( error ).replace( "'", "''" ) ) )
  140. vim.command( 'echohl None' )
  141. vim.command( 'return 0' )
  142. else:
  143. vim.command( 'return 1' )
  144. EOF
  145. endfunction
  146. function! s:SetUpKeyMappings()
  147. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  148. " exist and are now here purely for the sake of backwards compatibility; we
  149. " don't want to break users if we can avoid it.
  150. if exists('g:ycm_key_select_completion') &&
  151. \ index(g:ycm_key_list_select_completion,
  152. \ g:ycm_key_select_completion) == -1
  153. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  154. endif
  155. if exists('g:ycm_key_previous_completion') &&
  156. \ index(g:ycm_key_list_previous_completion,
  157. \ g:ycm_key_previous_completion) == -1
  158. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  159. endif
  160. for key in g:ycm_key_list_select_completion
  161. " With this command, when the completion window is visible, the tab key
  162. " (default) will select the next candidate in the window. In vim, this also
  163. " changes the typed-in text to that of the candidate completion.
  164. exe 'inoremap <expr>' . key .
  165. \ ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  166. endfor
  167. for key in g:ycm_key_list_previous_completion
  168. " This selects the previous candidate for shift-tab (default)
  169. exe 'inoremap <expr>' . key .
  170. \ ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  171. endfor
  172. if !empty( g:ycm_key_invoke_completion )
  173. let invoke_key = g:ycm_key_invoke_completion
  174. " Inside the console, <C-Space> is passed as <Nul> to Vim
  175. if invoke_key ==# '<C-Space>'
  176. imap <Nul> <C-Space>
  177. endif
  178. " <c-x><c-o> trigger omni completion, <c-p> deselects the first completion
  179. " candidate that vim selects by default
  180. silent! exe 'inoremap <unique> ' . invoke_key . ' <C-X><C-O><C-P>'
  181. endif
  182. if !empty( g:ycm_key_detailed_diagnostics )
  183. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  184. \ ' :YcmShowDetailedDiagnostic<cr>'
  185. endif
  186. endfunction
  187. function! s:SetUpSigns()
  188. " We try to ensure backwards compatibility with Syntastic if the user has
  189. " already defined styling for Syntastic highlight groups.
  190. if !hlexists( 'YcmErrorSign' )
  191. if hlexists( 'SyntasticErrorSign')
  192. highlight link YcmErrorSign SyntasticErrorSign
  193. else
  194. highlight link YcmErrorSign error
  195. endif
  196. endif
  197. if !hlexists( 'YcmWarningSign' )
  198. if hlexists( 'SyntasticWarningSign')
  199. highlight link YcmWarningSign SyntasticWarningSign
  200. else
  201. highlight link YcmWarningSign todo
  202. endif
  203. endif
  204. if !hlexists( 'YcmErrorLine' )
  205. highlight link YcmErrorLine SyntasticErrorLine
  206. endif
  207. if !hlexists( 'YcmWarningLine' )
  208. highlight link YcmWarningLine SyntasticWarningLine
  209. endif
  210. exe 'sign define YcmError text=' . g:ycm_error_symbol .
  211. \ ' texthl=YcmErrorSign linehl=YcmErrorLine'
  212. exe 'sign define YcmWarning text=' . g:ycm_warning_symbol .
  213. \ ' texthl=YcmWarningSign linehl=YcmWarningLine'
  214. endfunction
  215. function! s:SetUpSyntaxHighlighting()
  216. " We try to ensure backwards compatibility with Syntastic if the user has
  217. " already defined styling for Syntastic highlight groups.
  218. if !hlexists( 'YcmErrorSection' )
  219. if hlexists( 'SyntasticError' )
  220. highlight link YcmErrorSection SyntasticError
  221. else
  222. highlight link YcmErrorSection SpellBad
  223. endif
  224. endif
  225. if !hlexists( 'YcmWarningSection' )
  226. if hlexists( 'SyntasticWarning' )
  227. highlight link YcmWarningSection SyntasticWarning
  228. else
  229. highlight link YcmWarningSection SpellCap
  230. endif
  231. endif
  232. endfunction
  233. function! s:SetUpBackwardsCompatibility()
  234. let complete_in_comments_and_strings =
  235. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  236. if complete_in_comments_and_strings
  237. let g:ycm_complete_in_strings = 1
  238. let g:ycm_complete_in_comments = 1
  239. endif
  240. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  241. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  242. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  243. endif
  244. endfunction
  245. " Needed so that YCM is used instead of Syntastic
  246. function! s:TurnOffSyntasticForCFamily()
  247. let g:syntastic_cpp_checkers = []
  248. let g:syntastic_c_checkers = []
  249. let g:syntastic_objc_checkers = []
  250. let g:syntastic_objcpp_checkers = []
  251. endfunction
  252. function! s:DisableOnLargeFile( buffer )
  253. if exists( 'b:ycm_largefile' )
  254. return b:ycm_largefile
  255. endif
  256. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  257. let b:ycm_largefile =
  258. \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold
  259. if b:ycm_largefile
  260. exec s:python_command "vimsupport.PostVimMessage(" .
  261. \ "'YouCompleteMe is disabled in this buffer; " .
  262. \ "the file exceeded the max size (see YCM options).' )"
  263. endif
  264. return b:ycm_largefile
  265. endfunction
  266. function! s:AllowedToCompleteInBuffer( buffer )
  267. let buffer_filetype = getbufvar( a:buffer, '&filetype' )
  268. if empty( buffer_filetype ) ||
  269. \ getbufvar( a:buffer, '&buftype' ) ==# 'nofile' ||
  270. \ buffer_filetype ==# 'qf'
  271. return 0
  272. endif
  273. if s:DisableOnLargeFile( a:buffer )
  274. return 0
  275. endif
  276. let whitelist_allows = has_key( g:ycm_filetype_whitelist, '*' ) ||
  277. \ has_key( g:ycm_filetype_whitelist, buffer_filetype )
  278. let blacklist_allows = !has_key( g:ycm_filetype_blacklist, buffer_filetype )
  279. let allowed = whitelist_allows && blacklist_allows
  280. if allowed
  281. let s:previous_allowed_buffer_number = bufnr( a:buffer )
  282. endif
  283. return allowed
  284. endfunction
  285. function! s:AllowedToCompleteInCurrentBuffer()
  286. return s:AllowedToCompleteInBuffer( '%' )
  287. endfunction
  288. function! s:VisitedBufferRequiresReparse()
  289. if bufnr( '%' ) ==# s:previous_allowed_buffer_number
  290. return 0
  291. endif
  292. return s:AllowedToCompleteInCurrentBuffer()
  293. endfunction
  294. function! s:SetUpCpoptions()
  295. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  296. " no way to not have this and have YCM working, so force the flag.
  297. set cpoptions+=B
  298. " This prevents the display of "Pattern not found" & similar messages during
  299. " completion.
  300. set shortmess+=c
  301. endfunction
  302. function! s:SetUpCompleteopt()
  303. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  304. " instance adding 'longest'. This breaks YCM. So we force our settings.
  305. " There's no two ways about this: if you want to use YCM then you have to
  306. " have these completeopt settings, otherwise YCM won't work at all.
  307. " We need menuone in completeopt, otherwise when there's only one candidate
  308. " for completion, the menu doesn't show up.
  309. set completeopt-=menu
  310. set completeopt+=menuone
  311. " This is unnecessary with our features. People use this option to insert
  312. " the common prefix of all the matches and then add more differentiating chars
  313. " so that they can select a more specific match. With our features, they
  314. " don't need to insert the prefix; they just type the differentiating chars.
  315. " Also, having this option set breaks the plugin.
  316. set completeopt-=longest
  317. if g:ycm_add_preview_to_completeopt
  318. set completeopt+=preview
  319. endif
  320. endfunction
  321. function! s:OnVimLeave()
  322. exec s:python_command "ycm_state.OnVimLeave()"
  323. endfunction
  324. function! s:OnCompleteDone()
  325. exec s:python_command "ycm_state.OnCompleteDone()"
  326. endfunction
  327. function! s:OnFileTypeSet()
  328. if !s:AllowedToCompleteInCurrentBuffer()
  329. return
  330. endif
  331. call s:SetUpCompleteopt()
  332. call s:SetCompleteFunc()
  333. call s:SetOmnicompleteFunc()
  334. exec s:python_command "ycm_state.OnBufferVisit()"
  335. call s:OnFileReadyToParse( 1 )
  336. endfunction
  337. function! s:OnBufferEnter()
  338. if !s:VisitedBufferRequiresReparse()
  339. return
  340. endif
  341. call s:SetUpCompleteopt()
  342. call s:SetCompleteFunc()
  343. call s:SetOmnicompleteFunc()
  344. exec s:python_command "ycm_state.OnBufferVisit()"
  345. " Last parse may be outdated because of changes from other buffers. Force a
  346. " new parse.
  347. call s:OnFileReadyToParse( 1 )
  348. endfunction
  349. function! s:OnBufferUnload()
  350. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  351. " it as a true number for the getbufvar function.
  352. if !s:AllowedToCompleteInBuffer( str2nr( expand( '<abuf>' ) ) )
  353. return
  354. endif
  355. let deleted_buffer_file = expand( '<afile>:p' )
  356. exec s:python_command "ycm_state.OnBufferUnload(" .
  357. \ "vim.eval( 'deleted_buffer_file' ) )"
  358. endfunction
  359. function! s:OnFileReadyToParse( ... )
  360. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  361. " FileReadyToParse event notification, whether the buffer has changed or not;
  362. " effectively forcing a parse of the buffer. Default is 0.
  363. let force_parsing = a:0 > 0 && a:1
  364. if s:Pyeval( 'ycm_state.ServerBecomesReady()' )
  365. " Server was not ready until now and could not parse previous requests for
  366. " the current buffer. We need to send them again.
  367. exec s:python_command "ycm_state.OnBufferVisit()"
  368. exec s:python_command "ycm_state.OnFileReadyToParse()"
  369. " Setting the omnifunc requires us to ask the server if it has a native
  370. " semantic completer for the current buffer's filetype. Since we only set it
  371. " when entering a buffer or changing the filetype, we try to set it again
  372. " now that the server is ready.
  373. call s:SetOmnicompleteFunc()
  374. return
  375. endif
  376. " We only want to send a new FileReadyToParse event notification if the buffer
  377. " has changed since the last time we sent one, or if forced.
  378. if force_parsing || b:changedtick != get( b:, 'ycm_changedtick', -1 )
  379. exec s:python_command "ycm_state.OnFileReadyToParse()"
  380. call timer_stop( s:pollers.file_parse_response.id )
  381. let s:pollers.file_parse_response.id = timer_start(
  382. \ s:pollers.file_parse_response.wait_milliseconds,
  383. \ function( 's:PollFileParseResponse' ) )
  384. let b:ycm_changedtick = b:changedtick
  385. endif
  386. endfunction
  387. function! s:PollFileParseResponse( ... )
  388. if !s:Pyeval( "ycm_state.FileParseRequestReady()" )
  389. let s:pollers.file_parse_response.id = timer_start(
  390. \ s:pollers.file_parse_response.wait_milliseconds,
  391. \ function( 's:PollFileParseResponse' ) )
  392. return
  393. endif
  394. exec s:python_command "ycm_state.HandleFileParseRequest()"
  395. endfunction
  396. function! s:SetCompleteFunc()
  397. let &completefunc = 'youcompleteme#Complete'
  398. let &l:completefunc = 'youcompleteme#Complete'
  399. endfunction
  400. function! s:SetOmnicompleteFunc()
  401. if s:Pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  402. let &omnifunc = 'youcompleteme#OmniComplete'
  403. let &l:omnifunc = 'youcompleteme#OmniComplete'
  404. " If we don't have native filetype support but the omnifunc is set to YCM's
  405. " omnifunc because the previous file the user was editing DID have native
  406. " support, we remove our omnifunc.
  407. elseif &omnifunc == 'youcompleteme#OmniComplete'
  408. let &omnifunc = ''
  409. let &l:omnifunc = ''
  410. endif
  411. endfunction
  412. function! s:OnCursorMovedNormalMode()
  413. if !s:AllowedToCompleteInCurrentBuffer()
  414. return
  415. endif
  416. exec s:python_command "ycm_state.OnCursorMoved()"
  417. endfunction
  418. function! s:OnTextChangedNormalMode()
  419. if !s:AllowedToCompleteInCurrentBuffer()
  420. return
  421. endif
  422. call s:OnFileReadyToParse()
  423. endfunction
  424. function! s:OnTextChangedInsertMode()
  425. if !s:AllowedToCompleteInCurrentBuffer()
  426. return
  427. endif
  428. exec s:python_command "ycm_state.OnCursorMoved()"
  429. call s:UpdateCursorMoved()
  430. call s:IdentifierFinishedOperations()
  431. if g:ycm_autoclose_preview_window_after_completion
  432. call s:ClosePreviewWindowIfNeeded()
  433. endif
  434. if g:ycm_auto_trigger || s:omnifunc_mode
  435. call s:InvokeCompletion()
  436. endif
  437. " We have to make sure we correctly leave omnifunc mode even when the user
  438. " inserts something like a "operator[]" candidate string which fails
  439. " CurrentIdentifierFinished check.
  440. if s:omnifunc_mode && !s:Pyeval( 'base.LastEnteredCharIsIdentifierChar()')
  441. let s:omnifunc_mode = 0
  442. endif
  443. endfunction
  444. function! s:OnInsertLeave()
  445. if !s:AllowedToCompleteInCurrentBuffer()
  446. return
  447. endif
  448. let s:omnifunc_mode = 0
  449. call s:OnFileReadyToParse()
  450. exec s:python_command "ycm_state.OnInsertLeave()"
  451. if g:ycm_autoclose_preview_window_after_completion ||
  452. \ g:ycm_autoclose_preview_window_after_insertion
  453. call s:ClosePreviewWindowIfNeeded()
  454. endif
  455. endfunction
  456. function! s:OnInsertEnter()
  457. if !s:AllowedToCompleteInCurrentBuffer()
  458. return
  459. endif
  460. let s:old_cursor_position = []
  461. call s:OnFileReadyToParse()
  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. endfunction
  592. function! s:DebugInfo()
  593. echom "Printing YouCompleteMe debug information..."
  594. let debug_info = s:Pyeval( 'ycm_state.DebugInfo()' )
  595. for line in split( debug_info, "\n" )
  596. echom '-- ' . line
  597. endfor
  598. endfunction
  599. function! s:ToggleLogs(...)
  600. exec s:python_command "ycm_state.ToggleLogs( *vim.eval( 'a:000' ) )"
  601. endfunction
  602. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  603. return join( s:Pyeval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  604. endfunction
  605. function! s:CompleterCommand(...)
  606. " CompleterCommand will call the OnUserCommand function of a completer.
  607. " If the first arguments is of the form "ft=..." it can be used to specify the
  608. " completer to use (for example "ft=cpp"). Else the native filetype completer
  609. " of the current buffer is used. If no native filetype completer is found and
  610. " no completer was specified this throws an error. You can use
  611. " "ft=ycm:ident" to select the identifier completer.
  612. " The remaining arguments will be passed to the completer.
  613. let arguments = copy(a:000)
  614. let completer = ''
  615. if a:0 > 0 && strpart(a:1, 0, 3) == 'ft='
  616. if a:1 == 'ft=ycm:ident'
  617. let completer = 'identifier'
  618. endif
  619. let arguments = arguments[1:]
  620. endif
  621. exec s:python_command "ycm_state.SendCommandRequest(" .
  622. \ "vim.eval( 'l:arguments' ), vim.eval( 'l:completer' ) )"
  623. endfunction
  624. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  625. return join( s:Pyeval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  626. endfunction
  627. function! youcompleteme#OpenGoToList()
  628. exec s:python_command "vimsupport.PostVimMessage(" .
  629. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  630. \ "Do NOT use it.' )"
  631. exec s:python_command "vimsupport.OpenQuickFixList( True, True )"
  632. endfunction
  633. function! s:ShowDiagnostics()
  634. exec s:python_command "ycm_state.ShowDiagnostics()"
  635. endfunction
  636. function! s:ShowDetailedDiagnostic()
  637. exec s:python_command "ycm_state.ShowDetailedDiagnostic()"
  638. endfunction
  639. function! s:ForceCompileAndDiagnostics()
  640. exec s:python_command "ycm_state.ForceCompileAndDiagnostics()"
  641. endfunction
  642. " This is basic vim plugin boilerplate
  643. let &cpo = s:save_cpo
  644. unlet s:save_cpo