youcompleteme.vim 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. " Copyright (C) 2011-2018 YouCompleteMe contributors
  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:completion_stopped = 0
  24. " These two variables are initialized in youcompleteme#Enable.
  25. let s:default_completion = {}
  26. let s:completion = s:default_completion
  27. let s:default_signature_help = {}
  28. let s:signature_help = s:default_completion
  29. let s:previous_allowed_buffer_number = 0
  30. let s:pollers = {
  31. \ 'completion': {
  32. \ 'id': -1,
  33. \ 'wait_milliseconds': 10
  34. \ },
  35. \ 'signature_help': {
  36. \ 'id': -1,
  37. \ 'wait_milliseconds': 10
  38. \ },
  39. \ 'file_parse_response': {
  40. \ 'id': -1,
  41. \ 'wait_milliseconds': 100
  42. \ },
  43. \ 'server_ready': {
  44. \ 'id': -1,
  45. \ 'wait_milliseconds': 100
  46. \ },
  47. \ 'receive_messages': {
  48. \ 'id': -1,
  49. \ 'wait_milliseconds': 100
  50. \ }
  51. \ }
  52. let s:buftype_blacklist = {
  53. \ 'help': 1,
  54. \ 'terminal': 1,
  55. \ 'quickfix': 1
  56. \ }
  57. " When both versions are available, we prefer Python 3 over Python 2:
  58. " - faster startup (no monkey-patching from python-future);
  59. " - better Windows support (e.g. temporary paths are not returned in all
  60. " lowercase);
  61. " - Python 2 support will eventually be dropped.
  62. function! s:UsingPython3()
  63. if has('python3')
  64. return 1
  65. endif
  66. return 0
  67. endfunction
  68. let s:using_python3 = s:UsingPython3()
  69. let s:python_until_eof = s:using_python3 ? "python3 << EOF" : "python << EOF"
  70. let s:python_command = s:using_python3 ? "py3 " : "py "
  71. function! s:Pyeval( eval_string )
  72. if s:using_python3
  73. return py3eval( a:eval_string )
  74. endif
  75. return pyeval( a:eval_string )
  76. endfunction
  77. function! s:StartMessagePoll()
  78. if s:pollers.receive_messages.id < 0
  79. let s:pollers.receive_messages.id = timer_start(
  80. \ s:pollers.receive_messages.wait_milliseconds,
  81. \ function( 's:ReceiveMessages' ) )
  82. endif
  83. endfunction
  84. function! s:ReceiveMessages( timer_id )
  85. let poll_again = v:false
  86. if s:AllowedToCompleteInCurrentBuffer()
  87. let poll_again = s:Pyeval( 'ycm_state.OnPeriodicTick()' )
  88. endif
  89. if poll_again
  90. let s:pollers.receive_messages.id = timer_start(
  91. \ s:pollers.receive_messages.wait_milliseconds,
  92. \ function( 's:ReceiveMessages' ) )
  93. else
  94. " Don't poll again until we open another buffer
  95. let s:pollers.receive_messages.id = -1
  96. endif
  97. endfunction
  98. function! s:SetUpOptions()
  99. call s:SetUpCommands()
  100. call s:SetUpCpoptions()
  101. call s:SetUpCompleteopt()
  102. call s:SetUpKeyMappings()
  103. if g:ycm_show_diagnostics_ui
  104. call s:TurnOffSyntasticForCFamily()
  105. endif
  106. call s:SetUpSigns()
  107. call s:SetUpSyntaxHighlighting()
  108. endfunction
  109. function! youcompleteme#Enable()
  110. call s:SetUpBackwardsCompatibility()
  111. if !s:SetUpPython()
  112. return
  113. endif
  114. call s:SetUpOptions()
  115. call youcompleteme#EnableCursorMovedAutocommands()
  116. augroup youcompleteme
  117. autocmd!
  118. " Note that these events will NOT trigger for the file vim is started with;
  119. " so if you do "vim foo.cc", these events will not trigger when that buffer
  120. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  121. " that happens *after* FileType has already triggered for the initial file.
  122. " We don't parse the buffer on the BufRead event since it would only be
  123. " useful if the buffer filetype is set (we ignore the buffer if there is no
  124. " filetype) and if so, the FileType event has triggered before and thus the
  125. " buffer is already parsed.
  126. autocmd FileType * call s:OnFileTypeSet()
  127. autocmd BufEnter,CmdwinEnter * call s:OnBufferEnter()
  128. autocmd BufUnload * call s:OnBufferUnload()
  129. autocmd InsertLeave * call s:OnInsertLeave()
  130. autocmd VimLeave * call s:OnVimLeave()
  131. autocmd CompleteDone * call s:OnCompleteDone()
  132. if exists( '##CompleteChanged' )
  133. autocmd CompleteChanged * call s:OnCompleteChanged()
  134. endif
  135. autocmd BufEnter,WinEnter * call s:UpdateMatches()
  136. augroup END
  137. " The FileType event is not triggered for the first loaded file. We wait until
  138. " the server is ready to manually run the s:OnFileTypeSet function.
  139. let s:pollers.server_ready.id = timer_start(
  140. \ s:pollers.server_ready.wait_milliseconds,
  141. \ function( 's:PollServerReady' ) )
  142. let s:default_completion = s:Pyeval( 'vimsupport.NO_COMPLETIONS' )
  143. let s:completion = s:default_completion
  144. if exists( '*prop_type_add' ) && exists( '*prop_type_delete' )
  145. call prop_type_delete( 'YCM-signature-help-current-argument' )
  146. call prop_type_delete( 'YCM-signature-help-current-signature' )
  147. call prop_type_delete( 'YCM-signature-help-signature' )
  148. call prop_type_add( 'YCM-signature-help-current-argument', {
  149. \ 'highlight': 'PMenuSel',
  150. \ 'combine': 0,
  151. \ 'priority': 50,
  152. \ } )
  153. call prop_type_add( 'YCM-signature-help-current-signature', {
  154. \ 'highlight': 'PMenu',
  155. \ 'combine': 0,
  156. \ 'priority': 40,
  157. \ } )
  158. call prop_type_add( 'YCM-signature-help-signature', {
  159. \ 'highlight': 'PMenuSbar',
  160. \ 'combine': 0,
  161. \ 'priority': 40,
  162. \ } )
  163. endif
  164. endfunction
  165. function! youcompleteme#EnableCursorMovedAutocommands()
  166. augroup ycmcompletemecursormove
  167. autocmd!
  168. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  169. autocmd TextChanged * call s:OnTextChangedNormalMode()
  170. autocmd TextChangedI * call s:OnTextChangedInsertMode()
  171. " The TextChangedI event is not triggered when inserting a character while
  172. " the completion menu is open. We handle this by closing the completion menu
  173. " just before inserting a character.
  174. autocmd InsertCharPre * call s:OnInsertChar()
  175. augroup END
  176. endfunction
  177. function! youcompleteme#DisableCursorMovedAutocommands()
  178. autocmd! ycmcompletemecursormove
  179. endfunction
  180. function! youcompleteme#GetErrorCount()
  181. return s:Pyeval( 'ycm_state.GetErrorCount()' )
  182. endfunction
  183. function! youcompleteme#GetWarningCount()
  184. return s:Pyeval( 'ycm_state.GetWarningCount()' )
  185. endfunction
  186. function! s:SetUpPython() abort
  187. exec s:python_until_eof
  188. from __future__ import unicode_literals
  189. from __future__ import print_function
  190. from __future__ import division
  191. from __future__ import absolute_import
  192. import os.path as p
  193. import re
  194. import sys
  195. import traceback
  196. import vim
  197. root_folder = p.normpath( p.join( vim.eval( 's:script_folder_path' ), '..' ) )
  198. third_party_folder = p.join( root_folder, 'third_party' )
  199. python_stdlib_zip_regex = re.compile( 'python[23][0-9]\\.zip' )
  200. def IsStandardLibraryFolder( path ):
  201. return ( ( p.isfile( path )
  202. and python_stdlib_zip_regex.match( p.basename( path ) ) )
  203. or p.isfile( p.join( path, 'os.py' ) ) )
  204. def IsVirtualEnvLibraryFolder( path ):
  205. return p.isfile( p.join( path, 'orig-prefix.txt' ) )
  206. def GetStandardLibraryIndexInSysPath():
  207. for index, path in enumerate( sys.path ):
  208. if ( IsStandardLibraryFolder( path ) and
  209. not IsVirtualEnvLibraryFolder( path ) ):
  210. return index
  211. raise RuntimeError( 'Could not find standard library path in Python path.' )
  212. # Add dependencies to Python path.
  213. dependencies = [ p.join( root_folder, 'python' ),
  214. p.join( third_party_folder, 'requests-futures' ),
  215. p.join( third_party_folder, 'ycmd' ),
  216. p.join( third_party_folder, 'requests_deps', 'idna' ),
  217. p.join( third_party_folder, 'requests_deps', 'chardet' ),
  218. p.join( third_party_folder,
  219. 'requests_deps',
  220. 'urllib3',
  221. 'src' ),
  222. p.join( third_party_folder, 'requests_deps', 'certifi' ),
  223. p.join( third_party_folder, 'requests_deps', 'requests' ) ]
  224. # The concurrent.futures module is part of the standard library on Python 3.
  225. if sys.version_info[ 0 ] == 2:
  226. dependencies.append( p.join( third_party_folder, 'pythonfutures' ) )
  227. sys.path[ 0:0 ] = dependencies
  228. # We enclose this code in a try/except block to avoid backtraces in Vim.
  229. try:
  230. # The python-future module must be inserted after the standard library path.
  231. sys.path.insert( GetStandardLibraryIndexInSysPath() + 1,
  232. p.join( third_party_folder, 'python-future', 'src' ) )
  233. # Import the modules used in this file.
  234. from ycm import base, vimsupport, youcompleteme
  235. if 'ycm_state' in globals():
  236. # If re-initializing, pretend that we shut down
  237. ycm_state.OnVimLeave()
  238. del ycm_state
  239. ycm_state = youcompleteme.YouCompleteMe()
  240. except Exception as error:
  241. # We don't use PostVimMessage or EchoText from the vimsupport module because
  242. # importing this module may fail.
  243. vim.command( 'redraw | echohl WarningMsg' )
  244. for line in traceback.format_exc().splitlines():
  245. vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) )
  246. vim.command( "echo 'YouCompleteMe unavailable: {0}'"
  247. .format( str( error ).replace( "'", "''" ) ) )
  248. vim.command( 'echohl None' )
  249. vim.command( 'return 0' )
  250. else:
  251. vim.command( 'return 1' )
  252. EOF
  253. endfunction
  254. function! s:SetUpKeyMappings()
  255. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  256. " exist and are now here purely for the sake of backwards compatibility; we
  257. " don't want to break users if we can avoid it.
  258. if exists('g:ycm_key_select_completion') &&
  259. \ index(g:ycm_key_list_select_completion,
  260. \ g:ycm_key_select_completion) == -1
  261. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  262. endif
  263. if exists('g:ycm_key_previous_completion') &&
  264. \ index(g:ycm_key_list_previous_completion,
  265. \ g:ycm_key_previous_completion) == -1
  266. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  267. endif
  268. for key in g:ycm_key_list_select_completion
  269. " With this command, when the completion window is visible, the tab key
  270. " (default) will select the next candidate in the window. In vim, this also
  271. " changes the typed-in text to that of the candidate completion.
  272. exe 'inoremap <expr>' . key .
  273. \ ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  274. endfor
  275. for key in g:ycm_key_list_previous_completion
  276. " This selects the previous candidate for shift-tab (default)
  277. exe 'inoremap <expr>' . key .
  278. \ ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  279. endfor
  280. for key in g:ycm_key_list_stop_completion
  281. " When selecting a candidate and closing the completion menu with the <C-y>
  282. " key, the menu will automatically be reopened because of the TextChangedI
  283. " event. We define a command to prevent that.
  284. exe 'inoremap <expr>' . key . ' <SID>StopCompletion( "\' . key . '" )'
  285. endfor
  286. if !empty( g:ycm_key_invoke_completion )
  287. let invoke_key = g:ycm_key_invoke_completion
  288. " Inside the console, <C-Space> is passed as <Nul> to Vim
  289. if invoke_key ==# '<C-Space>'
  290. imap <Nul> <C-Space>
  291. endif
  292. silent! exe 'inoremap <unique> <silent> ' . invoke_key .
  293. \ ' <C-R>=<SID>RequestSemanticCompletion()<CR>'
  294. endif
  295. if !empty( g:ycm_key_detailed_diagnostics )
  296. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  297. \ ' :YcmShowDetailedDiagnostic<CR>'
  298. endif
  299. " The TextChangedI event is not triggered when deleting a character while the
  300. " completion menu is open. We handle this by closing the completion menu on
  301. " the keys that delete a character in insert mode.
  302. for key in [ "<BS>", "<C-h>" ]
  303. silent! exe 'inoremap <unique> <expr> ' . key .
  304. \ ' <SID>OnDeleteChar( "\' . key . '" )'
  305. endfor
  306. endfunction
  307. function! s:SetUpSigns()
  308. " We try to ensure backwards compatibility with Syntastic if the user has
  309. " already defined styling for Syntastic highlight groups.
  310. if !hlexists( 'YcmErrorSign' )
  311. if hlexists( 'SyntasticErrorSign')
  312. highlight link YcmErrorSign SyntasticErrorSign
  313. else
  314. highlight link YcmErrorSign error
  315. endif
  316. endif
  317. if !hlexists( 'YcmWarningSign' )
  318. if hlexists( 'SyntasticWarningSign')
  319. highlight link YcmWarningSign SyntasticWarningSign
  320. else
  321. highlight link YcmWarningSign todo
  322. endif
  323. endif
  324. if !hlexists( 'YcmErrorLine' )
  325. highlight link YcmErrorLine SyntasticErrorLine
  326. endif
  327. if !hlexists( 'YcmWarningLine' )
  328. highlight link YcmWarningLine SyntasticWarningLine
  329. endif
  330. exe 'sign define YcmError text=' . g:ycm_error_symbol .
  331. \ ' texthl=YcmErrorSign linehl=YcmErrorLine'
  332. exe 'sign define YcmWarning text=' . g:ycm_warning_symbol .
  333. \ ' texthl=YcmWarningSign linehl=YcmWarningLine'
  334. endfunction
  335. function! s:SetUpSyntaxHighlighting()
  336. " We try to ensure backwards compatibility with Syntastic if the user has
  337. " already defined styling for Syntastic highlight groups.
  338. if !hlexists( 'YcmErrorSection' )
  339. if hlexists( 'SyntasticError' )
  340. highlight link YcmErrorSection SyntasticError
  341. else
  342. highlight link YcmErrorSection SpellBad
  343. endif
  344. endif
  345. if !hlexists( 'YcmWarningSection' )
  346. if hlexists( 'SyntasticWarning' )
  347. highlight link YcmWarningSection SyntasticWarning
  348. else
  349. highlight link YcmWarningSection SpellCap
  350. endif
  351. endif
  352. endfunction
  353. function! s:SetUpBackwardsCompatibility()
  354. let complete_in_comments_and_strings =
  355. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  356. if complete_in_comments_and_strings
  357. let g:ycm_complete_in_strings = 1
  358. let g:ycm_complete_in_comments = 1
  359. endif
  360. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  361. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  362. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  363. endif
  364. endfunction
  365. " Needed so that YCM is used instead of Syntastic
  366. function! s:TurnOffSyntasticForCFamily()
  367. let g:syntastic_cpp_checkers = []
  368. let g:syntastic_c_checkers = []
  369. let g:syntastic_objc_checkers = []
  370. let g:syntastic_objcpp_checkers = []
  371. let g:syntastic_cuda_checkers = []
  372. endfunction
  373. function! s:DisableOnLargeFile( buffer )
  374. if exists( 'b:ycm_largefile' )
  375. return b:ycm_largefile
  376. endif
  377. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  378. let b:ycm_largefile =
  379. \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold
  380. if b:ycm_largefile
  381. exec s:python_command "vimsupport.PostVimMessage(" .
  382. \ "'YouCompleteMe is disabled in this buffer; " .
  383. \ "the file exceeded the max size (see YCM options).' )"
  384. endif
  385. return b:ycm_largefile
  386. endfunction
  387. function! s:AllowedToCompleteInBuffer( buffer )
  388. let buftype = getbufvar( a:buffer, '&buftype' )
  389. if has_key( s:buftype_blacklist, buftype )
  390. return 0
  391. endif
  392. let filetype = getbufvar( a:buffer, '&filetype' )
  393. if empty( filetype ) || s:DisableOnLargeFile( a:buffer )
  394. return 0
  395. endif
  396. let whitelist_allows = type( g:ycm_filetype_whitelist ) != type( {} ) ||
  397. \ has_key( g:ycm_filetype_whitelist, '*' ) ||
  398. \ has_key( g:ycm_filetype_whitelist, filetype )
  399. let blacklist_allows = type( g:ycm_filetype_blacklist ) != type( {} ) ||
  400. \ !has_key( g:ycm_filetype_blacklist, filetype )
  401. let allowed = whitelist_allows && blacklist_allows
  402. if allowed
  403. let s:previous_allowed_buffer_number = bufnr( a:buffer )
  404. endif
  405. return allowed
  406. endfunction
  407. function! s:AllowedToCompleteInCurrentBuffer()
  408. return s:AllowedToCompleteInBuffer( '%' )
  409. endfunction
  410. function! s:VisitedBufferRequiresReparse()
  411. if bufnr( '%' ) ==# s:previous_allowed_buffer_number
  412. return 0
  413. endif
  414. return s:AllowedToCompleteInCurrentBuffer()
  415. endfunction
  416. function! s:SetUpCpoptions()
  417. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  418. " no way to not have this and have YCM working, so force the flag.
  419. set cpoptions+=B
  420. " This prevents the display of "Pattern not found" & similar messages during
  421. " completion.
  422. set shortmess+=c
  423. endfunction
  424. function! s:SetUpCompleteopt()
  425. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  426. " instance adding 'longest'. This breaks YCM. So we force our settings.
  427. " There's no two ways about this: if you want to use YCM then you have to
  428. " have these completeopt settings, otherwise YCM won't work at all.
  429. " We need menuone in completeopt, otherwise when there's only one candidate
  430. " for completion, the menu doesn't show up.
  431. set completeopt-=menu
  432. set completeopt+=menuone
  433. " This is unnecessary with our features. People use this option to insert
  434. " the common prefix of all the matches and then add more differentiating chars
  435. " so that they can select a more specific match. With our features, they
  436. " don't need to insert the prefix; they just type the differentiating chars.
  437. " Also, having this option set breaks the plugin.
  438. set completeopt-=longest
  439. if g:ycm_add_preview_to_completeopt
  440. set completeopt+=preview
  441. endif
  442. endfunction
  443. function! s:SetCompleteFunc()
  444. let &completefunc = 'youcompleteme#CompleteFunc'
  445. endfunction
  446. function s:StopPoller( poller ) abort
  447. call timer_stop( a:poller.id )
  448. let a:poller.id = -1
  449. endfunction
  450. function! s:OnVimLeave()
  451. " Workaround a NeoVim issue - not shutting down timers correctly
  452. " https://github.com/neovim/neovim/issues/6840
  453. for poller in values( s:pollers )
  454. call s:StopPoller( poller )
  455. endfor
  456. exec s:python_command "ycm_state.OnVimLeave()"
  457. endfunction
  458. function! s:OnCompleteDone()
  459. if !s:AllowedToCompleteInCurrentBuffer()
  460. return
  461. endif
  462. exec s:python_command "ycm_state.OnCompleteDone()"
  463. call s:UpdateSignatureHelp()
  464. endfunction
  465. function! s:OnCompleteChanged()
  466. if !s:AllowedToCompleteInCurrentBuffer()
  467. return
  468. endif
  469. call s:UpdateSignatureHelp()
  470. endfunction
  471. function! s:OnFileTypeSet()
  472. " The contents of the command-line window are empty when the filetype is set
  473. " for the first time. Users should never change its filetype so we only rely
  474. " on the CmdwinEnter event for that window.
  475. if !empty( getcmdwintype() )
  476. return
  477. endif
  478. if !s:AllowedToCompleteInCurrentBuffer()
  479. return
  480. endif
  481. call s:SetUpCompleteopt()
  482. call s:SetCompleteFunc()
  483. call s:StartMessagePoll()
  484. exec s:python_command "ycm_state.OnFileTypeSet()"
  485. call s:OnFileReadyToParse( 1 )
  486. endfunction
  487. function! s:OnBufferEnter()
  488. call s:StartMessagePoll()
  489. if !s:VisitedBufferRequiresReparse()
  490. return
  491. endif
  492. call s:SetUpCompleteopt()
  493. call s:SetCompleteFunc()
  494. exec s:python_command "ycm_state.OnBufferVisit()"
  495. " Last parse may be outdated because of changes from other buffers. Force a
  496. " new parse.
  497. call s:OnFileReadyToParse( 1 )
  498. endfunction
  499. function! s:OnBufferUnload()
  500. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  501. " it as a true number for the getbufvar function.
  502. let buffer_number = str2nr( expand( '<abuf>' ) )
  503. if !s:AllowedToCompleteInBuffer( buffer_number )
  504. return
  505. endif
  506. exec s:python_command "ycm_state.OnBufferUnload( " . buffer_number . " )"
  507. endfunction
  508. function! s:UpdateMatches()
  509. exec s:python_command "ycm_state.UpdateMatches()"
  510. endfunction
  511. function! s:PollServerReady( timer_id )
  512. if !s:Pyeval( 'ycm_state.IsServerAlive()' )
  513. exec s:python_command "ycm_state.NotifyUserIfServerCrashed()"
  514. " Server crashed. Don't poll it again.
  515. return
  516. endif
  517. if !s:Pyeval( 'ycm_state.CheckIfServerIsReady()' )
  518. let s:pollers.server_ready.id = timer_start(
  519. \ s:pollers.server_ready.wait_milliseconds,
  520. \ function( 's:PollServerReady' ) )
  521. return
  522. endif
  523. call s:OnFileTypeSet()
  524. endfunction
  525. function! s:OnFileReadyToParse( ... )
  526. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  527. " FileReadyToParse event notification, whether the buffer has changed or not;
  528. " effectively forcing a parse of the buffer. Default is 0.
  529. let force_parsing = a:0 > 0 && a:1
  530. " We only want to send a new FileReadyToParse event notification if the buffer
  531. " has changed since the last time we sent one, or if forced.
  532. if force_parsing || s:Pyeval( "ycm_state.NeedsReparse()" )
  533. " We switched buffers or somethuing, so claer.
  534. " FIXME: sig hekp should be buffer local?
  535. call s:ClearSignatureHelp()
  536. exec s:python_command "ycm_state.OnFileReadyToParse()"
  537. call s:StopPoller( s:pollers.file_parse_response )
  538. let s:pollers.file_parse_response.id = timer_start(
  539. \ s:pollers.file_parse_response.wait_milliseconds,
  540. \ function( 's:PollFileParseResponse' ) )
  541. endif
  542. endfunction
  543. function! s:PollFileParseResponse( ... )
  544. if !s:Pyeval( "ycm_state.FileParseRequestReady()" )
  545. let s:pollers.file_parse_response.id = timer_start(
  546. \ s:pollers.file_parse_response.wait_milliseconds,
  547. \ function( 's:PollFileParseResponse' ) )
  548. return
  549. endif
  550. exec s:python_command "ycm_state.HandleFileParseRequest()"
  551. if s:Pyeval( "ycm_state.ShouldResendFileParseRequest()" )
  552. call s:OnFileReadyToParse( 1 )
  553. endif
  554. endfunction
  555. function! s:SendKeys( keys )
  556. " By default keys are added to the end of the typeahead buffer. If there are
  557. " already keys in the buffer, they will be processed first and may change the
  558. " state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in normal
  559. " mode instead of insert mode or <C-e> outside of completion mode). We avoid
  560. " that by inserting the keys at the start of the typeahead buffer with the 'i'
  561. " option. Also, we don't want the keys to be remapped to something else so we
  562. " add the 'n' option.
  563. call feedkeys( a:keys, 'in' )
  564. endfunction
  565. function! s:CloseCompletionMenu()
  566. if pumvisible()
  567. call s:SendKeys( "\<C-e>" )
  568. endif
  569. endfunction
  570. function! s:OnInsertChar()
  571. if !s:AllowedToCompleteInCurrentBuffer()
  572. return
  573. endif
  574. call s:StopPoller( s:pollers.completion )
  575. call s:CloseCompletionMenu()
  576. call s:StopPoller( s:pollers.signature_help )
  577. endfunction
  578. function! s:OnDeleteChar( key )
  579. if !s:AllowedToCompleteInCurrentBuffer()
  580. return a:key
  581. endif
  582. call s:StopPoller( s:pollers.completion )
  583. call s:StopPoller( s:pollers.signature_help )
  584. if pumvisible()
  585. return "\<C-y>" . a:key
  586. endif
  587. return a:key
  588. endfunction
  589. function! s:StopCompletion( key )
  590. call s:StopPoller( s:pollers.completion )
  591. call s:ClearSignatureHelp()
  592. if pumvisible()
  593. let s:completion_stopped = 1
  594. return "\<C-y>"
  595. endif
  596. return a:key
  597. endfunction
  598. function! s:OnCursorMovedNormalMode()
  599. if !s:AllowedToCompleteInCurrentBuffer()
  600. return
  601. endif
  602. exec s:python_command "ycm_state.OnCursorMoved()"
  603. endfunction
  604. function! s:OnTextChangedNormalMode()
  605. if !s:AllowedToCompleteInCurrentBuffer()
  606. return
  607. endif
  608. call s:OnFileReadyToParse()
  609. endfunction
  610. function! s:OnTextChangedInsertMode()
  611. if !s:AllowedToCompleteInCurrentBuffer()
  612. return
  613. endif
  614. if s:completion_stopped
  615. let s:completion_stopped = 0
  616. let s:completion = s:default_completion
  617. return
  618. endif
  619. call s:IdentifierFinishedOperations()
  620. " We have to make sure we correctly leave semantic mode even when the user
  621. " inserts something like a "operator[]" candidate string which fails
  622. " CurrentIdentifierFinished check.
  623. if s:force_semantic && !s:Pyeval( 'base.LastEnteredCharIsIdentifierChar()' )
  624. let s:force_semantic = 0
  625. endif
  626. if &completefunc == "youcompleteme#CompleteFunc" &&
  627. \ ( g:ycm_auto_trigger || s:force_semantic ) &&
  628. \ !s:InsideCommentOrStringAndShouldStop() &&
  629. \ !s:OnBlankLine()
  630. " Immediately call previous completion to avoid flickers.
  631. call s:Complete()
  632. call s:RequestCompletion()
  633. call s:UpdateSignatureHelp()
  634. call s:RequestSignatureHelp()
  635. endif
  636. exec s:python_command "ycm_state.OnCursorMoved()"
  637. if g:ycm_autoclose_preview_window_after_completion
  638. call s:ClosePreviewWindowIfNeeded()
  639. endif
  640. endfunction
  641. function! s:OnInsertLeave()
  642. if !s:AllowedToCompleteInCurrentBuffer()
  643. return
  644. endif
  645. call s:StopPoller( s:pollers.completion )
  646. let s:force_semantic = 0
  647. let s:completion = s:default_completion
  648. call s:OnFileReadyToParse()
  649. exec s:python_command "ycm_state.OnInsertLeave()"
  650. if g:ycm_autoclose_preview_window_after_completion ||
  651. \ g:ycm_autoclose_preview_window_after_insertion
  652. call s:ClosePreviewWindowIfNeeded()
  653. endif
  654. call s:ClearSignatureHelp()
  655. endfunction
  656. function! s:ClosePreviewWindowIfNeeded()
  657. let current_buffer_name = bufname('')
  658. " We don't want to try to close the preview window in special buffers like
  659. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  660. " with '['.
  661. if current_buffer_name[ 0 ] == '['
  662. return
  663. endif
  664. " This command does the actual closing of the preview window. If no preview
  665. " window is shown, nothing happens.
  666. pclose
  667. endfunction
  668. function! s:IdentifierFinishedOperations()
  669. if !s:Pyeval( 'base.CurrentIdentifierFinished()' )
  670. return
  671. endif
  672. exec s:python_command "ycm_state.OnCurrentIdentifierFinished()"
  673. let s:force_semantic = 0
  674. let s:completion = s:default_completion
  675. endfunction
  676. " Returns 1 when inside comment and 2 when inside string
  677. function! s:InsideCommentOrString()
  678. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  679. " in insert mode when this func is called.
  680. let syntax_group = synIDattr(
  681. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  682. if stridx(syntax_group, 'Comment') > -1
  683. return 1
  684. endif
  685. if stridx(syntax_group, 'String') > -1
  686. return 2
  687. endif
  688. return 0
  689. endfunction
  690. function! s:InsideCommentOrStringAndShouldStop()
  691. let retval = s:InsideCommentOrString()
  692. let inside_comment = retval == 1
  693. let inside_string = retval == 2
  694. if inside_comment && g:ycm_complete_in_comments ||
  695. \ inside_string && g:ycm_complete_in_strings
  696. return 0
  697. endif
  698. return retval
  699. endfunction
  700. function! s:OnBlankLine()
  701. return s:Pyeval( 'not vim.current.line or vim.current.line.isspace()' )
  702. endfunction
  703. function! s:RequestCompletion()
  704. exec s:python_command "ycm_state.SendCompletionRequest(" .
  705. \ "vimsupport.GetBoolValue( 's:force_semantic' ) )"
  706. call s:PollCompletion()
  707. endfunction
  708. function! s:RequestSemanticCompletion()
  709. if &completefunc == "youcompleteme#CompleteFunc"
  710. let s:force_semantic = 1
  711. exec s:python_command "ycm_state.SendCompletionRequest( True )"
  712. call s:PollCompletion()
  713. endif
  714. " Since this function is called in a mapping through the expression register
  715. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  716. " insert anything so we return an empty string.
  717. return ''
  718. endfunction
  719. function! s:PollCompletion( ... )
  720. if !s:Pyeval( 'ycm_state.CompletionRequestReady()' )
  721. let s:pollers.completion.id = timer_start(
  722. \ s:pollers.completion.wait_milliseconds,
  723. \ function( 's:PollCompletion' ) )
  724. return
  725. endif
  726. let s:completion = s:Pyeval( 'ycm_state.GetCompletionResponse()' )
  727. call s:Complete()
  728. endfunction
  729. function! s:ShouldUseSignatureHelp()
  730. return s:Pyeval( 'vimsupport.VimSupportsPopupWindows()' )
  731. endfunction
  732. function! s:RequestSignatureHelp()
  733. if !s:ShouldUseSignatureHelp()
  734. return
  735. endif
  736. if s:pollers.signature_help.id >= 0
  737. " We're already polling.
  738. return
  739. endif
  740. if s:Pyeval( 'ycm_state.SendSignatureHelpRequest()' )
  741. call s:PollSignatureHelp()
  742. endif
  743. endfunction
  744. function! s:PollSignatureHelp( ... )
  745. if !s:ShouldUseSignatureHelp()
  746. return
  747. endif
  748. if a:0 == 0 && s:pollers.signature_help.id >= 0
  749. " OK this is a bug. We have tried to poll for a response while the timer is
  750. " already running. Just return and wait for the timer to fire.
  751. return
  752. endif
  753. if !s:Pyeval( 'ycm_state.SignatureHelpRequestReady()' )
  754. let s:pollers.signature_help.id = timer_start(
  755. \ s:pollers.signature_help.wait_milliseconds,
  756. \ function( 's:PollSignatureHelp' ) )
  757. return
  758. endif
  759. let s:signature_help = s:Pyeval( 'ycm_state.GetSignatureHelpResponse()' )
  760. call s:UpdateSignatureHelp()
  761. endfunction
  762. function! s:Complete()
  763. " Do not call user's completion function if the start column is after the
  764. " current column or if there are no candidates. Close the completion menu
  765. " instead. This avoids keeping the user in completion mode.
  766. if s:completion.completion_start_column > s:completion.column ||
  767. \ empty( s:completion.completions )
  768. call s:CloseCompletionMenu()
  769. else
  770. " <c-x><c-u> invokes the user's completion function (which we have set to
  771. " youcompleteme#CompleteFunc), and <c-p> tells Vim to select the previous
  772. " completion candidate. This is necessary because by default, Vim selects
  773. " the first candidate when completion is invoked, and selecting a candidate
  774. " automatically replaces the current text with it. Calling <c-p> forces Vim
  775. " to deselect the first candidate and in turn preserve the user's current
  776. " text until he explicitly chooses to replace it with a completion.
  777. call s:SendKeys( "\<C-X>\<C-U>\<C-P>" )
  778. endif
  779. " Displaying or hiding the PUM might mean we need to hide the sig help
  780. call s:UpdateSignatureHelp()
  781. endfunction
  782. function! youcompleteme#CompleteFunc( findstart, base )
  783. if a:findstart
  784. " When auto-wrapping is enabled, Vim wraps the current line after the
  785. " completion request is sent but before calling this function. The starting
  786. " column returned by the server is invalid in that case and must be
  787. " recomputed.
  788. if s:completion.line != line( '.' )
  789. " Given
  790. " scb: column where the completion starts before auto-wrapping
  791. " cb: cursor column before auto-wrapping
  792. " sca: column where the completion starts after auto-wrapping
  793. " ca: cursor column after auto-wrapping
  794. " we have
  795. " ca - sca = cb - scb
  796. " sca = scb + ca - cb
  797. let s:completion.completion_start_column +=
  798. \ col( '.' ) - s:completion.column
  799. endif
  800. return s:completion.completion_start_column - 1
  801. endif
  802. return s:completion.completions
  803. endfunction
  804. function! s:UpdateSignatureHelp()
  805. if !s:ShouldUseSignatureHelp()
  806. return
  807. endif
  808. call s:Pyeval(
  809. \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' )
  810. endfunction
  811. function! s:ClearSignatureHelp()
  812. if !s:ShouldUseSignatureHelp()
  813. return
  814. endif
  815. call s:StopPoller( s:pollers.signature_help )
  816. let s:signature_help = s:default_signature_help
  817. call s:Pyeval( 'ycm_state.ClearSignatureHelp()' )
  818. endfunction
  819. function! youcompleteme#ServerPid()
  820. return s:Pyeval( 'ycm_state.ServerPid()' )
  821. endfunction
  822. function! s:SetUpCommands()
  823. command! YcmRestartServer call s:RestartServer()
  824. command! YcmDebugInfo call s:DebugInfo()
  825. command! -nargs=* -complete=custom,youcompleteme#LogsComplete
  826. \ YcmToggleLogs call s:ToggleLogs(<f-args>)
  827. if s:Pyeval( 'vimsupport.VimVersionAtLeast( "7.4.1898" )' )
  828. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  829. \ YcmCompleter call s:CompleterCommand(<q-mods>,
  830. \ <count>,
  831. \ <line1>,
  832. \ <line2>,
  833. \ <f-args>)
  834. else
  835. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  836. \ YcmCompleter call s:CompleterCommand('',
  837. \ <count>,
  838. \ <line1>,
  839. \ <line2>,
  840. \ <f-args>)
  841. endif
  842. command! YcmDiags call s:ShowDiagnostics()
  843. command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic()
  844. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  845. endfunction
  846. function! s:RestartServer()
  847. call s:SetUpOptions()
  848. exec s:python_command "ycm_state.RestartServer()"
  849. call s:StopPoller( s:pollers.receive_messages )
  850. call s:ClearSignatureHelp()
  851. call s:StopPoller( s:pollers.server_ready )
  852. let s:pollers.server_ready.id = timer_start(
  853. \ s:pollers.server_ready.wait_milliseconds,
  854. \ function( 's:PollServerReady' ) )
  855. endfunction
  856. function! s:DebugInfo()
  857. echom "Printing YouCompleteMe debug information..."
  858. let debug_info = s:Pyeval( 'ycm_state.DebugInfo()' )
  859. for line in split( debug_info, "\n" )
  860. echom '-- ' . line
  861. endfor
  862. endfunction
  863. function! s:ToggleLogs(...)
  864. exec s:python_command "ycm_state.ToggleLogs( *vim.eval( 'a:000' ) )"
  865. endfunction
  866. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  867. return join( s:Pyeval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  868. endfunction
  869. function! s:CompleterCommand( mods, count, line1, line2, ... )
  870. exec s:python_command "ycm_state.SendCommandRequest(" .
  871. \ "vim.eval( 'a:000' )," .
  872. \ "vim.eval( 'a:mods' )," .
  873. \ "vimsupport.GetBoolValue( 'a:count != -1' )," .
  874. \ "vimsupport.GetIntValue( 'a:line1' )," .
  875. \ "vimsupport.GetIntValue( 'a:line2' ) )"
  876. endfunction
  877. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  878. return join( s:Pyeval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  879. endfunction
  880. function! youcompleteme#OpenGoToList()
  881. exec s:python_command "vimsupport.PostVimMessage(" .
  882. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  883. \ "Do NOT use it.' )"
  884. exec s:python_command "vimsupport.OpenQuickFixList( True, True )"
  885. endfunction
  886. function! s:ShowDiagnostics()
  887. exec s:python_command "ycm_state.ShowDiagnostics()"
  888. endfunction
  889. function! s:ShowDetailedDiagnostic()
  890. exec s:python_command "ycm_state.ShowDetailedDiagnostic()"
  891. endfunction
  892. function! s:ForceCompileAndDiagnostics()
  893. exec s:python_command "ycm_state.ForceCompileAndDiagnostics()"
  894. endfunction
  895. " This is basic vim plugin boilerplate
  896. let &cpo = s:save_cpo
  897. unlet s:save_cpo