youcompleteme.vim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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:moved_vertically_in_insert_mode = 0
  26. let s:previous_num_chars_on_current_line = strlen( getline('.') )
  27. let s:diagnostic_ui_filetypes = {
  28. \ 'cpp': 1,
  29. \ 'cs': 1,
  30. \ 'c': 1,
  31. \ 'objc': 1,
  32. \ 'objcpp': 1,
  33. \ }
  34. function! youcompleteme#Enable()
  35. " When vim is in diff mode, don't run
  36. if &diff
  37. return
  38. endif
  39. call s:SetUpBackwardsCompatibility()
  40. " This can be 0 if YCM libs are old or -1 if an exception occured while
  41. " executing the function.
  42. if s:SetUpPython() != 1
  43. return
  44. endif
  45. call s:SetUpCommands()
  46. call s:SetUpCpoptions()
  47. call s:SetUpCompleteopt()
  48. call s:SetUpKeyMappings()
  49. if g:ycm_show_diagnostics_ui
  50. call s:TurnOffSyntasticForCFamily()
  51. endif
  52. call s:SetUpSigns()
  53. call s:SetUpSyntaxHighlighting()
  54. if g:ycm_allow_changing_updatetime && &updatetime > 2000
  55. set ut=2000
  56. endif
  57. call youcompleteme#EnableCursorMovedAutocommands()
  58. augroup youcompleteme
  59. autocmd!
  60. " Note that these events will NOT trigger for the file vim is started with;
  61. " so if you do "vim foo.cc", these events will not trigger when that buffer
  62. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  63. " that happens *after" BufRead/BufEnter has already triggered for the
  64. " initial file.
  65. " We also need to trigger buf init code on the FileType event because when
  66. " the user does :enew and then :set ft=something, we need to run buf init
  67. " code again.
  68. autocmd BufReadPre * call s:OnBufferReadPre( expand( '<afile>:p' ) )
  69. autocmd BufRead,BufEnter,FileType * call s:OnBufferVisit()
  70. autocmd BufUnload * call s:OnBufferUnload( expand( '<afile>:p' ) )
  71. autocmd CursorHold,CursorHoldI * call s:OnCursorHold()
  72. autocmd InsertLeave * call s:OnInsertLeave()
  73. autocmd InsertEnter * call s:OnInsertEnter()
  74. autocmd VimLeave * call s:OnVimLeave()
  75. autocmd CompleteDone * call s:OnCompleteDone()
  76. augroup END
  77. " Calling these once solves the problem of BufReadPre/BufRead/BufEnter not
  78. " triggering for the first loaded file. This should be the last commands
  79. " executed in this function!
  80. call s:OnBufferReadPre( expand( '<afile>:p' ) )
  81. call s:OnBufferVisit()
  82. endfunction
  83. function! youcompleteme#EnableCursorMovedAutocommands()
  84. augroup ycmcompletemecursormove
  85. autocmd!
  86. autocmd CursorMovedI * call s:OnCursorMovedInsertMode()
  87. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  88. augroup END
  89. endfunction
  90. function! youcompleteme#DisableCursorMovedAutocommands()
  91. autocmd! ycmcompletemecursormove CursorMoved *
  92. autocmd! ycmcompletemecursormove CursorMovedI *
  93. endfunction
  94. function! s:SetUpPython() abort
  95. python << EOF
  96. import sys
  97. import vim
  98. import os
  99. import subprocess
  100. script_folder = vim.eval( 's:script_folder_path' )
  101. sys.path.insert( 0, os.path.join( script_folder, '../python' ) )
  102. sys.path.insert( 0, os.path.join( script_folder, '../third_party/ycmd' ) )
  103. from ycmd import utils
  104. utils.AddNearestThirdPartyFoldersToSysPath( script_folder )
  105. # We need to import ycmd's third_party folders as well since we import and
  106. # use ycmd code in the client.
  107. utils.AddNearestThirdPartyFoldersToSysPath( utils.__file__ )
  108. from ycm import base
  109. base.LoadJsonDefaultsIntoVim()
  110. from ycmd import user_options_store
  111. user_options_store.SetAll( base.BuildServerConf() )
  112. from ycm import paths, vimsupport
  113. popen_args = [ paths.PathToPythonInterpreter(),
  114. paths.PathToCheckCoreVersion() ]
  115. if utils.SafePopen( popen_args ).wait() == 2:
  116. vimsupport.PostVimMessage(
  117. 'YouCompleteMe unavailable: YCM support libs too old, PLEASE RECOMPILE' )
  118. vim.command( 'return 0' )
  119. from ycm.youcompleteme import YouCompleteMe
  120. ycm_state = YouCompleteMe( user_options_store.GetAll() )
  121. vim.command( 'return 1' )
  122. EOF
  123. endfunction
  124. function! s:SetUpKeyMappings()
  125. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  126. " exist and are now here purely for the sake of backwards compatibility; we
  127. " don't want to break users if we can avoid it.
  128. if exists('g:ycm_key_select_completion') &&
  129. \ index(g:ycm_key_list_select_completion,
  130. \ g:ycm_key_select_completion) == -1
  131. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  132. endif
  133. if exists('g:ycm_key_previous_completion') &&
  134. \ index(g:ycm_key_list_previous_completion,
  135. \ g:ycm_key_previous_completion) == -1
  136. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  137. endif
  138. for key in g:ycm_key_list_select_completion
  139. " With this command, when the completion window is visible, the tab key
  140. " (default) will select the next candidate in the window. In vim, this also
  141. " changes the typed-in text to that of the candidate completion.
  142. exe 'inoremap <expr>' . key .
  143. \ ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  144. endfor
  145. for key in g:ycm_key_list_previous_completion
  146. " This selects the previous candidate for shift-tab (default)
  147. exe 'inoremap <expr>' . key .
  148. \ ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  149. endfor
  150. if !empty( g:ycm_key_invoke_completion )
  151. let invoke_key = g:ycm_key_invoke_completion
  152. " Inside the console, <C-Space> is passed as <Nul> to Vim
  153. if invoke_key ==# '<C-Space>'
  154. imap <Nul> <C-Space>
  155. endif
  156. " <c-x><c-o> trigger omni completion, <c-p> deselects the first completion
  157. " candidate that vim selects by default
  158. silent! exe 'inoremap <unique> ' . invoke_key . ' <C-X><C-O><C-P>'
  159. endif
  160. if !empty( g:ycm_key_detailed_diagnostics )
  161. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  162. \ ' :YcmShowDetailedDiagnostic<cr>'
  163. endif
  164. endfunction
  165. function! s:SetUpSigns()
  166. " We try to ensure backwards compatibility with Syntastic if the user has
  167. " already defined styling for Syntastic highlight groups.
  168. if !hlexists( 'YcmErrorSign' )
  169. if hlexists( 'SyntasticErrorSign')
  170. highlight link YcmErrorSign SyntasticErrorSign
  171. else
  172. highlight link YcmErrorSign error
  173. endif
  174. endif
  175. if !hlexists( 'YcmWarningSign' )
  176. if hlexists( 'SyntasticWarningSign')
  177. highlight link YcmWarningSign SyntasticWarningSign
  178. else
  179. highlight link YcmWarningSign todo
  180. endif
  181. endif
  182. if !hlexists( 'YcmErrorLine' )
  183. highlight link YcmErrorLine SyntasticErrorLine
  184. endif
  185. if !hlexists( 'YcmWarningLine' )
  186. highlight link YcmWarningLine SyntasticWarningLine
  187. endif
  188. exe 'sign define YcmError text=' . g:ycm_error_symbol .
  189. \ ' texthl=YcmErrorSign linehl=YcmErrorLine'
  190. exe 'sign define YcmWarning text=' . g:ycm_warning_symbol .
  191. \ ' texthl=YcmWarningSign linehl=YcmWarningLine'
  192. endfunction
  193. function! s:SetUpSyntaxHighlighting()
  194. " We try to ensure backwards compatibility with Syntastic if the user has
  195. " already defined styling for Syntastic highlight groups.
  196. if !hlexists( 'YcmErrorSection' )
  197. if hlexists( 'SyntasticError' )
  198. highlight link YcmErrorSection SyntasticError
  199. else
  200. highlight link YcmErrorSection SpellBad
  201. endif
  202. endif
  203. if !hlexists( 'YcmWarningSection' )
  204. if hlexists( 'SyntasticWarning' )
  205. highlight link YcmWarningSection SyntasticWarning
  206. else
  207. highlight link YcmWarningSection SpellCap
  208. endif
  209. endif
  210. endfunction
  211. function! s:SetUpBackwardsCompatibility()
  212. let complete_in_comments_and_strings =
  213. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  214. if complete_in_comments_and_strings
  215. let g:ycm_complete_in_strings = 1
  216. let g:ycm_complete_in_comments = 1
  217. endif
  218. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  219. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  220. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  221. endif
  222. endfunction
  223. " Needed so that YCM is used instead of Syntastic
  224. function! s:TurnOffSyntasticForCFamily()
  225. let g:syntastic_cpp_checkers = []
  226. let g:syntastic_c_checkers = []
  227. let g:syntastic_objc_checkers = []
  228. let g:syntastic_objcpp_checkers = []
  229. endfunction
  230. function! s:DiagnosticUiSupportedForCurrentFiletype()
  231. return get( s:diagnostic_ui_filetypes, &filetype, 0 )
  232. endfunction
  233. function! s:AllowedToCompleteInCurrentFile()
  234. if empty( &filetype ) ||
  235. \ getbufvar( winbufnr( winnr() ), "&buftype" ) ==# 'nofile' ||
  236. \ &filetype ==# 'qf'
  237. return 0
  238. endif
  239. if exists( 'b:ycm_largefile' )
  240. return 0
  241. endif
  242. let whitelist_allows = has_key( g:ycm_filetype_whitelist, '*' ) ||
  243. \ has_key( g:ycm_filetype_whitelist, &filetype )
  244. let blacklist_allows = !has_key( g:ycm_filetype_blacklist, &filetype )
  245. return whitelist_allows && blacklist_allows
  246. endfunction
  247. function! s:SetUpCommands()
  248. command! YcmRestartServer call s:RestartServer()
  249. command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic()
  250. command! YcmDebugInfo call s:DebugInfo()
  251. command! -nargs=? -complete=custom,youcompleteme#LogsComplete
  252. \ YcmToggleLogs call s:ToggleLogs(<f-args>)
  253. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete
  254. \ YcmCompleter call s:CompleterCommand(<f-args>)
  255. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  256. command! YcmDiags call s:ShowDiagnostics()
  257. endfunction
  258. function! s:SetUpCpoptions()
  259. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  260. " no way to not have this and have YCM working, so force the flag.
  261. set cpoptions+=B
  262. " This prevents the display of "Pattern not found" & similar messages during
  263. " completion. This is only available since Vim 7.4.314
  264. if pyeval( 'vimsupport.VimVersionAtLeast("7.4.314")' )
  265. set shortmess+=c
  266. endif
  267. endfunction
  268. function! s:SetUpCompleteopt()
  269. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  270. " instance adding 'longest'. This breaks YCM. So we force our settings.
  271. " There's no two ways about this: if you want to use YCM then you have to
  272. " have these completeopt settings, otherwise YCM won't work at all.
  273. " We need menuone in completeopt, otherwise when there's only one candidate
  274. " for completion, the menu doesn't show up.
  275. set completeopt-=menu
  276. set completeopt+=menuone
  277. " This is unnecessary with our features. People use this option to insert
  278. " the common prefix of all the matches and then add more differentiating chars
  279. " so that they can select a more specific match. With our features, they
  280. " don't need to insert the prefix; they just type the differentiating chars.
  281. " Also, having this option set breaks the plugin.
  282. set completeopt-=longest
  283. if g:ycm_add_preview_to_completeopt
  284. set completeopt+=preview
  285. endif
  286. endfunction
  287. " For various functions/use-cases, we want to keep track of whether the buffer
  288. " has changed since the last time they were invoked. We keep the state of
  289. " b:changedtick of the last time the specific function was called in
  290. " b:ycm_changedtick.
  291. function! s:SetUpYcmChangedTick()
  292. let b:ycm_changedtick =
  293. \ get( b:, 'ycm_changedtick', {
  294. \ 'file_ready_to_parse' : -1,
  295. \ } )
  296. endfunction
  297. function! s:OnVimLeave()
  298. py ycm_state.OnVimLeave()
  299. endfunction
  300. function! s:OnCompleteDone()
  301. py ycm_state.OnCompleteDone()
  302. endfunction
  303. function! s:OnBufferReadPre(filename)
  304. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  305. if threshold > 0 && getfsize( a:filename ) > threshold
  306. echohl WarningMsg |
  307. \ echomsg "YouCompleteMe is disabled in this buffer; " .
  308. \ "the file exceeded the max size (see YCM options)." |
  309. \ echohl None
  310. let b:ycm_largefile = 1
  311. endif
  312. endfunction
  313. function! s:OnBufferVisit()
  314. " We need to do this even when we are not allowed to complete in the current
  315. " file because we might be allowed to complete in the future! The canonical
  316. " example is creating a new buffer with :enew and then setting a filetype.
  317. call s:SetUpYcmChangedTick()
  318. if !s:AllowedToCompleteInCurrentFile()
  319. return
  320. endif
  321. call s:SetUpCompleteopt()
  322. call s:SetCompleteFunc()
  323. py ycm_state.OnBufferVisit()
  324. call s:OnFileReadyToParse()
  325. endfunction
  326. function! s:OnBufferUnload( deleted_buffer_file )
  327. if !s:AllowedToCompleteInCurrentFile() || empty( a:deleted_buffer_file )
  328. return
  329. endif
  330. py ycm_state.OnBufferUnload( vim.eval( 'a:deleted_buffer_file' ) )
  331. endfunction
  332. function! s:OnCursorHold()
  333. if !s:AllowedToCompleteInCurrentFile()
  334. return
  335. endif
  336. call s:SetUpCompleteopt()
  337. call s:OnFileReadyToParse()
  338. endfunction
  339. function! s:OnFileReadyToParse()
  340. " We need to call this just in case there is no b:ycm_changetick; this can
  341. " happen for special buffers.
  342. call s:SetUpYcmChangedTick()
  343. " Order is important here; we need to extract any done diagnostics before
  344. " reparsing the file again. If we sent the new parse request first, then
  345. " the response would always be pending when we called
  346. " UpdateDiagnosticNotifications.
  347. call s:UpdateDiagnosticNotifications()
  348. let buffer_changed = b:changedtick != b:ycm_changedtick.file_ready_to_parse
  349. if buffer_changed
  350. py ycm_state.OnFileReadyToParse()
  351. endif
  352. let b:ycm_changedtick.file_ready_to_parse = b:changedtick
  353. endfunction
  354. function! s:SetCompleteFunc()
  355. let &completefunc = 'youcompleteme#Complete'
  356. let &l:completefunc = 'youcompleteme#Complete'
  357. endfunction
  358. function! s:SetOmnicompleteFunc()
  359. if pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  360. let &omnifunc = 'youcompleteme#OmniComplete'
  361. let &l:omnifunc = 'youcompleteme#OmniComplete'
  362. " If we don't have native filetype support but the omnifunc is set to YCM's
  363. " omnifunc because the previous file the user was editing DID have native
  364. " support, we remove our omnifunc.
  365. elseif &omnifunc == 'youcompleteme#OmniComplete'
  366. let &omnifunc = ''
  367. let &l:omnifunc = ''
  368. endif
  369. endfunction
  370. function! s:OnCursorMovedInsertMode()
  371. if !s:AllowedToCompleteInCurrentFile()
  372. return
  373. endif
  374. py ycm_state.OnCursorMoved()
  375. call s:UpdateCursorMoved()
  376. " Basically, we need to only trigger the completion menu when the user has
  377. " inserted or deleted a character, NOT just when the user moves in insert mode
  378. " (with, say, the arrow keys). If we trigger the menu even on pure moves, then
  379. " it's impossible to move in insert mode since the up/down arrows start moving
  380. " the selected completion in the completion menu. Yeah, people shouldn't be
  381. " moving in insert mode at all (that's what normal mode is for) but explain
  382. " that to the users who complain...
  383. if !s:BufferTextChangedSinceLastMoveInInsertMode()
  384. return
  385. endif
  386. call s:IdentifierFinishedOperations()
  387. if g:ycm_autoclose_preview_window_after_completion
  388. call s:ClosePreviewWindowIfNeeded()
  389. endif
  390. if g:ycm_auto_trigger || s:omnifunc_mode
  391. call s:InvokeCompletion()
  392. endif
  393. " We have to make sure we correctly leave omnifunc mode even when the user
  394. " inserts something like a "operator[]" candidate string which fails
  395. " CurrentIdentifierFinished check.
  396. if s:omnifunc_mode && !pyeval( 'base.LastEnteredCharIsIdentifierChar()')
  397. let s:omnifunc_mode = 0
  398. endif
  399. endfunction
  400. function! s:OnCursorMovedNormalMode()
  401. if !s:AllowedToCompleteInCurrentFile()
  402. return
  403. endif
  404. call s:OnFileReadyToParse()
  405. py ycm_state.OnCursorMoved()
  406. endfunction
  407. function! s:OnInsertLeave()
  408. if !s:AllowedToCompleteInCurrentFile()
  409. return
  410. endif
  411. let s:omnifunc_mode = 0
  412. call s:OnFileReadyToParse()
  413. py ycm_state.OnInsertLeave()
  414. if g:ycm_autoclose_preview_window_after_completion ||
  415. \ g:ycm_autoclose_preview_window_after_insertion
  416. call s:ClosePreviewWindowIfNeeded()
  417. endif
  418. endfunction
  419. function! s:OnInsertEnter()
  420. let s:previous_num_chars_on_current_line = strlen( getline('.') )
  421. if !s:AllowedToCompleteInCurrentFile()
  422. return
  423. endif
  424. if !get( b:, 'ycm_omnicomplete', 0 )
  425. let b:ycm_omnicomplete = 1
  426. call s:SetOmnicompleteFunc()
  427. endif
  428. let s:old_cursor_position = []
  429. endfunction
  430. function! s:UpdateCursorMoved()
  431. let current_position = getpos('.')
  432. let s:cursor_moved = current_position != s:old_cursor_position
  433. let s:moved_vertically_in_insert_mode = s:old_cursor_position != [] &&
  434. \ current_position[ 1 ] != s:old_cursor_position[ 1 ]
  435. let s:old_cursor_position = current_position
  436. endfunction
  437. function! s:BufferTextChangedSinceLastMoveInInsertMode()
  438. let num_chars_in_current_cursor_line = strlen( getline('.') )
  439. if s:moved_vertically_in_insert_mode
  440. let s:previous_num_chars_on_current_line = num_chars_in_current_cursor_line
  441. return 0
  442. endif
  443. let changed_text_on_current_line = num_chars_in_current_cursor_line !=
  444. \ s:previous_num_chars_on_current_line
  445. let s:previous_num_chars_on_current_line = num_chars_in_current_cursor_line
  446. return changed_text_on_current_line
  447. endfunction
  448. function! s:ClosePreviewWindowIfNeeded()
  449. let current_buffer_name = bufname('')
  450. " We don't want to try to close the preview window in special buffers like
  451. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  452. " with '['.
  453. if current_buffer_name[ 0 ] == '['
  454. return
  455. endif
  456. " This command does the actual closing of the preview window. If no preview
  457. " window is shown, nothing happens.
  458. pclose
  459. endfunction
  460. function! s:UpdateDiagnosticNotifications()
  461. let should_display_diagnostics = g:ycm_show_diagnostics_ui &&
  462. \ s:DiagnosticUiSupportedForCurrentFiletype()
  463. if !should_display_diagnostics
  464. return
  465. endif
  466. py ycm_state.UpdateDiagnosticInterface()
  467. endfunction
  468. function! s:IdentifierFinishedOperations()
  469. if !pyeval( 'base.CurrentIdentifierFinished()' )
  470. return
  471. endif
  472. py ycm_state.OnCurrentIdentifierFinished()
  473. let s:omnifunc_mode = 0
  474. endfunction
  475. " Returns 1 when inside comment and 2 when inside string
  476. function! s:InsideCommentOrString()
  477. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  478. " in insert mode when this func is called.
  479. let syntax_group = synIDattr( synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  480. if stridx(syntax_group, 'Comment') > -1
  481. return 1
  482. endif
  483. if stridx(syntax_group, 'String') > -1
  484. return 2
  485. endif
  486. return 0
  487. endfunction
  488. function! s:InsideCommentOrStringAndShouldStop()
  489. let retval = s:InsideCommentOrString()
  490. let inside_comment = retval == 1
  491. let inside_string = retval == 2
  492. if inside_comment && g:ycm_complete_in_comments ||
  493. \ inside_string && g:ycm_complete_in_strings
  494. return 0
  495. endif
  496. return retval
  497. endfunction
  498. function! s:OnBlankLine()
  499. return pyeval( 'not vim.current.line or vim.current.line.isspace()' )
  500. endfunction
  501. function! s:InvokeCompletion()
  502. if &completefunc != "youcompleteme#Complete"
  503. return
  504. endif
  505. if s:InsideCommentOrStringAndShouldStop() || s:OnBlankLine()
  506. return
  507. endif
  508. " This is tricky. First, having 'refresh' set to 'always' in the dictionary
  509. " that our completion function returns makes sure that our completion function
  510. " is called on every keystroke. Second, when the sequence of characters the
  511. " user typed produces no results in our search an infinite loop can occur. The
  512. " problem is that our feedkeys call triggers the OnCursorMovedI event which we
  513. " are tied to. We prevent this infinite loop from starting by making sure that
  514. " the user has moved the cursor since the last time we provided completion
  515. " results.
  516. if !s:cursor_moved
  517. return
  518. endif
  519. " <c-x><c-u> invokes the user's completion function (which we have set to
  520. " youcompleteme#Complete), and <c-p> tells Vim to select the previous
  521. " completion candidate. This is necessary because by default, Vim selects the
  522. " first candidate when completion is invoked, and selecting a candidate
  523. " automatically replaces the current text with it. Calling <c-p> forces Vim to
  524. " deselect the first candidate and in turn preserve the user's current text
  525. " until he explicitly chooses to replace it with a completion.
  526. call feedkeys( "\<C-X>\<C-U>\<C-P>", 'n' )
  527. endfunction
  528. python << EOF
  529. def GetCompletionsInner():
  530. request = ycm_state.GetCurrentCompletionRequest()
  531. request.Start()
  532. while not request.Done():
  533. if bool( int( vim.eval( 'complete_check()' ) ) ):
  534. return { 'words' : [], 'refresh' : 'always'}
  535. results = base.AdjustCandidateInsertionText( request.Response() )
  536. return { 'words' : results, 'refresh' : 'always' }
  537. EOF
  538. function! s:GetCompletions()
  539. py results = GetCompletionsInner()
  540. let results = pyeval( 'results' )
  541. return results
  542. endfunction
  543. " This is our main entry point. This is what vim calls to get completions.
  544. function! youcompleteme#Complete( findstart, base )
  545. " After the user types one character after the call to the omnifunc, the
  546. " completefunc will be called because of our mapping that calls the
  547. " completefunc on every keystroke. Therefore we need to delegate the call we
  548. " 'stole' back to the omnifunc
  549. if s:omnifunc_mode
  550. return youcompleteme#OmniComplete( a:findstart, a:base )
  551. endif
  552. if a:findstart
  553. " InvokeCompletion has this check but we also need it here because of random
  554. " Vim bugs and unfortunate interactions with the autocommands of other
  555. " plugins
  556. if !s:cursor_moved
  557. " for vim, -2 means not found but don't trigger an error message
  558. " see :h complete-functions
  559. return -2
  560. endif
  561. if !pyeval( 'ycm_state.IsServerAlive()' )
  562. return -2
  563. endif
  564. py ycm_state.CreateCompletionRequest()
  565. return pyeval( 'base.CompletionStartColumn()' )
  566. else
  567. return s:GetCompletions()
  568. endif
  569. endfunction
  570. function! youcompleteme#OmniComplete( findstart, base )
  571. if a:findstart
  572. if !pyeval( 'ycm_state.IsServerAlive()' )
  573. return -2
  574. endif
  575. let s:omnifunc_mode = 1
  576. py ycm_state.CreateCompletionRequest( force_semantic = True )
  577. return pyeval( 'base.CompletionStartColumn()' )
  578. else
  579. return s:GetCompletions()
  580. endif
  581. endfunction
  582. function! youcompleteme#ServerPid()
  583. return pyeval( 'ycm_state.ServerPid()' )
  584. endfunction
  585. function! s:RestartServer()
  586. py ycm_state.RestartServer()
  587. endfunction
  588. function! s:ShowDetailedDiagnostic()
  589. py ycm_state.ShowDetailedDiagnostic()
  590. endfunction
  591. function! s:DebugInfo()
  592. echom "Printing YouCompleteMe debug information..."
  593. let debug_info = pyeval( 'ycm_state.DebugInfo()' )
  594. for line in split( debug_info, "\n" )
  595. echom '-- ' . line
  596. endfor
  597. endfunction
  598. function! s:ToggleLogs(...)
  599. let stderr = a:0 == 0 || a:1 !=? 'Stdout'
  600. let stdout = a:0 == 0 || a:1 !=? 'Stderr'
  601. py ycm_state.ToggleLogs( stdout = vimsupport.GetBoolValue( 'l:stdout' ),
  602. \ stderr = vimsupport.GetBoolValue( 'l:stderr' ) )
  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. py ycm_state.SendCommandRequest( vim.eval( 'l:arguments' ),
  621. \ vim.eval( 'l:completer' ) )
  622. endfunction
  623. function! youcompleteme#OpenGoToList()
  624. set lazyredraw
  625. cclose
  626. execute 'belowright copen 3'
  627. set nolazyredraw
  628. au WinLeave <buffer> q " automatically leave, if an option is chosen
  629. redraw!
  630. endfunction
  631. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  632. return "Stdout\nStderr"
  633. endfunction
  634. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  635. return join( pyeval( 'ycm_state.GetDefinedSubcommands()' ),
  636. \ "\n")
  637. endfunction
  638. function! s:ForceCompile()
  639. if !pyeval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  640. echom "Native filetype completion not supported for current file, "
  641. \ . "cannot force recompilation."
  642. return 0
  643. endif
  644. echom "Forcing compilation, this will block Vim until done."
  645. py ycm_state.OnFileReadyToParse()
  646. while 1
  647. let diagnostics_ready = pyeval(
  648. \ 'ycm_state.DiagnosticsForCurrentFileReady()' )
  649. if diagnostics_ready
  650. break
  651. endif
  652. sleep 100m
  653. endwhile
  654. return 1
  655. endfunction
  656. function! s:ForceCompileAndDiagnostics()
  657. let compilation_succeeded = s:ForceCompile()
  658. if !compilation_succeeded
  659. return
  660. endif
  661. call s:UpdateDiagnosticNotifications()
  662. echom "Diagnostics refreshed."
  663. endfunction
  664. function! s:ShowDiagnostics()
  665. let compilation_succeeded = s:ForceCompile()
  666. if !compilation_succeeded
  667. return
  668. endif
  669. let diags = pyeval(
  670. \ 'ycm_state.GetDiagnosticsFromStoredRequest( qflist_format = True )' )
  671. if !empty( diags )
  672. call setloclist( 0, diags )
  673. if g:ycm_open_loclist_on_ycm_diags
  674. lopen
  675. endif
  676. else
  677. echom "No warnings or errors detected"
  678. endif
  679. endfunction
  680. " This is basic vim plugin boilerplate
  681. let &cpo = s:save_cpo
  682. unlet s:save_cpo