youcompleteme.vim 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. " NOTE: Noevim reports v:version as 800, which is garbage. For some features
  21. " that are supporetd by our minimum Vim version, we have to guard them against
  22. " neovim, which doesn't implement them.
  23. let s:is_neovim = has( 'nvim' )
  24. " This needs to be called outside of a function
  25. let s:script_folder_path = escape( expand( '<sfile>:p:h' ), '\' )
  26. let s:force_semantic = 0
  27. let s:completion_stopped = 0
  28. " These two variables are initialized in youcompleteme#Enable.
  29. let s:default_completion = {}
  30. let s:completion = s:default_completion
  31. let s:default_signature_help = {}
  32. let s:signature_help = s:default_completion
  33. let s:previous_allowed_buffer_number = 0
  34. let s:pollers = {
  35. \ 'completion': {
  36. \ 'id': -1,
  37. \ 'wait_milliseconds': 10
  38. \ },
  39. \ 'signature_help': {
  40. \ 'id': -1,
  41. \ 'wait_milliseconds': 10
  42. \ },
  43. \ 'file_parse_response': {
  44. \ 'id': -1,
  45. \ 'wait_milliseconds': 100
  46. \ },
  47. \ 'server_ready': {
  48. \ 'id': -1,
  49. \ 'wait_milliseconds': 100
  50. \ },
  51. \ 'receive_messages': {
  52. \ 'id': -1,
  53. \ 'wait_milliseconds': 100
  54. \ },
  55. \ 'command': {
  56. \ 'id': -1,
  57. \ 'wait_milliseconds': 100
  58. \ }
  59. \ }
  60. let s:buftype_blacklist = {
  61. \ 'help': 1,
  62. \ 'terminal': 1,
  63. \ 'quickfix': 1,
  64. \ 'popup': 1,
  65. \ 'nofile': 1,
  66. \ }
  67. let s:last_char_inserted_by_user = v:true
  68. let s:enable_hover = 0
  69. let s:cursorhold_popup = -1
  70. let s:force_preview_popup = 0
  71. let s:RESOLVE_NONE = 0
  72. let s:RESOLVE_UP_FRONT = 1
  73. let s:RESOLVE_ON_DEMAND = 2
  74. let s:resolve_completions = s:RESOLVE_NONE
  75. function! s:StartMessagePoll()
  76. if s:pollers.receive_messages.id < 0
  77. let s:pollers.receive_messages.id = timer_start(
  78. \ s:pollers.receive_messages.wait_milliseconds,
  79. \ function( 's:ReceiveMessages' ) )
  80. endif
  81. endfunction
  82. function! s:ReceiveMessages( timer_id )
  83. let poll_again = v:false
  84. if s:AllowedToCompleteInCurrentBuffer()
  85. let poll_again = py3eval( 'ycm_state.OnPeriodicTick()' )
  86. endif
  87. if poll_again
  88. let s:pollers.receive_messages.id = timer_start(
  89. \ s:pollers.receive_messages.wait_milliseconds,
  90. \ function( 's:ReceiveMessages' ) )
  91. else
  92. " Don't poll again until we open another buffer
  93. let s:pollers.receive_messages.id = -1
  94. endif
  95. endfunction
  96. function! s:SetUpOptions()
  97. call s:SetUpCommands()
  98. call s:SetUpCpoptions()
  99. call s:SetUpCompleteopt()
  100. call s:SetUpKeyMappings()
  101. if g:ycm_show_diagnostics_ui
  102. call s:TurnOffSyntasticForCFamily()
  103. endif
  104. call s:SetUpSigns()
  105. call s:SetUpSyntaxHighlighting()
  106. endfunction
  107. function! youcompleteme#Enable()
  108. call s:SetUpBackwardsCompatibility()
  109. let completeopt = split( &completeopt, ',' )
  110. " Will we add 'popup' to the 'completeopt' (later)
  111. let s:force_preview_popup =
  112. \ type( g:ycm_add_preview_to_completeopt ) == v:t_string &&
  113. \ g:ycm_add_preview_to_completeopt ==# 'popup' &&
  114. \ !s:is_neovim
  115. " Will we add 'preview' to the 'completeopt' (later)
  116. let force_preview =
  117. \ type( g:ycm_add_preview_to_completeopt ) != v:t_string &&
  118. \ g:ycm_add_preview_to_completeopt
  119. " Will we be using the preview popup ? That is either the user set it in their
  120. " compelteopt or we're going to add it later.
  121. let use_preview_popup =
  122. \ s:force_preview_popup ||
  123. \ index( completeopt, 'popup' ) >= 0
  124. " We should only ask the server to resolve completion items upfront if we're
  125. " going to display them - that is either:
  126. " - popup is (or will be) in completeopt
  127. " - preview is (or will be) in completeopt, or
  128. let require_resolve =
  129. \ use_preview_popup ||
  130. \ force_preview ||
  131. \ index( completeopt, 'preview' ) >= 0
  132. if use_preview_popup && exists( '*popup_findinfo' )
  133. " If the preview popup is going to be used, and on-demand resolve can be
  134. " supported, enable it.
  135. let s:resolve_completions = s:RESOLVE_ON_DEMAND
  136. elseif require_resolve
  137. " The preview window or info popup is enalbed - request the server
  138. " pre-resolves completion items
  139. let s:resolve_completions = s:RESOLVE_UP_FRONT
  140. else
  141. " Otherwise, there's no point in resolving completions - they'll never be
  142. " displayed.
  143. endif
  144. if !s:SetUpPython()
  145. return
  146. endif
  147. call s:SetUpOptions()
  148. call youcompleteme#EnableCursorMovedAutocommands()
  149. augroup youcompleteme
  150. autocmd!
  151. " Note that these events will NOT trigger for the file vim is started with;
  152. " so if you do "vim foo.cc", these events will not trigger when that buffer
  153. " is read. This is because youcompleteme#Enable() is called on VimEnter and
  154. " that happens *after* FileType has already triggered for the initial file.
  155. " We don't parse the buffer on the BufRead event since it would only be
  156. " useful if the buffer filetype is set (we ignore the buffer if there is no
  157. " filetype) and if so, the FileType event has triggered before and thus the
  158. " buffer is already parsed.
  159. autocmd BufWritePost,FileWritePost * call s:OnFileSave()
  160. autocmd FileType * call s:OnFileTypeSet()
  161. autocmd BufEnter,CmdwinEnter * call s:OnBufferEnter()
  162. autocmd BufUnload * call s:OnBufferUnload()
  163. autocmd InsertLeave * call s:OnInsertLeave()
  164. autocmd VimLeave * call s:OnVimLeave()
  165. autocmd CompleteDone * call s:OnCompleteDone()
  166. autocmd CompleteChanged * call s:OnCompleteChanged()
  167. autocmd BufEnter,WinEnter * call s:UpdateMatches()
  168. augroup END
  169. " The FileType event is not triggered for the first loaded file. We wait until
  170. " the server is ready to manually run the s:OnFileTypeSet function.
  171. let s:pollers.server_ready.id = timer_start(
  172. \ s:pollers.server_ready.wait_milliseconds,
  173. \ function( 's:PollServerReady' ) )
  174. let s:default_completion = py3eval( 'vimsupport.NO_COMPLETIONS' )
  175. let s:completion = s:default_completion
  176. if exists( '*prop_type_add' ) && exists( '*prop_type_delete' )
  177. hi default YCMInverse term=reverse cterm=reverse gui=reverse
  178. call prop_type_delete( 'YCM-signature-help-current-argument' )
  179. call prop_type_add( 'YCM-signature-help-current-argument', {
  180. \ 'highlight': 'YCMInverse',
  181. \ 'combine': 1,
  182. \ 'priority': 50,
  183. \ } )
  184. endif
  185. endfunction
  186. function! youcompleteme#EnableCursorMovedAutocommands()
  187. augroup ycmcompletemecursormove
  188. autocmd!
  189. autocmd CursorMoved * call s:OnCursorMovedNormalMode()
  190. autocmd TextChanged * call s:OnTextChangedNormalMode()
  191. autocmd TextChangedI * call s:OnTextChangedInsertMode( v:false )
  192. autocmd TextChangedP * call s:OnTextChangedInsertMode( v:true )
  193. autocmd InsertCharPre * call s:OnInsertChar()
  194. augroup END
  195. endfunction
  196. function! youcompleteme#DisableCursorMovedAutocommands()
  197. autocmd! ycmcompletemecursormove
  198. endfunction
  199. function! youcompleteme#GetErrorCount()
  200. return py3eval( 'ycm_state.GetErrorCount()' )
  201. endfunction
  202. function! youcompleteme#GetWarningCount()
  203. return py3eval( 'ycm_state.GetWarningCount()' )
  204. endfunction
  205. function! s:SetUpPython() abort
  206. py3 << EOF
  207. import os.path as p
  208. import sys
  209. import traceback
  210. import vim
  211. root_folder = p.normpath( p.join( vim.eval( 's:script_folder_path' ), '..' ) )
  212. third_party_folder = p.join( root_folder, 'third_party' )
  213. # Add dependencies to Python path.
  214. dependencies = [ p.join( root_folder, 'python' ),
  215. p.join( third_party_folder, 'requests-futures' ),
  216. p.join( third_party_folder, 'ycmd' ),
  217. p.join( third_party_folder, 'requests_deps', 'idna' ),
  218. p.join( third_party_folder, 'requests_deps', 'chardet' ),
  219. p.join( third_party_folder,
  220. 'requests_deps',
  221. 'urllib3',
  222. 'src' ),
  223. p.join( third_party_folder, 'requests_deps', 'certifi' ),
  224. p.join( third_party_folder, 'requests_deps', 'requests' ) ]
  225. sys.path[ 0:0 ] = dependencies
  226. # We enclose this code in a try/except block to avoid backtraces in Vim.
  227. try:
  228. # Import the modules used in this file.
  229. from ycm import base, vimsupport, youcompleteme
  230. if 'ycm_state' in globals():
  231. # If re-initializing, pretend that we shut down
  232. ycm_state.OnVimLeave()
  233. del ycm_state
  234. # If we're able to resolve completion details asynchronously, set the option
  235. # which enables this in the server.
  236. if int( vim.eval( 's:resolve_completions == s:RESOLVE_ON_DEMAND' ) ):
  237. # resovle a small number upfront, the rest on demand
  238. default_options = {
  239. 'max_num_candidates_to_detail': 10
  240. }
  241. elif int( vim.eval( 's:resolve_completions == s:RESOLVE_NONE' ) ):
  242. # don't reasolve any
  243. default_options = {
  244. 'max_num_candidates_to_detail': 0
  245. }
  246. else:
  247. # i.e. s:resolve_completions == s:RESOLVE_UP_FRONT
  248. # The server will decide - i.e. resovle everything upfront
  249. default_options = {}
  250. ycm_state = youcompleteme.YouCompleteMe( default_options )
  251. except Exception as error:
  252. # We don't use PostVimMessage or EchoText from the vimsupport module because
  253. # importing this module may fail.
  254. vim.command( 'redraw | echohl WarningMsg' )
  255. for line in traceback.format_exc().splitlines():
  256. vim.command( "echom '{0}'".format( line.replace( "'", "''" ) ) )
  257. vim.command( "echo 'YouCompleteMe unavailable: {0}'"
  258. .format( str( error ).replace( "'", "''" ) ) )
  259. vim.command( 'echohl None' )
  260. vim.command( 'return 0' )
  261. else:
  262. vim.command( 'return 1' )
  263. EOF
  264. endfunction
  265. function! s:SetUpKeyMappings()
  266. " The g:ycm_key_select_completion and g:ycm_key_previous_completion used to
  267. " exist and are now here purely for the sake of backwards compatibility; we
  268. " don't want to break users if we can avoid it.
  269. if exists('g:ycm_key_select_completion') &&
  270. \ index(g:ycm_key_list_select_completion,
  271. \ g:ycm_key_select_completion) == -1
  272. call add(g:ycm_key_list_select_completion, g:ycm_key_select_completion)
  273. endif
  274. if exists('g:ycm_key_previous_completion') &&
  275. \ index(g:ycm_key_list_previous_completion,
  276. \ g:ycm_key_previous_completion) == -1
  277. call add(g:ycm_key_list_previous_completion, g:ycm_key_previous_completion)
  278. endif
  279. for key in g:ycm_key_list_select_completion
  280. " With this command, when the completion window is visible, the tab key
  281. " (default) will select the next candidate in the window. In vim, this also
  282. " changes the typed-in text to that of the candidate completion.
  283. exe 'inoremap <expr>' . key . ' pumvisible() ? "\<C-n>" : "\' . key .'"'
  284. endfor
  285. for key in g:ycm_key_list_previous_completion
  286. " This selects the previous candidate for shift-tab (default)
  287. exe 'inoremap <expr>' . key . ' pumvisible() ? "\<C-p>" : "\' . key .'"'
  288. endfor
  289. for key in g:ycm_key_list_stop_completion
  290. " When selecting a candidate and closing the completion menu with the <C-y>
  291. " key, the menu will automatically be reopened because of the TextChangedI
  292. " event. We define a command to prevent that.
  293. exe 'inoremap <expr>' . key . ' <SID>StopCompletion( "\' . key . '" )'
  294. endfor
  295. if !empty( g:ycm_key_invoke_completion )
  296. let invoke_key = g:ycm_key_invoke_completion
  297. " Inside the console, <C-Space> is passed as <Nul> to Vim
  298. if invoke_key ==# '<C-Space>'
  299. imap <Nul> <C-Space>
  300. endif
  301. silent! exe 'inoremap <unique> <silent> ' . invoke_key .
  302. \ ' <C-R>=<SID>RequestSemanticCompletion()<CR>'
  303. endif
  304. if !empty( g:ycm_key_detailed_diagnostics )
  305. silent! exe 'nnoremap <unique> ' . g:ycm_key_detailed_diagnostics .
  306. \ ' :YcmShowDetailedDiagnostic<CR>'
  307. endif
  308. endfunction
  309. function! s:SetUpSigns()
  310. " We try to ensure backwards compatibility with Syntastic if the user has
  311. " already defined styling for Syntastic highlight groups.
  312. if !hlexists( 'YcmErrorSign' )
  313. if hlexists( 'SyntasticErrorSign')
  314. highlight link YcmErrorSign SyntasticErrorSign
  315. else
  316. highlight link YcmErrorSign error
  317. endif
  318. endif
  319. if !hlexists( 'YcmWarningSign' )
  320. if hlexists( 'SyntasticWarningSign')
  321. highlight link YcmWarningSign SyntasticWarningSign
  322. else
  323. highlight link YcmWarningSign todo
  324. endif
  325. endif
  326. if !hlexists( 'YcmErrorLine' )
  327. highlight link YcmErrorLine SyntasticErrorLine
  328. endif
  329. if !hlexists( 'YcmWarningLine' )
  330. highlight link YcmWarningLine SyntasticWarningLine
  331. endif
  332. exe 'sign define YcmError text=' . g:ycm_error_symbol .
  333. \ ' texthl=YcmErrorSign linehl=YcmErrorLine'
  334. exe 'sign define YcmWarning text=' . g:ycm_warning_symbol .
  335. \ ' texthl=YcmWarningSign linehl=YcmWarningLine'
  336. endfunction
  337. function! s:SetUpSyntaxHighlighting()
  338. " We try to ensure backwards compatibility with Syntastic if the user has
  339. " already defined styling for Syntastic highlight groups.
  340. if !hlexists( 'YcmErrorSection' )
  341. if hlexists( 'SyntasticError' )
  342. highlight link YcmErrorSection SyntasticError
  343. else
  344. highlight link YcmErrorSection SpellBad
  345. endif
  346. endif
  347. if !hlexists( 'YcmWarningSection' )
  348. if hlexists( 'SyntasticWarning' )
  349. highlight link YcmWarningSection SyntasticWarning
  350. else
  351. highlight link YcmWarningSection SpellCap
  352. endif
  353. endif
  354. endfunction
  355. function! s:SetUpBackwardsCompatibility()
  356. let complete_in_comments_and_strings =
  357. \ get( g:, 'ycm_complete_in_comments_and_strings', 0 )
  358. if complete_in_comments_and_strings
  359. let g:ycm_complete_in_strings = 1
  360. let g:ycm_complete_in_comments = 1
  361. endif
  362. " ycm_filetypes_to_completely_ignore is the old name for fileype_blacklist
  363. if has_key( g:, 'ycm_filetypes_to_completely_ignore' )
  364. let g:filetype_blacklist = g:ycm_filetypes_to_completely_ignore
  365. endif
  366. endfunction
  367. " Needed so that YCM is used instead of Syntastic
  368. function! s:TurnOffSyntasticForCFamily()
  369. let g:syntastic_cpp_checkers = []
  370. let g:syntastic_c_checkers = []
  371. let g:syntastic_objc_checkers = []
  372. let g:syntastic_objcpp_checkers = []
  373. let g:syntastic_cuda_checkers = []
  374. endfunction
  375. function! s:DisableOnLargeFile( buffer )
  376. if exists( 'b:ycm_largefile' )
  377. return b:ycm_largefile
  378. endif
  379. let threshold = g:ycm_disable_for_files_larger_than_kb * 1024
  380. let b:ycm_largefile =
  381. \ threshold > 0 && getfsize( expand( a:buffer ) ) > threshold
  382. if b:ycm_largefile
  383. py3 vimsupport.PostVimMessage( 'YouCompleteMe is disabled in this buffer;' +
  384. \ ' the file exceeded the max size (see YCM options).' )
  385. endif
  386. return b:ycm_largefile
  387. endfunction
  388. function! s:HasAnyKey( dict, keys )
  389. for key in a:keys
  390. if has_key( a:dict, key )
  391. return 1
  392. endif
  393. endfor
  394. return 0
  395. endfunction
  396. function! s:AllowedToCompleteInBuffer( buffer )
  397. let buftype = getbufvar( a:buffer, '&buftype' )
  398. if has_key( s:buftype_blacklist, buftype )
  399. return 0
  400. endif
  401. let filetype = getbufvar( a:buffer, '&filetype' )
  402. if empty( filetype )
  403. let filetype = 'ycm_nofiletype'
  404. endif
  405. let whitelist_allows = type( g:ycm_filetype_whitelist ) != v:t_dict ||
  406. \ has_key( g:ycm_filetype_whitelist, '*' ) ||
  407. \ s:HasAnyKey( g:ycm_filetype_whitelist, split( filetype, '\.' ) )
  408. let blacklist_allows = type( g:ycm_filetype_blacklist ) != v:t_dict ||
  409. \ !s:HasAnyKey( g:ycm_filetype_blacklist, split( filetype, '\.' ) )
  410. let allowed = whitelist_allows && blacklist_allows
  411. if !allowed || s:DisableOnLargeFile( a:buffer )
  412. return 0
  413. endif
  414. if allowed
  415. let s:previous_allowed_buffer_number = bufnr( a:buffer )
  416. endif
  417. return allowed
  418. endfunction
  419. function! s:AllowedToCompleteInCurrentBuffer()
  420. return s:AllowedToCompleteInBuffer( '%' )
  421. endfunction
  422. function! s:VisitedBufferRequiresReparse()
  423. if bufnr( '%' ) ==# s:previous_allowed_buffer_number
  424. return 0
  425. endif
  426. return s:AllowedToCompleteInCurrentBuffer()
  427. endfunction
  428. function! s:SetUpCpoptions()
  429. " Without this flag in cpoptions, critical YCM mappings do not work. There's
  430. " no way to not have this and have YCM working, so force the flag.
  431. set cpoptions+=B
  432. " This prevents the display of "Pattern not found" & similar messages during
  433. " completion.
  434. set shortmess+=c
  435. endfunction
  436. function! s:SetUpCompleteopt()
  437. " Some plugins (I'm looking at you, vim-notes) change completeopt by for
  438. " instance adding 'longest'. This breaks YCM. So we force our settings.
  439. " There's no two ways about this: if you want to use YCM then you have to
  440. " have these completeopt settings, otherwise YCM won't work at all.
  441. " We need menuone in completeopt, otherwise when there's only one candidate
  442. " for completion, the menu doesn't show up.
  443. set completeopt-=menu
  444. set completeopt+=menuone
  445. " This is unnecessary with our features. People use this option to insert
  446. " the common prefix of all the matches and then add more differentiating chars
  447. " so that they can select a more specific match. With our features, they
  448. " don't need to insert the prefix; they just type the differentiating chars.
  449. " Also, having this option set breaks the plugin.
  450. set completeopt-=longest
  451. if s:resolve_completions == s:RESOLVE_ON_DEMAND
  452. set completeopt+=popuphidden
  453. endif
  454. if s:force_preview_popup
  455. set completeopt+=popup
  456. elseif g:ycm_add_preview_to_completeopt
  457. set completeopt+=preview
  458. endif
  459. endfunction
  460. function! s:EnableCompletingInCurrentBuffer()
  461. let b:ycm_completing = 1
  462. endfunction
  463. function s:StopPoller( poller ) abort
  464. call timer_stop( a:poller.id )
  465. let a:poller.id = -1
  466. endfunction
  467. function! s:OnVimLeave()
  468. " Workaround a NeoVim issue - not shutting down timers correctly
  469. " https://github.com/neovim/neovim/issues/6840
  470. for poller in values( s:pollers )
  471. call s:StopPoller( poller )
  472. endfor
  473. py3 ycm_state.OnVimLeave()
  474. endfunction
  475. function! s:OnCompleteDone()
  476. if !s:AllowedToCompleteInCurrentBuffer()
  477. return
  478. endif
  479. let s:last_char_inserted_by_user = v:false
  480. py3 ycm_state.OnCompleteDone()
  481. call s:UpdateSignatureHelp()
  482. endfunction
  483. function! s:OnCompleteChanged()
  484. if !s:AllowedToCompleteInCurrentBuffer()
  485. return
  486. endif
  487. if ! empty( v:event.completed_item )
  488. let s:last_char_inserted_by_user = v:false
  489. call s:ResolveCompletionItem( v:event.completed_item )
  490. endif
  491. call s:UpdateSignatureHelp()
  492. endfunction
  493. function! s:ResolveCompletionItem( item )
  494. if s:resolve_completions != s:RESOLVE_ON_DEMAND
  495. return
  496. endif
  497. let complete_mode = complete_info( [ 'mode' ] ).mode
  498. if complete_mode !=# 'eval' && complete_mode !=# 'function'
  499. return
  500. endif
  501. if py3eval( 'ycm_state.ResolveCompletionItem( vim.eval( "a:item" ) )' )
  502. call s:StopPoller( s:pollers.completion )
  503. call timer_start( 0, function( 's:PollResolve', [ a:item ] ) )
  504. else
  505. call s:ShowInfoPopup( a:item )
  506. endif
  507. endfunction
  508. function! s:EnableAutoHover()
  509. if g:ycm_auto_hover ==# 'CursorHold' && s:enable_hover
  510. augroup YcmBufHover
  511. autocmd! * <buffer>
  512. autocmd CursorHold <buffer> call s:Hover()
  513. augroup END
  514. endif
  515. endfunction
  516. function! s:DisableAutoHover()
  517. augroup YcmBufHover
  518. autocmd! * <buffer>
  519. augroup END
  520. endfunction
  521. function! s:OnFileTypeSet()
  522. " The contents of the command-line window are empty when the filetype is set
  523. " for the first time. Users should never change its filetype so we only rely
  524. " on the CmdwinEnter event for that window.
  525. if !empty( getcmdwintype() )
  526. return
  527. endif
  528. if !s:AllowedToCompleteInCurrentBuffer()
  529. return
  530. endif
  531. call s:SetUpCompleteopt()
  532. call s:EnableCompletingInCurrentBuffer()
  533. call s:StartMessagePoll()
  534. call s:EnableAutoHover()
  535. py3 ycm_state.OnFileTypeSet()
  536. call s:OnFileReadyToParse( 1 )
  537. endfunction
  538. function! s:OnFileSave()
  539. let buffer_number = str2nr( expand( '<abuf>' ) )
  540. if !s:AllowedToCompleteInBuffer( buffer_number )
  541. return
  542. endif
  543. py3 ycm_state.OnFileSave( vimsupport.GetIntValue( 'buffer_number' ) )
  544. endfunction
  545. function! s:OnBufferEnter()
  546. call s:StartMessagePoll()
  547. if !s:VisitedBufferRequiresReparse()
  548. return
  549. endif
  550. call s:SetUpCompleteopt()
  551. call s:EnableCompletingInCurrentBuffer()
  552. py3 ycm_state.OnBufferVisit()
  553. " Last parse may be outdated because of changes from other buffers. Force a
  554. " new parse.
  555. call s:OnFileReadyToParse( 1 )
  556. endfunction
  557. function! s:OnBufferUnload()
  558. " Expanding <abuf> returns the unloaded buffer number as a string but we want
  559. " it as a true number for the getbufvar function.
  560. let buffer_number = str2nr( expand( '<abuf>' ) )
  561. if !s:AllowedToCompleteInBuffer( buffer_number )
  562. return
  563. endif
  564. py3 ycm_state.OnBufferUnload( vimsupport.GetIntValue( 'buffer_number' ) )
  565. endfunction
  566. function! s:UpdateMatches()
  567. py3 ycm_state.UpdateMatches()
  568. endfunction
  569. function! s:PollServerReady( timer_id )
  570. if !py3eval( 'ycm_state.IsServerAlive()' )
  571. py3 ycm_state.NotifyUserIfServerCrashed()
  572. " Server crashed. Don't poll it again.
  573. return
  574. endif
  575. if !py3eval( 'ycm_state.CheckIfServerIsReady()' )
  576. let s:pollers.server_ready.id = timer_start(
  577. \ s:pollers.server_ready.wait_milliseconds,
  578. \ function( 's:PollServerReady' ) )
  579. return
  580. endif
  581. call s:OnFileTypeSet()
  582. endfunction
  583. function! s:OnFileReadyToParse( ... )
  584. " Accepts an optional parameter that is either 0 or 1. If 1, send a
  585. " FileReadyToParse event notification, whether the buffer has changed or not;
  586. " effectively forcing a parse of the buffer. Default is 0.
  587. let force_parsing = a:0 > 0 && a:1
  588. " We only want to send a new FileReadyToParse event notification if the buffer
  589. " has changed since the last time we sent one, or if forced.
  590. if force_parsing || py3eval( "ycm_state.NeedsReparse()" )
  591. " We switched buffers or somethuing, so claer.
  592. " FIXME: sig hekp should be buffer local?
  593. call s:ClearSignatureHelp()
  594. py3 ycm_state.OnFileReadyToParse()
  595. call s:StopPoller( s:pollers.file_parse_response )
  596. let s:pollers.file_parse_response.id = timer_start(
  597. \ s:pollers.file_parse_response.wait_milliseconds,
  598. \ function( 's:PollFileParseResponse' ) )
  599. endif
  600. endfunction
  601. function! s:PollFileParseResponse( ... )
  602. if !py3eval( "ycm_state.FileParseRequestReady()" )
  603. let s:pollers.file_parse_response.id = timer_start(
  604. \ s:pollers.file_parse_response.wait_milliseconds,
  605. \ function( 's:PollFileParseResponse' ) )
  606. return
  607. endif
  608. py3 ycm_state.HandleFileParseRequest()
  609. if py3eval( "ycm_state.ShouldResendFileParseRequest()" )
  610. call s:OnFileReadyToParse( 1 )
  611. endif
  612. endfunction
  613. function! s:SendKeys( keys )
  614. " By default keys are added to the end of the typeahead buffer. If there are
  615. " already keys in the buffer, they will be processed first and may change
  616. " the state that our keys combination was sent for (e.g. <C-X><C-U><C-P> in
  617. " normal mode instead of insert mode or <C-e> outside of completion mode).
  618. " We avoid that by inserting the keys at the start of the typeahead buffer
  619. " with the 'i' option. Also, we don't want the keys to be remapped to
  620. " something else so we add the 'n' option.
  621. call feedkeys( a:keys, 'in' )
  622. endfunction
  623. function! s:CloseCompletionMenu()
  624. if pumvisible()
  625. call s:SendKeys( "\<C-e>" )
  626. endif
  627. endfunction
  628. function! s:OnInsertChar()
  629. if !s:AllowedToCompleteInCurrentBuffer()
  630. return
  631. endif
  632. let s:last_char_inserted_by_user = v:true
  633. endfunction
  634. function! s:StopCompletion( key )
  635. call s:StopPoller( s:pollers.completion )
  636. call s:ClearSignatureHelp()
  637. if pumvisible()
  638. let s:completion_stopped = 1
  639. return "\<C-y>"
  640. endif
  641. return a:key
  642. endfunction
  643. function! s:OnCursorMovedNormalMode()
  644. if !s:AllowedToCompleteInCurrentBuffer()
  645. return
  646. endif
  647. py3 ycm_state.OnCursorMoved()
  648. endfunction
  649. function! s:OnTextChangedNormalMode()
  650. if !s:AllowedToCompleteInCurrentBuffer()
  651. return
  652. endif
  653. call s:OnFileReadyToParse()
  654. endfunction
  655. function! s:OnTextChangedInsertMode( popup_is_visible )
  656. if !s:AllowedToCompleteInCurrentBuffer()
  657. return
  658. endif
  659. if a:popup_is_visible && !s:last_char_inserted_by_user
  660. " If the last "input" wasn't from a user typing (i.e. didn't come from
  661. " InsertCharPre, then ignore this change in the text. This prevents ctrl-n
  662. " or tab from causing us to re-filter the list based on the now-selected
  663. " item.
  664. return
  665. endif
  666. if s:completion_stopped
  667. let s:completion_stopped = 0
  668. let s:completion = s:default_completion
  669. return
  670. endif
  671. call s:IdentifierFinishedOperations()
  672. " We have to make sure we correctly leave semantic mode even when the user
  673. " inserts something like a "operator[]" candidate string which fails
  674. " CurrentIdentifierFinished check.
  675. if s:force_semantic && !py3eval( 'base.LastEnteredCharIsIdentifierChar()' )
  676. let s:force_semantic = 0
  677. endif
  678. if get( b:, 'ycm_completing' ) &&
  679. \ ( g:ycm_auto_trigger || s:force_semantic ) &&
  680. \ !s:InsideCommentOrStringAndShouldStop() &&
  681. \ !s:OnBlankLine()
  682. " The call to s:Complete here is necessary, to minimize flicker when we
  683. " close the pum on every keypress. In that case, we try to quickly show it
  684. " again with whatver the latest completion result is. When using complete(),
  685. " we don't need to do this, as we only close the pum when there are no
  686. " completions. However, it's still useful as we don't want Vim's filtering
  687. " to _ever_ apply. Examples of when this is problematic is when typing some
  688. " keys to filter (that are not a prefix of the completion), then deleting a
  689. " character. Normally Vim would re-filter based on the new "query", but we
  690. " don't want that.
  691. call s:Complete()
  692. call s:RequestCompletion()
  693. call s:UpdateSignatureHelp()
  694. call s:RequestSignatureHelp()
  695. endif
  696. py3 ycm_state.OnCursorMoved()
  697. if g:ycm_autoclose_preview_window_after_completion
  698. call s:ClosePreviewWindowIfNeeded()
  699. endif
  700. endfunction
  701. function! s:OnInsertLeave()
  702. if !s:AllowedToCompleteInCurrentBuffer()
  703. return
  704. endif
  705. let s:last_char_inserted_by_user = v:false
  706. call s:StopPoller( s:pollers.completion )
  707. let s:force_semantic = 0
  708. let s:completion = s:default_completion
  709. call s:OnFileReadyToParse()
  710. py3 ycm_state.OnInsertLeave()
  711. if g:ycm_autoclose_preview_window_after_completion ||
  712. \ g:ycm_autoclose_preview_window_after_insertion
  713. call s:ClosePreviewWindowIfNeeded()
  714. endif
  715. call s:ClearSignatureHelp()
  716. endfunction
  717. function! s:ClosePreviewWindowIfNeeded()
  718. let current_buffer_name = bufname('')
  719. " We don't want to try to close the preview window in special buffers like
  720. " "[Command Line]"; if we do, Vim goes bonkers. Special buffers always start
  721. " with '['.
  722. if current_buffer_name[ 0 ] == '['
  723. return
  724. endif
  725. " This command does the actual closing of the preview window. If no preview
  726. " window is shown, nothing happens.
  727. pclose
  728. endfunction
  729. function! s:IdentifierFinishedOperations()
  730. if !py3eval( 'base.CurrentIdentifierFinished()' )
  731. return
  732. endif
  733. py3 ycm_state.OnCurrentIdentifierFinished()
  734. let s:force_semantic = 0
  735. let s:completion = s:default_completion
  736. endfunction
  737. " Returns 1 when inside comment and 2 when inside string
  738. function! s:InsideCommentOrString()
  739. " Has to be col('.') -1 because col('.') doesn't exist at this point. We are
  740. " in insert mode when this func is called.
  741. let syntax_group = synIDattr(
  742. \ synIDtrans( synID( line( '.' ), col( '.' ) - 1, 1 ) ), 'name')
  743. if stridx(syntax_group, 'Comment') > -1
  744. return 1
  745. endif
  746. if stridx(syntax_group, 'String') > -1
  747. return 2
  748. endif
  749. return 0
  750. endfunction
  751. function! s:InsideCommentOrStringAndShouldStop()
  752. let retval = s:InsideCommentOrString()
  753. let inside_comment = retval == 1
  754. let inside_string = retval == 2
  755. if inside_comment && g:ycm_complete_in_comments ||
  756. \ inside_string && g:ycm_complete_in_strings
  757. return 0
  758. endif
  759. return retval
  760. endfunction
  761. function! s:OnBlankLine()
  762. return py3eval( 'not vim.current.line or vim.current.line.isspace()' )
  763. endfunction
  764. function! s:RequestCompletion()
  765. call s:StopPoller( s:pollers.completion )
  766. py3 ycm_state.SendCompletionRequest(
  767. \ vimsupport.GetBoolValue( 's:force_semantic' ) )
  768. if py3eval( 'ycm_state.CompletionRequestReady()' )
  769. " We can't call complete() syncrhounsouly in the TextChangedI/TextChangedP
  770. " autocommmands (it's designed to be used async only completion). The result
  771. " (somewhat oddly) is that the completion menu is shown, but ctrl-n doesn't
  772. " actually select anything.
  773. " When the request is satisfied synchronously (e.g. the omnicompleter), we
  774. " must return to the main loop before triggering completion, so we use a 0ms
  775. " timer for that.
  776. let s:pollers.completion.id = timer_start( 0,
  777. \ function( 's:PollCompletion' ) )
  778. else
  779. " Otherwise, use our usual poll timeout
  780. call s:PollCompletion()
  781. endif
  782. endfunction
  783. function! s:RequestSemanticCompletion()
  784. if !s:AllowedToCompleteInCurrentBuffer()
  785. return ''
  786. endif
  787. if get( b:, 'ycm_completing' )
  788. let s:force_semantic = 1
  789. call s:StopPoller( s:pollers.completion )
  790. py3 ycm_state.SendCompletionRequest( True )
  791. if py3eval( 'ycm_state.CompletionRequestReady()' )
  792. " We can't call complete() syncrhounsouly in the TextChangedI/TextChangedP
  793. " autocommmands (it's designed to be used async only completion). The
  794. " result (somewhat oddly) is that the completion menu is shown, but ctrl-n
  795. " doesn't actually select anything. When the request is satisfied
  796. " synchronously (e.g. the omnicompleter), we must return to the main loop
  797. " before triggering completion, so we use a 0ms timer for that.
  798. let s:pollers.completion.id = timer_start(
  799. \ 0,
  800. \ function( 's:PollCompletion' ) )
  801. else
  802. " Otherwise, use our usual poll timeout
  803. call s:PollCompletion()
  804. endif
  805. endif
  806. " Since this function is called in a mapping through the expression register
  807. " <C-R>=, its return value is inserted (see :h c_CTRL-R_=). We don't want to
  808. " insert anything so we return an empty string.
  809. return ''
  810. endfunction
  811. function! s:PollCompletion( ... )
  812. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  813. let s:pollers.completion.id = timer_start(
  814. \ s:pollers.completion.wait_milliseconds,
  815. \ function( 's:PollCompletion' ) )
  816. return
  817. endif
  818. let s:completion = py3eval( 'ycm_state.GetCompletionResponse()' )
  819. call s:Complete()
  820. endfunction
  821. function! s:PollResolve( item, ... )
  822. if !py3eval( 'ycm_state.CompletionRequestReady()' )
  823. let s:pollers.completion.id = timer_start(
  824. \ s:pollers.completion.wait_milliseconds,
  825. \ function( 's:PollResolve', [ a:item ] ) )
  826. return
  827. endif
  828. " Note we re-use the 'completion' request for resolves. This prevents us
  829. " sending a completion request and a resolve request at the same time, as
  830. " resolve requests re-use the requset data from the last completion request
  831. " and it must not change.
  832. " We also re-use the poller, so that any new completion request effectively
  833. " cancels this poller.
  834. let completion_item =
  835. \ py3eval( 'ycm_state.GetCompletionResponse()[ "completion" ]' )
  836. if empty( completion_item ) || empty( completion_item.info )
  837. return
  838. endif
  839. call s:ShowInfoPopup( completion_item )
  840. endfunction
  841. function! s:ShowInfoPopup( completion_item )
  842. let id = popup_findinfo()
  843. if id
  844. call popup_settext( id, split( a:completion_item.info, '\n' ) )
  845. call popup_show( id )
  846. endif
  847. endfunction
  848. function! s:ShouldUseSignatureHelp()
  849. return py3eval( 'vimsupport.VimSupportsPopupWindows()' )
  850. endfunction
  851. function! s:RequestSignatureHelp()
  852. if !s:ShouldUseSignatureHelp()
  853. return
  854. endif
  855. call s:StopPoller( s:pollers.signature_help )
  856. if py3eval( 'ycm_state.SendSignatureHelpRequest()' )
  857. call s:PollSignatureHelp()
  858. endif
  859. endfunction
  860. function! s:PollSignatureHelp( ... )
  861. if !s:ShouldUseSignatureHelp()
  862. return
  863. endif
  864. if a:0 == 0 && s:pollers.signature_help.id >= 0
  865. " OK this is a bug. We have tried to poll for a response while the timer is
  866. " already running. Just return and wait for the timer to fire.
  867. return
  868. endif
  869. if !py3eval( 'ycm_state.SignatureHelpRequestReady()' )
  870. let s:pollers.signature_help.id = timer_start(
  871. \ s:pollers.signature_help.wait_milliseconds,
  872. \ function( 's:PollSignatureHelp' ) )
  873. return
  874. endif
  875. let s:signature_help = py3eval( 'ycm_state.GetSignatureHelpResponse()' )
  876. call s:UpdateSignatureHelp()
  877. endfunction
  878. function! s:Complete()
  879. " It's possible for us to be called (by our timer) when we're not _strictly_
  880. " in insert mode. This can happen when mode is temporarily switched, e.g.
  881. " due to Ctrl-r or Ctrl-o or a timer or something. If we're not in insert
  882. " mode _now_ do nothing (FIXME: or should we queue a timer ?)
  883. if count( [ 'i', 'R' ], mode() ) == 0
  884. return
  885. endif
  886. if s:completion.line != line( '.' )
  887. " Given
  888. " scb: column where the completion starts before auto-wrapping
  889. " cb: cursor column before auto-wrapping
  890. " sca: column where the completion starts after auto-wrapping
  891. " ca: cursor column after auto-wrapping
  892. " we have
  893. " ca - sca = cb - scb
  894. " sca = scb + ca - cb
  895. let s:completion.completion_start_column +=
  896. \ col( '.' ) - s:completion.column
  897. endif
  898. if len( s:completion.completions )
  899. let old_completeopt = &completeopt
  900. set completeopt+=noselect
  901. call complete( s:completion.completion_start_column,
  902. \ s:completion.completions )
  903. let &completeopt = old_completeopt
  904. elseif pumvisible()
  905. call s:CloseCompletionMenu()
  906. endif
  907. endfunction
  908. function! s:UpdateSignatureHelp()
  909. if !s:ShouldUseSignatureHelp()
  910. return
  911. endif
  912. call py3eval(
  913. \ 'ycm_state.UpdateSignatureHelp( vim.eval( "s:signature_help" ) )' )
  914. endfunction
  915. function! s:ClearSignatureHelp()
  916. if !s:ShouldUseSignatureHelp()
  917. return
  918. endif
  919. call s:StopPoller( s:pollers.signature_help )
  920. let s:signature_help = s:default_signature_help
  921. call py3eval( 'ycm_state.ClearSignatureHelp()' )
  922. endfunction
  923. function! youcompleteme#ServerPid()
  924. return py3eval( 'ycm_state.ServerPid()' )
  925. endfunction
  926. function! s:SetUpCommands()
  927. command! YcmRestartServer call s:RestartServer()
  928. command! YcmDebugInfo call s:DebugInfo()
  929. command! -nargs=* -complete=custom,youcompleteme#LogsComplete -count=0
  930. \ YcmToggleLogs call s:ToggleLogs( <f-count>,
  931. \ <f-mods>,
  932. \ <f-args>)
  933. command! -nargs=* -complete=custom,youcompleteme#SubCommandsComplete -range
  934. \ YcmCompleter call s:CompleterCommand(<q-mods>,
  935. \ <count>,
  936. \ <line1>,
  937. \ <line2>,
  938. \ <f-args>)
  939. command! YcmDiags call s:ShowDiagnostics()
  940. command! YcmShowDetailedDiagnostic call s:ShowDetailedDiagnostic()
  941. command! YcmForceCompileAndDiagnostics call s:ForceCompileAndDiagnostics()
  942. endfunction
  943. function! s:RestartServer()
  944. call s:SetUpOptions()
  945. py3 ycm_state.RestartServer()
  946. call s:StopPoller( s:pollers.receive_messages )
  947. call s:StopPoller( s:pollers.command )
  948. call s:ClearSignatureHelp()
  949. call s:StopPoller( s:pollers.server_ready )
  950. let s:pollers.server_ready.id = timer_start(
  951. \ s:pollers.server_ready.wait_milliseconds,
  952. \ function( 's:PollServerReady' ) )
  953. endfunction
  954. function! s:DebugInfo()
  955. echom "Printing YouCompleteMe debug information..."
  956. let debug_info = py3eval( 'ycm_state.DebugInfo()' )
  957. echom '-- Resolve completions:'
  958. \ ( s:resolve_completions == s:RESOLVE_ON_DEMAND ? 'On demand' :
  959. \ s:resolve_completions == s:RESOLVE_UP_FRONT ? 'Up front' :
  960. \ 'Never' )
  961. for line in split( debug_info, "\n" )
  962. echom '-- ' . line
  963. endfor
  964. endfunction
  965. function! s:ToggleLogs( count, ... )
  966. py3 ycm_state.ToggleLogs( vimsupport.GetIntValue( 'a:count' ),
  967. \ *vim.eval( 'a:000' ) )
  968. endfunction
  969. function! youcompleteme#LogsComplete( arglead, cmdline, cursorpos )
  970. return join( py3eval( 'list( ycm_state.GetLogfiles() )' ), "\n" )
  971. endfunction
  972. function! youcompleteme#GetCommandResponse( ... )
  973. if !s:AllowedToCompleteInCurrentBuffer()
  974. return ''
  975. endif
  976. if !get( b:, 'ycm_completing' )
  977. return ''
  978. endif
  979. return py3eval( 'ycm_state.GetCommandResponse( vim.eval( "a:000" ) )' )
  980. endfunction
  981. function! youcompleteme#GetCommandResponseAsync( callback, ... )
  982. if !s:AllowedToCompleteInCurrentBuffer()
  983. eval a:callback( '' )
  984. return
  985. endif
  986. if !get( b:, 'ycm_completing' )
  987. eval a:callback( '' )
  988. return
  989. endif
  990. if s:pollers.command.id != -1
  991. eval a:callback( '' )
  992. return
  993. endif
  994. py3 ycm_state.SendCommandRequestAsync( vim.eval( "a:000" ) )
  995. let s:pollers.command.id = timer_start(
  996. \ s:pollers.command.wait_milliseconds,
  997. \ function( 's:PollCommand', [ a:callback ] ) )
  998. endfunction
  999. function! s:PollCommand( callback, id )
  1000. if py3eval( 'ycm_state.GetCommandRequest() is None' )
  1001. " Possible in case of race conditions and things like RestartServer
  1002. " But particualrly in the tests
  1003. return
  1004. endif
  1005. if !py3eval( 'ycm_state.GetCommandRequest().Done()' )
  1006. let s:pollers.command.id = timer_start(
  1007. \ s:pollers.command.wait_milliseconds,
  1008. \ function( 's:PollCommand', [ a:callback ] ) )
  1009. return
  1010. endif
  1011. call s:StopPoller( s:pollers.command )
  1012. let result = py3eval( 'ycm_state.GetCommandRequest().StringResponse()' )
  1013. eval a:callback( result )
  1014. endfunction
  1015. function! s:CompleterCommand( mods, count, line1, line2, ... )
  1016. py3 ycm_state.SendCommandRequest(
  1017. \ vim.eval( 'a:000' ),
  1018. \ vim.eval( 'a:mods' ),
  1019. \ vimsupport.GetBoolValue( 'a:count != -1' ),
  1020. \ vimsupport.GetIntValue( 'a:line1' ),
  1021. \ vimsupport.GetIntValue( 'a:line2' ) )
  1022. endfunction
  1023. function! youcompleteme#SubCommandsComplete( arglead, cmdline, cursorpos )
  1024. return join( py3eval( 'ycm_state.GetDefinedSubcommands()' ), "\n" )
  1025. endfunction
  1026. function! youcompleteme#GetDefinedSubcommands()
  1027. if !s:AllowedToCompleteInCurrentBuffer()
  1028. return []
  1029. endif
  1030. if !exists( 'b:ycm_completing' )
  1031. return []
  1032. endif
  1033. return py3eval( 'ycm_state.GetDefinedSubcommands()' )
  1034. endfunction
  1035. function! youcompleteme#OpenGoToList()
  1036. py3 vimsupport.PostVimMessage(
  1037. \ "'WARNING: youcompleteme#OpenGoToList function is deprecated. " .
  1038. \ "Do NOT use it.'" )
  1039. py3 vimsupport.OpenQuickFixList( True, True )
  1040. endfunction
  1041. function! s:ShowDiagnostics()
  1042. py3 ycm_state.ShowDiagnostics()
  1043. endfunction
  1044. function! s:ShowDetailedDiagnostic()
  1045. py3 ycm_state.ShowDetailedDiagnostic()
  1046. endfunction
  1047. function! s:ForceCompileAndDiagnostics()
  1048. py3 ycm_state.ForceCompileAndDiagnostics()
  1049. endfunction
  1050. if exists( '*popup_atcursor' )
  1051. function s:Hover()
  1052. if !py3eval( 'ycm_state.NativeFiletypeCompletionUsable()' )
  1053. " Cancel the autocommand if it happens to have been set
  1054. call s:DisableAutoHover()
  1055. return
  1056. endif
  1057. if !has_key( b:, 'ycm_hover' )
  1058. let cmds = youcompleteme#GetDefinedSubcommands()
  1059. if index( cmds, 'GetHover' ) >= 0
  1060. let b:ycm_hover = {
  1061. \ 'command': 'GetHover',
  1062. \ 'syntax': 'markdown',
  1063. \ }
  1064. elseif index( cmds, 'GetDoc' ) >= 0
  1065. let b:ycm_hover = {
  1066. \ 'command': 'GetDoc',
  1067. \ 'syntax': '',
  1068. \ }
  1069. elseif index( cmds, 'GetType' ) >= 0
  1070. let b:ycm_hover = {
  1071. \ 'command': 'GetType',
  1072. \ 'syntax': &syntax,
  1073. \ }
  1074. else
  1075. let b:ycm_hover = {}
  1076. endif
  1077. endif
  1078. if empty( b:ycm_hover )
  1079. return
  1080. endif
  1081. call youcompleteme#GetCommandResponseAsync(
  1082. \ function( 's:ShowHoverResult' ),
  1083. \ b:ycm_hover.command )
  1084. endfunction
  1085. function! s:ShowHoverResult( response )
  1086. call popup_hide( s:cursorhold_popup )
  1087. if empty( a:response )
  1088. return
  1089. endif
  1090. " Try to position the popup at the cursor, but avoid wrapping. If the
  1091. " longest line is > screen width (&columns), then we just have to wrap, and
  1092. " place the popup at the leftmost column.
  1093. "
  1094. " Find the longest line (FIXME: probably doesn't work well for multi-byte)
  1095. let lines = split( a:response, "\n" )
  1096. let len = max( map( copy( lines ), "len( v:val )" ) )
  1097. let wrap = 0
  1098. let col = 'cursor'
  1099. " max width is screen columns minus x padding (2)
  1100. if len >= (&columns - 2)
  1101. " There's at least one line > our max - enable word wrap and draw the
  1102. " popup at the leftmost column
  1103. let col = 1
  1104. let wrap = 1
  1105. endif
  1106. let s:cursorhold_popup = popup_atcursor(
  1107. \ lines,
  1108. \ {
  1109. \ 'col': col,
  1110. \ 'wrap': wrap,
  1111. \ 'padding': [ 0, 1, 0, 1 ],
  1112. \ 'moved': 'word',
  1113. \ 'maxwidth': &columns,
  1114. \ 'close': 'click',
  1115. \ 'fixed': 0,
  1116. \ }
  1117. \ )
  1118. call setbufvar( winbufnr( s:cursorhold_popup ),
  1119. \ '&syntax',
  1120. \ b:ycm_hover.syntax )
  1121. endfunction
  1122. function! s:ToggleHover()
  1123. let pos = popup_getpos( s:cursorhold_popup )
  1124. if !empty( pos ) && pos.visible
  1125. call popup_hide( s:cursorhold_popup )
  1126. let s:cursorhold_popup = -1
  1127. " Diable the auto-trigger until the next cursor movement.
  1128. call s:DisableAutoHover()
  1129. augroup YCMHover
  1130. autocmd! CursorMoved <buffer>
  1131. autocmd CursorMoved <buffer> call s:EnableAutoHover()
  1132. augroup END
  1133. else
  1134. call s:Hover()
  1135. endif
  1136. endfunction
  1137. let s:enable_hover = 1
  1138. nnoremap <silent> <plug>(YCMHover) :<C-u>call <SID>ToggleHover()<CR>
  1139. else
  1140. " Don't break people's mappings if this feature is disabled, just do nothing.
  1141. nnoremap <silent> <plug>(YCMHover) <Nop>
  1142. endif
  1143. function! youcompleteme#Test_GetPollers()
  1144. return s:pollers
  1145. endfunction
  1146. " This is basic vim plugin boilerplate
  1147. let &cpo = s:save_cpo
  1148. unlet s:save_cpo