youcompleteme.vim 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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:OnVimLeave()
  447. " Workaround a NeoVim issue - not shutting down timers correctly
  448. " https://github.com/neovim/neovim/issues/6840
  449. for poller in values( s:pollers )
  450. call timer_stop( poller.id )
  451. endfor
  452. exec s:python_command "ycm_state.OnVimLeave()"
  453. endfunction
  454. function! s:OnCompleteDone()
  455. if !s:AllowedToCompleteInCurrentBuffer()
  456. return
  457. endif
  458. exec s:python_command "ycm_state.OnCompleteDone()"
  459. call s:UpdateSignatureHelp()
  460. endfunction
  461. function! s:OnCompleteChanged()
  462. if !s:AllowedToCompleteInCurrentBuffer()
  463. return
  464. endif
  465. call s:UpdateSignatureHelp()
  466. endfunction
  467. function! s:OnFileTypeSet()
  468. " The contents of the command-line window are empty when the filetype is set
  469. " for the first time. Users should never change its filetype so we only rely
  470. " on the CmdwinEnter event for that window.
  471. if !empty( getcmdwintype() )
  472. return
  473. endif
  474. if !s:AllowedToCompleteInCurrentBuffer()
  475. return
  476. endif
  477. call s:SetUpCompleteopt()
  478. call s:SetCompleteFunc()
  479. call s:StartMessagePoll()
  480. exec s:python_command "ycm_state.OnBufferVisit()"
  481. call s:OnFileReadyToParse( 1 )
  482. endfunction
  483. function! s:OnBufferEnter()
  484. if !s:VisitedBufferRequiresReparse()
  485. return
  486. endif
  487. call s:SetUpCompleteopt()
  488. call s:SetCompleteFunc()
  489. call s:StartMessagePoll()
  490. exec s:python_command "ycm_state.OnBufferVisit()"
  491. " Last parse may be outdated because of changes from other buffers. Force a
  492. " new parse.
  493. call s:OnFileReadyToParse( 1 )
  494. endfunction
  495. function! s:OnBufferUnload()
  496. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  497. " it as a true number for the getbufvar function.
  498. let buffer_number = str2nr( expand( '<abuf>' ) )
  499. if !s:AllowedToCompleteInBuffer( buffer_number )
  500. return
  501. endif
  502. exec s:python_command "ycm_state.OnBufferUnload( " . buffer_number . " )"
  503. endfunction
  504. function! s:UpdateMatches()
  505. exec s:python_command "ycm_state.UpdateMatches()"
  506. endfunction
  507. function! s:PollServerReady( timer_id )
  508. if !s:Pyeval( 'ycm_state.IsServerAlive()' )
  509. exec s:python_command "ycm_state.NotifyUserIfServerCrashed()"
  510. " Server crashed. Don't poll it again.
  511. return
  512. endif
  513. if !s:Pyeval( 'ycm_state.CheckIfServerIsReady()' )
  514. let s:pollers.server_ready.id = timer_start(
  515. \ s:pollers.server_ready.wait_milliseconds,
  516. \ function( 's:PollServerReady' ) )
  517. return
  518. endif
  519. call s:OnFileTypeSet()
  520. endfunction
  521. function! s:OnFileReadyToParse( ... )
  522. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  523. " FileReadyToParse event notification, whether the buffer has changed or not;
  524. " effectively forcing a parse of the buffer. Default is 0.
  525. let force_parsing = a:0 > 0 && a:1
  526. " We only want to send a new FileReadyToParse event notification if the buffer
  527. " has changed since the last time we sent one, or if forced.
  528. if force_parsing || s:Pyeval( "ycm_state.NeedsReparse()" )
  529. " We switched buffers or somethuing, so claer.
  530. " FIXME: sig hekp should be buffer local?
  531. call s:ClearSignatureHelp()
  532. exec s:python_command "ycm_state.OnFileReadyToParse()"
  533. call timer_stop( s:pollers.file_parse_response.id )
  534. let s:pollers.file_parse_response.id = timer_start(
  535. \ s:pollers.file_parse_response.wait_milliseconds,
  536. \ function( 's:PollFileParseResponse' ) )
  537. endif
  538. endfunction
  539. function! s:PollFileParseResponse( ... )
  540. if !s:Pyeval( "ycm_state.FileParseRequestReady()" )
  541. let s:pollers.file_parse_response.id = timer_start(
  542. \ s:pollers.file_parse_response.wait_milliseconds,
  543. \ function( 's:PollFileParseResponse' ) )
  544. return
  545. endif
  546. exec s:python_command "ycm_state.HandleFileParseRequest()"
  547. if s:Pyeval( "ycm_state.ShouldResendFileParseRequest()" )
  548. call s:OnFileReadyToParse( 1 )
  549. endif
  550. endfunction
  551. function! s:SendKeys( keys )
  552. " By default keys are added to the end of the typeahead buffer. If there are
  553. " already keys in the buffer, they will be processed first and may change the
  554. " state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in normal
  555. " mode instead of insert mode or <C-e> outside of completion mode). We avoid
  556. " that by inserting the keys at the start of the typeahead buffer with the 'i'
  557. " option. Also, we don't want the keys to be remapped to something else so we
  558. " add the 'n' option.
  559. call feedkeys( a:keys, 'in' )
  560. endfunction
  561. function! s:CloseCompletionMenu()
  562. if pumvisible()
  563. call s:SendKeys( "\<C-e>" )
  564. endif
  565. endfunction
  566. function! s:OnInsertChar()
  567. if !s:AllowedToCompleteInCurrentBuffer()
  568. return
  569. endif
  570. call timer_stop( s:pollers.completion.id )
  571. call s:CloseCompletionMenu()
  572. " TODO: Do we really need this here?
  573. call timer_stop( s:pollers.signature_help.id )
  574. endfunction
  575. function! s:OnDeleteChar( key )
  576. if !s:AllowedToCompleteInCurrentBuffer()
  577. return a:key
  578. endif
  579. call timer_stop( s:pollers.completion.id )
  580. "
  581. " TODO: Do we really need this here?
  582. call timer_stop( s:pollers.signature_help.id )
  583. if pumvisible()
  584. return "\<C-y>" . a:key
  585. endif
  586. return a:key
  587. endfunction
  588. function! s:StopCompletion( key )
  589. call timer_stop( s:pollers.completion.id )
  590. call s:ClearSignatureHelp()
  591. if pumvisible()
  592. let s:completion_stopped = 1
  593. return "\<C-y>"
  594. endif
  595. return a:key
  596. endfunction
  597. function! s:OnCursorMovedNormalMode()
  598. if !s:AllowedToCompleteInCurrentBuffer()
  599. return
  600. endif
  601. exec s:python_command "ycm_state.OnCursorMoved()"
  602. endfunction
  603. function! s:OnTextChangedNormalMode()
  604. if !s:AllowedToCompleteInCurrentBuffer()
  605. return
  606. endif
  607. call s:OnFileReadyToParse()
  608. endfunction
  609. function! s:OnTextChangedInsertMode()
  610. if !s:AllowedToCompleteInCurrentBuffer()
  611. return
  612. endif
  613. if s:completion_stopped
  614. let s:completion_stopped = 0
  615. let s:completion = s:default_completion
  616. return
  617. endif
  618. call s:IdentifierFinishedOperations()
  619. " We have to make sure we correctly leave semantic mode even when the user
  620. " inserts something like a "operator[]" candidate string which fails
  621. " CurrentIdentifierFinished check.
  622. if s:force_semantic && !s:Pyeval( 'base.LastEnteredCharIsIdentifierChar()' )
  623. let s:force_semantic = 0
  624. endif
  625. if &completefunc == "youcompleteme#CompleteFunc" &&
  626. \ ( g:ycm_auto_trigger || s:force_semantic ) &&
  627. \ !s:InsideCommentOrStringAndShouldStop() &&
  628. \ !s:OnBlankLine()
  629. " Immediately call previous completion to avoid flickers.
  630. call s:Complete()
  631. call s:RequestCompletion()
  632. call s:UpdateSignatureHelp()
  633. call s:RequestSignatureHelp()
  634. endif
  635. exec s:python_command "ycm_state.OnCursorMoved()"
  636. if g:ycm_autoclose_preview_window_after_completion
  637. call s:ClosePreviewWindowIfNeeded()
  638. endif
  639. endfunction
  640. function! s:OnInsertLeave()
  641. if !s:AllowedToCompleteInCurrentBuffer()
  642. return
  643. endif
  644. call timer_stop( s:pollers.completion.id )
  645. let s:force_semantic = 0
  646. let s:completion = s:default_completion
  647. call s:OnFileReadyToParse()
  648. exec s:python_command "ycm_state.OnInsertLeave()"
  649. if g:ycm_autoclose_preview_window_after_completion ||
  650. \ g:ycm_autoclose_preview_window_after_insertion
  651. call s:ClosePreviewWindowIfNeeded()
  652. endif
  653. call s:ClearSignatureHelp()
  654. endfunction
  655. function! s:ClosePreviewWindowIfNeeded()
  656. let current_buffer_name = bufname('')
  657. " We don't want to try to close the preview window in special buffers like
  658. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  659. " with '['.
  660. if current_buffer_name[ 0 ] == '['
  661. return
  662. endif
  663. " This command does the actual closing of the preview window. If no preview
  664. " window is shown, nothing happens.
  665. pclose
  666. endfunction
  667. function! s:IdentifierFinishedOperations()
  668. if !s:Pyeval( 'base.CurrentIdentifierFinished()' )
  669. return
  670. endif
  671. exec s:python_command "ycm_state.OnCurrentIdentifierFinished()"
  672. let s:force_semantic = 0
  673. let s:completion = s:default_completion
  674. endfunction
  675. " Returns 1 when inside comment and 2 when inside string
  676. function! s:InsideCommentOrString()
  677. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  678. " in insert mode when this func is called.
  679. let syntax_group = synIDattr(
  680. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  681. if stridx(syntax_group, 'Comment') > -1
  682. return 1
  683. endif
  684. if stridx(syntax_group, 'String') > -1
  685. return 2
  686. endif
  687. return 0
  688. endfunction
  689. function! s:InsideCommentOrStringAndShouldStop()
  690. let retval = s:InsideCommentOrString()
  691. let inside_comment = retval == 1
  692. let inside_string = retval == 2
  693. if inside_comment && g:ycm_complete_in_comments ||
  694. \ inside_string && g:ycm_complete_in_strings
  695. return 0
  696. endif
  697. return retval
  698. endfunction
  699. function! s:OnBlankLine()
  700. return s:Pyeval( 'not vim.current.line or vim.current.line.isspace()' )
  701. endfunction
  702. function! s:RequestCompletion()
  703. exec s:python_command "ycm_state.SendCompletionRequest(" .
  704. \ "vimsupport.GetBoolValue( 's:force_semantic' ) )"
  705. call s:PollCompletion()
  706. endfunction
  707. function! s:RequestSemanticCompletion()
  708. if &completefunc == "youcompleteme#CompleteFunc"
  709. let s:force_semantic = 1
  710. exec s:python_command "ycm_state.SendCompletionRequest( True )"
  711. call s:PollCompletion()
  712. endif
  713. " Since this function is called in a mapping through the expression register
  714. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  715. " insert anything so we return an empty string.
  716. return ''
  717. endfunction
  718. function! s:PollCompletion( ... )
  719. if !s:Pyeval( 'ycm_state.CompletionRequestReady()' )
  720. let s:pollers.completion.id = timer_start(
  721. \ s:pollers.completion.wait_milliseconds,
  722. \ function( 's:PollCompletion' ) )
  723. return
  724. endif
  725. let s:completion = s:Pyeval( 'ycm_state.GetCompletionResponse()' )
  726. call s:Complete()
  727. endfunction
  728. function! s:ShouldUseSignatureHelp()
  729. return s:Pyeval( 'vimsupport.VimSupportsPopupWindows()' )
  730. endfunction
  731. function! s:RequestSignatureHelp()
  732. if !s:ShouldUseSignatureHelp()
  733. return
  734. endif
  735. exec s:python_command "ycm_state.SendSignatureHelpRequest()"
  736. call s:PollSignatureHelp()
  737. endfunction
  738. function! s:PollSignatureHelp( ... )
  739. if !s:ShouldUseSignatureHelp()
  740. return
  741. endif
  742. if !s:Pyeval( 'ycm_state.SignatureHelpRequestReady()' )
  743. let s:pollers.signature_help.id = timer_start(
  744. \ s:pollers.signature_help.wait_milliseconds,
  745. \ function( 's:PollSignatureHelp' ) )
  746. return
  747. endif
  748. let s:signature_help = s:Pyeval( 'ycm_state.GetSignatureHelpResponse()' )
  749. call s:UpdateSignatureHelp()
  750. endfunction
  751. function! s:Complete()
  752. " Do not call user's completion function if the start column is after the
  753. " current column or if there are no candidates. Close the completion menu
  754. " instead. This avoids keeping the user in completion mode.
  755. if s:completion.completion_start_column > s:completion.column ||
  756. \ empty( s:completion.completions )
  757. call s:CloseCompletionMenu()
  758. else
  759. " <c-x><c-u> invokes the user's completion function (which we have set to
  760. " youcompleteme#CompleteFunc), and <c-p> tells Vim to select the previous
  761. " completion candidate. This is necessary because by default, Vim selects
  762. " the first candidate when completion is invoked, and selecting a candidate
  763. " automatically replaces the current text with it. Calling <c-p> forces Vim
  764. " to deselect the first candidate and in turn preserve the user's current
  765. " text until he explicitly chooses to replace it with a completion.
  766. call s:SendKeys( "\<C-X>\<C-U>\<C-P>" )
  767. endif
  768. " Displaying or hiding the PUM might mean we need to hide the sig help
  769. call s:UpdateSignatureHelp()
  770. endfunction
  771. function! youcompleteme#CompleteFunc( findstart, base )
  772. if a:findstart
  773. " When auto-wrapping is enabled, Vim wraps the current line after the
  774. " completion request is sent but before calling this function. The starting
  775. " column returned by the server is invalid in that case and must be
  776. " recomputed.
  777. if s:completion.line != line( '.' )
  778. " Given
  779. " scb: column where the completion starts before auto-wrapping
  780. " cb: cursor column before auto-wrapping
  781. " sca: column where the completion starts after auto-wrapping
  782. " ca: cursor column after auto-wrapping
  783. " we have
  784. " ca - sca = cb - scb
  785. " sca = scb + ca - cb
  786. let s:completion.completion_start_column +=
  787. \ col( '.' ) - s:completion.column
  788. endif
  789. return s:completion.completion_start_column - 1
  790. endif
  791. return s:completion.completions
  792. endfunction
  793. function! s:UpdateSignatureHelp()
  794. if !s:ShouldUseSignatureHelp()
  795. return
  796. endif
  797. call s:Pyeval(
  798. \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' )
  799. endfunction
  800. function! s:ClearSignatureHelp()
  801. if !s:ShouldUseSignatureHelp()
  802. return
  803. endif
  804. call timer_stop( s:pollers.signature_help.id )
  805. let s:signature_help = s:default_signature_help
  806. call s:Pyeval( 'ycm_state.ClearSignatureHelp()' )
  807. endfunction
  808. function! youcompleteme#ServerPid()
  809. return s:Pyeval( 'ycm_state.ServerPid()' )
  810. endfunction
  811. function! s:SetUpCommands()
  812. command! YcmRestartServer call s:RestartServer()
  813. command! YcmDebugInfo call s:DebugInfo()
  814. command! -nargs=* -complete=custom,youcompleteme#LogsComplete
  815. \ YcmToggleLogs call s:ToggleLogs(<f-args>)
  816. if s:Pyeval( 'vimsupport.VimVersionAtLeast( "7.4.1898" )' )
  817. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  818. \ YcmCompleter call s:CompleterCommand(<q-mods>,
  819. \ <count>,
  820. \ <line1>,
  821. \ <line2>,
  822. \ <f-args>)
  823. else
  824. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  825. \ YcmCompleter call s:CompleterCommand('',
  826. \ <count>,
  827. \ <line1>,
  828. \ <line2>,
  829. \ <f-args>)
  830. endif
  831. command! YcmDiags call s:ShowDiagnostics()
  832. command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic()
  833. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  834. endfunction
  835. function! s:RestartServer()
  836. call s:SetUpOptions()
  837. exec s:python_command "ycm_state.RestartServer()"
  838. call timer_stop( s:pollers.receive_messages.id )
  839. let s:pollers.receive_messages.id = -1
  840. call s:ClearSignatureHelp()
  841. call timer_stop( s:pollers.server_ready.id )
  842. let s:pollers.server_ready.id = timer_start(
  843. \ s:pollers.server_ready.wait_milliseconds,
  844. \ function( 's:PollServerReady' ) )
  845. endfunction
  846. function! s:DebugInfo()
  847. echom "Printing YouCompleteMe debug information..."
  848. let debug_info = s:Pyeval( 'ycm_state.DebugInfo()' )
  849. for line in split( debug_info, "\n" )
  850. echom '-- ' . line
  851. endfor
  852. endfunction
  853. function! s:ToggleLogs(...)
  854. exec s:python_command "ycm_state.ToggleLogs( *vim.eval( 'a:000' ) )"
  855. endfunction
  856. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  857. return join( s:Pyeval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  858. endfunction
  859. function! s:CompleterCommand( mods, count, line1, line2, ... )
  860. exec s:python_command "ycm_state.SendCommandRequest(" .
  861. \ "vim.eval( 'a:000' )," .
  862. \ "vim.eval( 'a:mods' )," .
  863. \ "vimsupport.GetBoolValue( 'a:count != -1' )," .
  864. \ "vimsupport.GetIntValue( 'a:line1' )," .
  865. \ "vimsupport.GetIntValue( 'a:line2' ) )"
  866. endfunction
  867. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  868. return join( s:Pyeval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  869. endfunction
  870. function! youcompleteme#OpenGoToList()
  871. exec s:python_command "vimsupport.PostVimMessage(" .
  872. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  873. \ "Do NOT use it.' )"
  874. exec s:python_command "vimsupport.OpenQuickFixList( True, True )"
  875. endfunction
  876. function! s:ShowDiagnostics()
  877. exec s:python_command "ycm_state.ShowDiagnostics()"
  878. endfunction
  879. function! s:ShowDetailedDiagnostic()
  880. exec s:python_command "ycm_state.ShowDetailedDiagnostic()"
  881. endfunction
  882. function! s:ForceCompileAndDiagnostics()
  883. exec s:python_command "ycm_state.ForceCompileAndDiagnostics()"
  884. endfunction
  885. " This is basic vim plugin boilerplate
  886. let &cpo = s:save_cpo
  887. unlet s:save_cpo