robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqMerge pull request #39598 from zeertzjq/vim-9.1.1756e4876d8126

master
58.5 KiB1968 linesraw
1" Debugger plugin using gdb.
2"
3" Author: Bram Moolenaar
4" Copyright: Vim license applies, see ":help license"
5" Last Change: 2026 Mar 11
6"
7" WORK IN PROGRESS - The basics works stable, more to come
8" Note: In general you need at least GDB 7.12 because this provides the
9" frame= response in MI thread-selected events we need to sync stack to file.
10" The one included with "old" MingW is too old (7.6.1), you may upgrade it or
11" use a newer version from http://www.equation.com/servlet/equation.cmd?fa=gdb
12"
13" There are two ways to run gdb:
14" - In a terminal window; used if possible, does not work on MS-Windows
15"   Not used when g:termdebug_use_prompt is set to 1.
16" - Using a "prompt" buffer; may use a terminal window for the program
17"
18" For both the current window is used to view source code and shows the
19" current statement from gdb.
20"
21" USING A TERMINAL WINDOW
22"
23" Opens two visible terminal windows:
24" 1. runs a pty for the debugged program, as with ":term NONE"
25" 2. runs gdb, passing the pty of the debugged program
26" A third terminal window is hidden, it is used for communication with gdb.
27"
28" USING A PROMPT BUFFER
29"
30" Opens a window with a prompt buffer to communicate with gdb.
31" Gdb is run as a job with callbacks for I/O.
32" On Unix another terminal window is opened to run the debugged program
33" On MS-Windows a separate console is opened to run the debugged program
34"
35" The communication with gdb uses GDB/MI.  See:
36" https://sourceware.org/gdb/current/onlinedocs/gdb/GDB_002fMI.html
37"
38" NEOVIM COMPATIBILITY
39"
40" The vim specific functionalities were replaced with neovim specific calls:
41" - term_start -> `jobstart(…, {'term': v:true})`
42" - term_sendkeys -> chansend
43" - term_getline -> getbufline
44" - job_info && term_getjob -> nvim_get_chan_info
45" - balloon -> vim.lsp.util.open_floating_preview
46
47func s:Echoerr(msg)
48  echohl ErrorMsg | echom $'[termdebug] {a:msg}' | echohl None
49endfunc
50
51" In case this gets sourced twice.
52if exists(':Termdebug')
53  call s:Echoerr('Termdebug already loaded.')
54  finish
55endif
56
57" The terminal feature does not work with gdb on win32.
58if !has('win32')
59  let s:way = 'terminal'
60else
61  let s:way = 'prompt'
62endif
63
64let s:keepcpo = &cpo
65set cpo&vim
66
67" The command that starts debugging, e.g. ":Termdebug vim".
68" To end type "quit" in the gdb window.
69command -nargs=* -complete=file -bang Termdebug call s:StartDebug(<bang>0, <f-args>)
70command -nargs=+ -complete=file -bang TermdebugCommand call s:StartDebugCommand(<bang>0, <f-args>)
71
72" Keep track of whether Termdebug is running for tests and users.
73let g:termdebug_is_running = v:false
74
75let s:pc_id = 12
76let s:asm_id = 13
77let s:break_id = 14  " breakpoint number is added to this
78let s:stopped = v:true
79let s:running = v:false
80
81let s:parsing_disasm_msg = 0
82let s:asm_lines = []
83let s:asm_addr = ''
84
85" Take a breakpoint number as used by GDB and turn it into an integer.
86" The breakpoint may contain a dot: 123.4 -> 123004
87" The main breakpoint has a zero subid.
88func s:Breakpoint2SignNumber(id, subid)
89  return s:break_id + a:id * 1000 + a:subid
90endfunction
91
92" Define or adjust the default highlighting, using background "new".
93" When the 'background' option is set then "old" has the old value.
94func s:Highlight(init, old, new)
95  let default = a:init ? 'default ' : ''
96  if a:new ==# 'light' && a:old !=# 'light'
97    exe $"hi {default}debugPC term=reverse ctermbg=lightblue guibg=lightblue"
98  elseif a:new ==# 'dark' && a:old !=# 'dark'
99    exe $"hi {default}debugPC term=reverse ctermbg=darkblue guibg=darkblue"
100  endif
101endfunc
102
103" Define the default highlighting, using the current 'background' value.
104func s:InitHighlight()
105  call s:Highlight(1, '', &background)
106  hi default debugBreakpoint term=reverse ctermbg=red guibg=red
107  hi default debugBreakpointDisabled term=reverse ctermbg=gray guibg=gray
108endfunc
109
110" Setup an autocommand to redefine the default highlight when the colorscheme
111" is changed.
112func s:InitAutocmd()
113  augroup TermDebug
114    autocmd!
115    autocmd ColorScheme * call s:InitHighlight()
116  augroup END
117endfunc
118
119" Get the command to execute the debugger as a list, defaults to ["gdb"].
120func s:GetCommand()
121  if exists('g:termdebug_config')
122    let cmd = get(g:termdebug_config, 'command', 'gdb')
123  elseif exists('g:termdebugger')
124    let cmd = g:termdebugger
125  else
126    let cmd = 'gdb'
127  endif
128
129  return type(cmd) == v:t_list ? copy(cmd) : [cmd]
130endfunc
131
132func s:StartDebug(bang, ...)
133  " First argument is the command to debug, second core file or process ID.
134  call s:StartDebug_internal({'gdb_args': a:000, 'bang': a:bang})
135endfunc
136
137func s:StartDebugCommand(bang, ...)
138  " First argument is the command to debug, rest are run arguments.
139  call s:StartDebug_internal({'gdb_args': [a:1], 'proc_args': a:000[1:], 'bang': a:bang})
140endfunc
141
142func s:StartDebug_internal(dict)
143  if get(g:, 'termdebug_is_running', v:false) || exists('s:gdbwin')
144    call s:Echoerr('Terminal debugger already running, cannot run two')
145    return
146  endif
147  let gdbcmd = s:GetCommand()
148  if !executable(gdbcmd[0])
149    call s:Echoerr($'Cannot execute debugger program "{gdbcmd[0]}"')
150    return
151  endif
152
153  let s:ptywin = 0
154  let s:pid = 0
155  let s:asmwin = 0
156  let s:asmbufnr = 0
157  let s:varwin = 0
158  let s:varbufnr = 0
159
160  if exists('#User#TermdebugStartPre')
161    doauto <nomodeline> User TermdebugStartPre
162  endif
163
164  " Uncomment this line to write logging in "debuglog".
165  " call ch_logfile('debuglog', 'w')
166
167  let s:sourcewin = win_getid()
168
169  " Remember the old value of 'signcolumn' for each buffer that it's set in, so
170  " that we can restore the value for all buffers.
171  let b:save_signcolumn = &signcolumn
172  let s:signcolumn_buflist = [bufnr()]
173
174  let s:saved_columns = 0
175  let s:allleft = v:false
176  let wide = 0
177  if exists('g:termdebug_config')
178    let wide = get(g:termdebug_config, 'wide', 0)
179  elseif exists('g:termdebug_wide')
180    let wide = g:termdebug_wide
181  endif
182  if wide > 0
183    if &columns < wide
184      let s:saved_columns = &columns
185      let &columns = wide
186      " If we make the Vim window wider, use the whole left half for the debug
187      " windows.
188      let s:allleft = v:true
189    endif
190    let s:vertical = v:true
191  else
192    let s:vertical = v:false
193  endif
194
195  " Override using a terminal window by setting g:termdebug_use_prompt to 1.
196  let use_prompt = 0
197  if exists('g:termdebug_config')
198    let use_prompt = get(g:termdebug_config, 'use_prompt', 0)
199  elseif exists('g:termdebug_use_prompt')
200    let use_prompt = g:termdebug_use_prompt
201  endif
202  if !has('win32') && !use_prompt
203    let s:way = 'terminal'
204  else
205    let s:way = 'prompt'
206  endif
207
208  if s:way == 'prompt'
209    call s:StartDebug_prompt(a:dict)
210  else
211    call s:StartDebug_term(a:dict)
212  endif
213
214  if s:GetDisasmWindow()
215    let curwinid = win_getid()
216    call s:GotoAsmwinOrCreateIt()
217    call win_gotoid(curwinid)
218  endif
219
220  if s:GetVariablesWindow()
221    let curwinid = win_getid()
222    call s:GotoVariableswinOrCreateIt()
223    call win_gotoid(curwinid)
224  endif
225
226  if exists('#User#TermdebugStartPost')
227    doauto <nomodeline> User TermdebugStartPost
228  endif
229  let g:termdebug_is_running = v:true
230endfunc
231
232" Use when debugger didn't start or ended.
233func s:CloseBuffers()
234  for bufnr in [get(s:, 'promptbufnr', 0), get(s:, 'ptybufnr', 0), get(s:, 'asmbufnr', 0), get(s:, 'varbufnr', 0)]
235    if bufnr > 0 && bufexists(bufnr)
236      execute $'bwipe! {bufnr}'
237    endif
238  endfor
239  if exists('s:comm_job_id')
240    let commbufnr = get(nvim_get_chan_info(s:comm_job_id), 'buffer', 0)
241    if commbufnr > 0 && bufexists(commbufnr)
242      execute $'bwipe! {commbufnr}'
243    endif
244  endif
245  let s:running = v:false
246  unlet! s:gdbwin
247endfunc
248
249func s:IsGdbStarted()
250  if !s:gdb_running
251    let cmd_name = string(s:GetCommand()[0])
252    call s:Echoerr($'{cmd_name} exited unexpectedly')
253    call s:CloseBuffers()
254    return v:false
255  endif
256  return v:true
257endfunc
258
259" Open a terminal window without a job, to run the debugged program in.
260func s:StartDebug_term(dict)
261  execute s:vertical ? 'vnew' : 'new'
262  let s:pty_job_id = jobstart('tail -f /dev/null;#gdb program', {'term': v:true})
263  if s:pty_job_id == 0
264    call s:Echoerr('Invalid argument (or job table is full) while opening terminal window')
265    return
266  elseif s:pty_job_id == -1
267    call s:Echoerr('Failed to open the program terminal window')
268    return
269  endif
270  let pty_job_info = nvim_get_chan_info(s:pty_job_id)
271  let s:ptybufnr = pty_job_info['buffer']
272  let pty = pty_job_info['pty']
273  let s:ptywin = win_getid()
274  if s:vertical
275    " Assuming the source code window will get a signcolumn, use two more
276    " columns for that, thus one less for the terminal window.
277    exe $":{(&columns / 2 - 1)}wincmd |"
278    if s:allleft
279      " use the whole left column
280      wincmd H
281    endif
282  endif
283
284  " Create a hidden terminal window to communicate with gdb
285  let s:comm_job_id = jobstart('tail -f /dev/null;#gdb communication', {
286        \ 'on_stdout': function('s:JobOutCallback', {'last_line': '', 'real_cb': function('s:CommOutput')}),
287        \ 'pty': v:true,
288        \ })
289  " hide terminal buffer
290  if s:comm_job_id == 0
291    call s:Echoerr('Invalid argument (or job table is full) while opening communication terminal window')
292    exe 'bwipe! ' . s:ptybufnr
293    return
294  elseif s:comm_job_id == -1
295    call s:Echoerr('Failed to open the communication terminal window')
296    exe $'bwipe! {s:ptybufnr}'
297    return
298  endif
299  let comm_job_info = nvim_get_chan_info(s:comm_job_id)
300  let commpty = comm_job_info['pty']
301
302  let gdb_args = get(a:dict, 'gdb_args', [])
303  let proc_args = get(a:dict, 'proc_args', [])
304
305  let gdb_cmd = s:GetCommand()
306
307  if exists('g:termdebug_config') && has_key(g:termdebug_config, 'command_add_args')
308    let gdb_cmd = g:termdebug_config.command_add_args(gdb_cmd, pty)
309  else
310    " Add -quiet to avoid the intro message causing a hit-enter prompt.
311    let gdb_cmd += ['-quiet']
312    " Disable pagination, it causes everything to stop at the gdb
313    let gdb_cmd += ['-iex', 'set pagination off']
314    " Interpret commands while the target is running.  This should usually only
315    " be exec-interrupt, since many commands don't work properly while the
316    " target is running (so execute during startup).
317    let gdb_cmd += ['-iex', 'set mi-async on']
318    " Open a terminal window to run the debugger.
319    let gdb_cmd += ['-tty', pty]
320    " Command executed _after_ startup is done, provides us with the necessary
321    " feedback
322    let gdb_cmd += ['-ex', 'echo startupdone\n']
323  endif
324
325  if exists('g:termdebug_config') && has_key(g:termdebug_config, 'command_filter')
326    let gdb_cmd = g:termdebug_config.command_filter(gdb_cmd)
327  endif
328
329  " Adding arguments requested by the user
330  let gdb_cmd += gdb_args
331
332  execute 'new'
333  " call ch_log($'executing "{join(gdb_cmd)}"')
334  let s:gdb_job_id = jobstart(gdb_cmd, {'term': v:true, 'on_exit': function('s:EndTermDebug')})
335  if s:gdb_job_id == 0
336    call s:Echoerr('Invalid argument (or job table is full) while opening gdb terminal window')
337    exe 'bwipe! ' . s:ptybufnr
338    return
339  elseif s:gdb_job_id == -1
340    call s:Echoerr('Failed to open the gdb terminal window')
341    call s:CloseBuffers()
342    return
343  endif
344  let s:gdb_running = v:true
345  let s:starting = v:true
346  let gdb_job_info = nvim_get_chan_info(s:gdb_job_id)
347  let s:gdbbufnr = gdb_job_info['buffer']
348  let s:gdbwin = win_getid()
349
350  " Wait for the "startupdone" message before sending any commands.
351  let try_count = 0
352  while 1
353    if !s:IsGdbStarted()
354      return
355    endif
356
357    for lnum in range(1, 200)
358      if get(getbufline(s:gdbbufnr, lnum), 0, '') =~ 'startupdone'
359        let try_count = 9999
360        break
361      endif
362    endfor
363    let try_count += 1
364    if try_count > 300
365      " done or give up after five seconds
366      break
367    endif
368    sleep 10m
369  endwhile
370
371  " Set arguments to be run.
372  if !empty(proc_args)
373    call chansend(s:gdb_job_id, $"server set args {join(proc_args)}\r")
374  endif
375
376  " Connect gdb to the communication pty, using the GDB/MI interface.
377  " Prefix "server" to avoid adding this to the history.
378  call chansend(s:gdb_job_id, $"server new-ui mi {commpty}\r")
379
380  " Wait for the response to show up, users may not notice the error and wonder
381  " why the debugger doesn't work.
382  let try_count = 0
383  while 1
384    if !s:IsGdbStarted()
385      return
386    endif
387
388    let response = ''
389    for lnum in range(1, 200)
390      let line1 = get(getbufline(s:gdbbufnr, lnum), 0, '')
391      let line2 = get(getbufline(s:gdbbufnr, lnum + 1), 0, '')
392      if line1 =~ 'new-ui mi '
393        " response can be in the same line or the next line
394        let response = line1 . line2
395        if response =~ 'Undefined command'
396          call s:Echoerr('Sorry, your gdb is too old, gdb 7.12 is required')
397          " CHECKME: possibly send a "server show version" here
398          call s:CloseBuffers()
399          return
400        endif
401        if response =~ 'New UI allocated'
402          " Success!
403          break
404        endif
405      elseif line1 =~ 'Reading symbols from' && line2 !~ 'new-ui mi '
406        " Reading symbols might take a while, try more times
407        let try_count -= 1
408      endif
409    endfor
410    if response =~ 'New UI allocated'
411      break
412    endif
413    let try_count += 1
414    if try_count > 100
415      call s:Echoerr('Cannot check if your gdb works, continuing anyway')
416      break
417    endif
418    sleep 10m
419  endwhile
420
421  let s:starting = v:false
422
423  " Set the filetype, this can be used to add mappings.
424  set filetype=termdebug
425
426  call s:StartDebugCommon(a:dict)
427endfunc
428
429" Open a window with a prompt buffer to run gdb in.
430func s:StartDebug_prompt(dict)
431  if s:vertical
432    vertical new
433  else
434    new
435  endif
436  let s:gdbwin = win_getid()
437  let s:promptbufnr = bufnr('')
438  call prompt_setprompt(s:promptbufnr, 'gdb> ')
439  set buftype=prompt
440
441  if empty(glob('gdb'))
442    file gdb
443  elseif empty(glob('Termdebug-gdb-console'))
444    file Termdebug-gdb-console
445  else
446    call s:Echoerr("You have a file/folder named 'gdb'
447          \ or 'Termdebug-gdb-console'.
448          \ Please exit and rename them because Termdebug may not work as expected.")
449  endif
450
451  call prompt_setcallback(s:promptbufnr, function('s:PromptCallback'))
452  call prompt_setinterrupt(s:promptbufnr, function('s:PromptInterrupt'))
453
454  if s:vertical
455    " Assuming the source code window will get a signcolumn, use two more
456    " columns for that, thus one less for the terminal window.
457    exe $":{(&columns / 2 - 1)}wincmd |"
458  endif
459
460  let gdb_args = get(a:dict, 'gdb_args', [])
461  let proc_args = get(a:dict, 'proc_args', [])
462
463  let gdb_cmd = s:GetCommand()
464  " Add -quiet to avoid the intro message causing a hit-enter prompt.
465  let gdb_cmd += ['-quiet']
466  " Disable pagination, it causes everything to stop at the gdb, needs to be run early
467  let gdb_cmd += ['-iex', 'set pagination off']
468  " Interpret commands while the target is running.  This should usually only
469  " be exec-interrupt, since many commands don't work properly while the
470  " target is running (so execute during startup).
471  let gdb_cmd += ['-iex', 'set mi-async on']
472  " directly communicate via mi2
473  let gdb_cmd += ['--interpreter=mi2']
474
475  " Adding arguments requested by the user
476  let gdb_cmd += gdb_args
477
478  " call ch_log($'executing "{join(gdb_cmd)}"')
479  let s:gdbjob = jobstart(gdb_cmd, {
480        \ 'on_exit': function('s:EndPromptDebug'),
481        \ 'on_stdout': function('s:JobOutCallback', {'last_line': '', 'real_cb': function('s:GdbOutCallback')}),
482        \ })
483  if s:gdbjob == 0
484    call s:Echoerr('Invalid argument (or job table is full) while starting gdb job')
485    if s:promptbufnr > 0 && bufexists(s:promptbufnr)
486      exe $'bwipe! {s:promptbufnr}'
487    endif
488    return
489  elseif s:gdbjob == -1
490    call s:Echoerr('Failed to start the gdb job')
491    call s:CloseBuffers()
492    return
493  endif
494  exe $'au BufUnload <buffer={s:promptbufnr}> ++once call jobstop(s:gdbjob)'
495
496  let s:ptybufnr = 0
497  if has('win32')
498    " MS-Windows: run in a new console window for maximum compatibility
499    call s:SendCommand('set new-console on')
500  else
501    " Unix: Run the debugged program in a terminal window.  Open it below the
502    " gdb window.
503    belowright new
504    let s:pty_job_id = jobstart('tail -f /dev/null;#gdb program', {'term': v:true})
505    if s:pty_job_id == 0
506      call s:Echoerr('Invalid argument (or job table is full) while opening terminal window')
507      return
508    elseif s:pty_job_id == -1
509      call s:Echoerr('Failed to open the program terminal window')
510      return
511    endif
512    let pty_job_info = nvim_get_chan_info(s:pty_job_id)
513    let s:ptybufnr = pty_job_info['buffer']
514    let pty = pty_job_info['pty']
515    let s:ptywin = win_getid()
516    call s:SendCommand($'tty {pty}')
517
518    " Since GDB runs in a prompt window, the environment has not been set to
519    " match a terminal window, need to do that now.
520    call s:SendCommand('set env TERM = xterm-color')
521    call s:SendCommand($'set env ROWS = {winheight(s:ptywin)}')
522    call s:SendCommand($'set env LINES = {winheight(s:ptywin)}')
523    call s:SendCommand($'set env COLUMNS = {winwidth(s:ptywin)}')
524    call s:SendCommand($'set env COLORS = {&t_Co}')
525    call s:SendCommand($'set env VIM_TERMINAL = {v:version}')
526  endif
527  call s:SendCommand('set print pretty on')
528  call s:SendCommand('set breakpoint pending on')
529
530  " Set arguments to be run
531  if !empty(proc_args)
532    call s:SendCommand($'set args {join(proc_args)}')
533  endif
534
535  call s:StartDebugCommon(a:dict)
536  startinsert
537endfunc
538
539func s:StartDebugCommon(dict)
540  " Sign used to highlight the line where the program has stopped.
541  " There can be only one.
542  call sign_define('debugPC', #{linehl: 'debugPC'})
543
544  " Install debugger commands in the text window.
545  call win_gotoid(s:sourcewin)
546  call s:InstallCommands()
547  call win_gotoid(s:gdbwin)
548
549  " Contains breakpoints that have been placed, key is a string with the GDB
550  " breakpoint number.
551  " Each entry is a dict, containing the sub-breakpoints.  Key is the subid.
552  " For a breakpoint that is just a number the subid is zero.
553  " For a breakpoint "123.4" the id is "123" and subid is "4".
554  " Example, when breakpoint "44", "123", "123.1" and "123.2" exist:
555  " {'44': {'0': entry}, '123': {'0': entry, '1': entry, '2': entry}}
556  let s:breakpoints = {}
557
558  " Contains breakpoints by file/lnum.  The key is "fname:lnum".
559  " Each entry is a list of breakpoint IDs at that position.
560  let s:breakpoint_locations = {}
561
562  augroup TermDebug
563    au BufRead * call s:BufRead()
564    au BufUnload * call s:BufUnloaded()
565    au OptionSet background call s:Highlight(0, v:option_old, v:option_new)
566  augroup END
567
568  " Run the command if the bang attribute was given and got to the debug
569  " window.
570  if get(a:dict, 'bang', 0)
571    call s:SendResumingCommand('-exec-run')
572    call win_gotoid(s:ptywin)
573  endif
574endfunc
575
576" Send a command to gdb.  "cmd" is the string without line terminator.
577func s:SendCommand(cmd)
578  " call ch_log($'sending to gdb: {a:cmd}')
579  if s:way == 'prompt'
580    call chansend(s:gdbjob, $"{a:cmd}\n")
581  else
582    call chansend(s:comm_job_id, $"{a:cmd}\r")
583  endif
584endfunc
585
586func s:StopCommand()
587  if s:way == 'prompt'
588    call s:PromptInterrupt()
589  else
590    call s:SendCommand('-exec-interrupt')
591  endif
592endfunc
593
594func s:ContinueCommand()
595  if s:way == 'prompt'
596    call s:SendCommand('continue')
597  else
598    " using -exec-continue results in CTRL-C in the gdb window not working,
599    " communicating via commbuf (= use of SendCommand) has the same result
600    " call s:SendCommand('-exec-continue')
601    call chansend(s:gdb_job_id, "continue\r")
602  endif
603endfunc
604
605" This is global so that a user can create their mappings with this.
606func TermDebugSendCommand(cmd)
607  if s:way == 'prompt'
608    call chansend(s:gdbjob, $"{a:cmd}\n")
609  else
610    let do_continue = 0
611    if !s:stopped
612      let do_continue = 1
613      if s:way == 'prompt'
614        " Need to send a signal to get the UI to listen.  Strangely this is only
615        " needed once.
616        call jobstop(s:gdbjob)
617      else
618        Stop
619      endif
620      sleep 10m
621    endif
622    " TODO: should we prepend CTRL-U to clear the command?
623    call chansend(s:gdb_job_id, $"{a:cmd}\r")
624    if do_continue
625      Continue
626    endif
627  endif
628endfunc
629
630" Send a command that resumes the program.  If the program isn't stopped the
631" command is not sent (to avoid a repeated command to cause trouble).
632" If the command is sent then reset s:stopped.
633func s:SendResumingCommand(cmd)
634  if s:stopped
635    " reset s:stopped here, it may take a bit of time before we get a response
636    let s:stopped = v:false
637    " call ch_log('assume that program is running after this command')
638    call s:SendCommand(a:cmd)
639  " else
640    " call ch_log($'dropping command, program is running: {a:cmd}')
641  endif
642endfunc
643
644" Function called when entering a line in the prompt buffer.
645func s:PromptCallback(text)
646  call s:SendCommand(a:text)
647endfunc
648
649" Function called when pressing CTRL-C in the prompt buffer and when placing a
650" breakpoint.
651func s:PromptInterrupt()
652  " call ch_log('Interrupting gdb')
653  if has('win32')
654    " Using job_stop() does not work on MS-Windows, need to send SIGTRAP to
655    " the debugger program so that gdb responds again.
656    if s:pid == 0
657      call s:Echoerr('Cannot interrupt gdb, did not find a process ID')
658    else
659      call debugbreak(s:pid)
660    endif
661  else
662    call v:lua.vim.uv.kill(jobpid(s:gdbjob), 'sigint')
663  endif
664endfunc
665
666" Wrapper around job callback that handles partial lines (:h channel-lines).
667" It should be called from a Dictionary with the following keys:
668" - last_line: the last (partial) line received
669" - real_cb: a callback that assumes full lines
670func s:JobOutCallback(jobid, data, event) dict
671  let eof = (a:data == [''])
672  let msgs = a:data
673  let msgs[0] = self.last_line .. msgs[0]
674  if eof
675    let self.last_line = ''
676  else
677    let self.last_line = msgs[-1]
678    unlet msgs[-1]
679  endif
680  call self.real_cb(a:jobid, msgs, a:event)
681endfunc
682
683" Function called when gdb outputs text.
684func s:GdbOutCallback(job_id, msgs, event)
685  " call ch_log($'received from gdb: {a:text}')
686
687  let comm_msgs = []
688  let lines = []
689
690  for msg in a:msgs
691    " Disassembly messages need to be forwarded as-is.
692    if s:parsing_disasm_msg || msg =~ '^&"disassemble'
693      call s:CommOutput(a:job_id, [msg], a:event)
694      continue
695    endif
696
697    " Drop the gdb prompt, we have our own.
698    " Drop status and echo'd commands.
699    if msg == '(gdb) ' || msg == '^done' || msg[0] == '&'
700      continue
701    endif
702
703    if msg =~ '^\^error,msg='
704      if exists('s:evalexpr')
705            \ && s:DecodeMessage(msg[11:], v:false)
706            \    =~ 'A syntax error in expression, near\|No symbol .* in current context'
707        " Silently drop evaluation errors.
708        unlet s:evalexpr
709        continue
710      endif
711    elseif msg[0] == '~'
712      call add(lines, s:DecodeMessage(msg[1:], v:false))
713      continue
714    endif
715
716    call add(comm_msgs, msg)
717  endfor
718
719  let curwinid = win_getid()
720  call win_gotoid(s:gdbwin)
721
722  " Add the output above the current prompt.
723  for line in lines
724    " Nvim supports multi-line input in prompt-buffer, so the prompt line is
725    " not always the last line.
726    call append(line("':") - 1, line)
727  endfor
728  if !empty(lines)
729    set modified
730  endif
731
732  call win_gotoid(curwinid)
733  call s:CommOutput(a:job_id, comm_msgs, a:event)
734endfunc
735
736" Decode a message from gdb.  "quotedText" starts with a ", return the text up
737" to the next unescaped ", unescaping characters:
738" - remove line breaks (unless "literal" is v:true)
739" - change \" to "
740" - change \\t to \t (unless "literal" is v:true)
741" - change \0xhh to \xhh (disabled for now)
742" - change \ooo to octal
743" - change \\ to \
744func s:DecodeMessage(quotedText, literal)
745  if a:quotedText[0] != '"'
746    call s:Echoerr($'DecodeMessage(): missing quote in {a:quotedText}')
747    return
748  endif
749  let msg = a:quotedText
750        \ ->substitute('^"\|[^\\]\zs".*', '', 'g')
751        \ ->substitute('\\"', '"', 'g')
752        "\ multi-byte characters arrive in octal form
753        "\ NULL-values must be kept encoded as those break the string otherwise
754        \ ->substitute('\\000', s:NullRepl, 'g')
755        \ ->substitute('\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
756        "\ Note: GDB docs also mention hex encodings - the translations below work
757        "\       but we keep them out for performance-reasons until we actually see
758        "\       those in mi-returns
759        "\ \ ->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
760        "\ \ ->substitute('\\0x00', s:NullRepl, 'g')
761        \ ->substitute('\\\\', '\', 'g')
762        \ ->substitute(s:NullRepl, '\\000', 'g')
763  if !a:literal
764    return msg
765        \ ->substitute('\\t', "\t", 'g')
766        \ ->substitute('\\n', '', 'g')
767  else
768    return msg
769  endif
770endfunc
771const s:NullRepl = 'XXXNULLXXX'
772
773" Extract the "name" value from a gdb message with fullname="name".
774func s:GetFullname(msg)
775  if a:msg !~ 'fullname'
776    return ''
777  endif
778  let name = s:DecodeMessage(substitute(a:msg, '.*fullname=', '', ''), v:true)
779  if has('win32') && name =~ ':\\\\'
780    " sometimes the name arrives double-escaped
781    let name = substitute(name, '\\\\', '\\', 'g')
782  endif
783  return name
784endfunc
785
786" Extract the "addr" value from a gdb message with addr="0x0001234".
787func s:GetAsmAddr(msg)
788  if a:msg !~ 'addr='
789    return ''
790  endif
791  let addr = s:DecodeMessage(substitute(a:msg, '.*addr=', '', ''), v:false)
792  return addr
793endfunc
794
795func s:EndTermDebug(job_id, exit_code, event)
796  let s:gdb_running = v:false
797  if s:starting
798    return
799  endif
800
801  if exists('#User#TermdebugStopPre')
802    doauto <nomodeline> User TermdebugStopPre
803  endif
804
805  unlet s:gdbwin
806  call s:EndDebugCommon()
807endfunc
808
809func s:EndDebugCommon()
810  let curwinid = win_getid()
811  call s:CloseBuffers()
812
813  " Restore 'signcolumn' in all buffers for which it was set.
814  call win_gotoid(s:sourcewin)
815  let was_buf = bufnr()
816  for bufnr in s:signcolumn_buflist
817    if bufexists(bufnr)
818      exe $":{bufnr}buf"
819      if exists('b:save_signcolumn')
820        let &signcolumn = b:save_signcolumn
821        unlet b:save_signcolumn
822      endif
823    endif
824  endfor
825  if bufexists(was_buf)
826    exe $":{was_buf}buf"
827  endif
828
829  call s:DeleteCommands()
830
831  call win_gotoid(curwinid)
832
833  if s:saved_columns > 0
834    let &columns = s:saved_columns
835  endif
836
837  if exists('#User#TermdebugStopPost')
838    doauto <nomodeline> User TermdebugStopPost
839  endif
840
841  au! TermDebug
842  let g:termdebug_is_running = v:false
843endfunc
844
845func s:EndPromptDebug(job_id, exit_code, event)
846  if exists('#User#TermdebugStopPre')
847    doauto <nomodeline> User TermdebugStopPre
848  endif
849
850  call s:EndDebugCommon()
851  unlet! s:gdbwin
852  "call ch_log("Returning from EndPromptDebug()")
853endfunc
854
855" - CommOutput: &"disassemble $pc\n"
856" - CommOutput: ~"Dump of assembler code for function main(int, char**):\n"
857" - CommOutput: ~"   0x0000555556466f69 <+0>:\tpush   rbp\n"
858" ...
859" - CommOutput: ~"   0x0000555556467cd0:\tpop    rbp\n"
860" - CommOutput: ~"   0x0000555556467cd1:\tret    \n"
861" - CommOutput: ~"End of assembler dump.\n"
862" - CommOutput: ^done
863
864" - CommOutput: &"disassemble $pc\n"
865" - CommOutput: &"No function contains specified address.\n"
866" - CommOutput: ^error,msg="No function contains specified address."
867func s:HandleDisasmMsg(msg)
868  if a:msg =~ '^\^done'
869    let curwinid = win_getid()
870    if win_gotoid(s:asmwin)
871      silent! %delete _
872      call setline(1, s:asm_lines)
873      set nomodified
874      set filetype=asm
875
876      let lnum = search($'^{s:asm_addr}')
877      if lnum != 0
878        call sign_unplace('TermDebug', #{id: s:asm_id})
879        call sign_place(s:asm_id, 'TermDebug', 'debugPC', '%', #{lnum: lnum})
880      endif
881
882      call win_gotoid(curwinid)
883    endif
884
885    let s:parsing_disasm_msg = 0
886    let s:asm_lines = []
887  elseif a:msg =~ '^\^error,msg='
888    if s:parsing_disasm_msg == 1
889      " Disassemble call ran into an error. This can happen when gdb can't
890      " find the function frame address, so let's try to disassemble starting
891      " at current PC
892      call s:SendCommand('disassemble $pc,+100')
893    endif
894    let s:parsing_disasm_msg = 0
895  elseif a:msg =~ '^&"disassemble \$pc'
896    if a:msg =~ '+100'
897      " This is our second disasm attempt
898      let s:parsing_disasm_msg = 2
899    endif
900  elseif a:msg !~ '^&"disassemble'
901    let value = substitute(a:msg, '^\~\"[ ]*', '', '')
902    let value = substitute(value, '^=>[ ]*', '', '')
903    " Nvim already trims the final "\r" in s:CommOutput()
904    " let value = substitute(value, '\\n\"\r$', '', '')
905    let value = substitute(value, '\\n\"$', '', '')
906    let value = substitute(value, '\r', '', '')
907    let value = substitute(value, '\\t', ' ', 'g')
908
909    if value != '' || !empty(s:asm_lines)
910      call add(s:asm_lines, value)
911    endif
912  endif
913endfunc
914
915func s:ParseVarinfo(varinfo)
916  let dict = {}
917  let nameIdx = matchstrpos(a:varinfo, '{name="\([^"]*\)"')
918  let dict['name'] = a:varinfo[nameIdx[1] + 7 : nameIdx[2] - 2]
919  let typeIdx = matchstrpos(a:varinfo, ',type="\([^"]*\)"')
920  " 'type' maybe is a url-like string,
921  " try to shorten it and show only the /tail
922  let dict['type'] = (a:varinfo[typeIdx[1] + 7 : typeIdx[2] - 2])->fnamemodify(':t')
923  let valueIdx = matchstrpos(a:varinfo, ',value="\(.*\)"}')
924  if valueIdx[1] == -1
925    let dict['value'] = 'Complex value'
926  else
927    let dict['value'] = a:varinfo[valueIdx[1] + 8 : valueIdx[2] - 3]
928  endif
929  return dict
930endfunc
931
932func s:HandleVariablesMsg(msg)
933  let curwinid = win_getid()
934  if win_gotoid(s:varwin)
935
936    silent! %delete _
937    let spaceBuffer = 20
938    let spaces = repeat(' ', 16)
939    call setline(1, $'Type{spaces}Name{spaces}Value')
940    let cnt = 1
941    let capture = '{name=".\{-}",\%(arg=".\{-}",\)\{0,1\}type=".\{-}"\%(,value=".\{-}"\)\{0,1\}}'
942    let varinfo = matchstr(a:msg, capture, 0, cnt)
943    while varinfo != ''
944      let vardict = s:ParseVarinfo(varinfo)
945      call setline(cnt + 1, vardict['type'] .
946            \ repeat(' ', max([20 - len(vardict['type']), 1])) .
947            \ vardict['name'] .
948            \ repeat(' ', max([20 - len(vardict['name']), 1])) .
949            \ vardict['value'])
950      let cnt += 1
951      let varinfo = matchstr(a:msg, capture, 0, cnt)
952    endwhile
953  endif
954  call win_gotoid(curwinid)
955endfunc
956
957func s:CommOutput(job_id, msgs, event)
958  for msg in a:msgs
959    " Nvim job lines are split on "\n", so trim a suffixed CR.
960    if msg[-1:] == "\r"
961      let msg = msg[:-2]
962    endif
963
964    if s:parsing_disasm_msg
965      call s:HandleDisasmMsg(msg)
966    elseif msg != ''
967      if msg =~ '^\(\*stopped\|\*running\|=thread-selected\)'
968        call s:HandleCursor(msg)
969      elseif msg =~ '^\^done,bkpt=' || msg =~ '^=breakpoint-created,'
970        call s:HandleNewBreakpoint(msg, 0)
971      elseif msg =~ '^=breakpoint-modified,'
972        call s:HandleNewBreakpoint(msg, 1)
973      elseif msg =~ '^=breakpoint-deleted,'
974        call s:HandleBreakpointDelete(msg)
975      elseif msg =~ '^=thread-group-started'
976        call s:HandleProgramRun(msg)
977      elseif msg =~ '^\^done,value='
978        call s:HandleEvaluate(msg)
979      elseif msg =~ '^\^error,msg='
980        call s:HandleError(msg)
981      elseif msg =~ '^&"disassemble'
982        let s:parsing_disasm_msg = 1
983        let s:asm_lines = []
984        call s:HandleDisasmMsg(msg)
985      elseif msg =~ '^\^done,variables='
986        call s:HandleVariablesMsg(msg)
987      endif
988    endif
989  endfor
990endfunc
991
992func s:GotoProgram()
993  if has('win32')
994    if executable('powershell')
995      call system(printf('powershell -Command "add-type -AssemblyName microsoft.VisualBasic;[Microsoft.VisualBasic.Interaction]::AppActivate(%d);"', s:pid))
996    endif
997  else
998    call win_gotoid(s:ptywin)
999  endif
1000endfunc
1001
1002" Install commands in the current window to control the debugger.
1003func s:InstallCommands()
1004  let save_cpo = &cpo
1005  set cpo&vim
1006
1007  command -nargs=? Break call s:SetBreakpoint(<q-args>)
1008  command -nargs=? Tbreak call s:SetBreakpoint(<q-args>, v:true)
1009  command ToggleBreak call s:ToggleBreak()
1010  command Clear call s:ClearBreakpoint()
1011  command Step call s:SendResumingCommand('-exec-step')
1012  command Over call s:SendResumingCommand('-exec-next')
1013  command -nargs=? Until call s:Until(<q-args>)
1014  command Finish call s:SendResumingCommand('-exec-finish')
1015  command -nargs=* Run call s:Run(<q-args>)
1016  command -nargs=* Arguments call s:SendResumingCommand('-exec-arguments ' . <q-args>)
1017  command Stop call s:StopCommand()
1018  command Continue call s:ContinueCommand()
1019  command RunOrContinue call s:RunOrContinue()
1020
1021  command -nargs=* Frame call s:Frame(<q-args>)
1022  command -count=1 Up call s:Up(<count>)
1023  command -count=1 Down call s:Down(<count>)
1024
1025  command -range -nargs=* Evaluate call s:Evaluate(<range>, <q-args>)
1026  command Gdb call win_gotoid(s:gdbwin)
1027  command Program call s:GotoProgram()
1028  command Source call s:GotoSourcewinOrCreateIt()
1029  command Asm call s:GotoAsmwinOrCreateIt()
1030  command Var call s:GotoVariableswinOrCreateIt()
1031  command Winbar call s:InstallWinbar(1)
1032
1033  let map = 1
1034  if exists('g:termdebug_config')
1035    let map = get(g:termdebug_config, 'map_K', 1)
1036  elseif exists('g:termdebug_map_K')
1037    let map = g:termdebug_map_K
1038  endif
1039  if map
1040    let s:saved_K_map = maparg('K', 'n', 0, 1)
1041    if !empty(s:saved_K_map) && !s:saved_K_map.buffer || empty(s:saved_K_map)
1042      nnoremap K :Evaluate<CR>
1043    endif
1044  endif
1045
1046  let map = 1
1047  if exists('g:termdebug_config')
1048    let map = get(g:termdebug_config, 'map_plus', 1)
1049  endif
1050  if map
1051    let s:saved_plus_map = maparg('+', 'n', 0, 1)
1052    if !empty(s:saved_plus_map) && !s:saved_plus_map.buffer || empty(s:saved_plus_map)
1053      nnoremap <expr> + $'<Cmd>{v:count1}Up<CR>'
1054    endif
1055  endif
1056
1057  let map = 1
1058  if exists('g:termdebug_config')
1059    let map = get(g:termdebug_config, 'map_minus', 1)
1060  endif
1061  if map
1062    let s:saved_minus_map = maparg('-', 'n', 0, 1)
1063    if !empty(s:saved_minus_map) && !s:saved_minus_map.buffer || empty(s:saved_minus_map)
1064      nnoremap <expr> - $'<Cmd>{v:count1}Down<CR>'
1065    endif
1066  endif
1067
1068
1069  if has('menu') && &mouse != ''
1070    call s:InstallWinbar(0)
1071
1072    let popup = 1
1073    if exists('g:termdebug_config')
1074      let popup = get(g:termdebug_config, 'popup', 1)
1075    elseif exists('g:termdebug_popup')
1076      let popup = g:termdebug_popup
1077    endif
1078    if popup
1079      let s:saved_mousemodel = &mousemodel
1080      let &mousemodel = 'popup_setpos'
1081      an 1.200 PopUp.-SEP3-     <Nop>
1082      an 1.210 PopUp.Set\ breakpoint    :Break<CR>
1083      an 1.220 PopUp.Clear\ breakpoint  :Clear<CR>
1084      an 1.230 PopUp.Run\ until         :Until<CR>
1085      an 1.240 PopUp.Evaluate           :Evaluate<CR>
1086    endif
1087  endif
1088
1089  let &cpo = save_cpo
1090endfunc
1091
1092" let s:winbar_winids = []
1093
1094" Install the window toolbar in the current window.
1095func s:InstallWinbar(force)
1096  " if has('menu') && &mouse != ''
1097  "   nnoremenu WinBar.Step   :Step<CR>
1098  "   nnoremenu WinBar.Next   :Over<CR>
1099  "   nnoremenu WinBar.Finish :Finish<CR>
1100  "   nnoremenu WinBar.Cont   :Continue<CR>
1101  "   nnoremenu WinBar.Stop   :Stop<CR>
1102  "   nnoremenu WinBar.Eval   :Evaluate<CR>
1103  "   call add(s:winbar_winids, win_getid())
1104  " endif
1105endfunc
1106
1107" Delete installed debugger commands in the current window.
1108func s:DeleteCommands()
1109  delcommand Break
1110  delcommand Tbreak
1111  delcommand Clear
1112  delcommand Step
1113  delcommand Over
1114  delcommand Until
1115  delcommand Finish
1116  delcommand Run
1117  delcommand Arguments
1118  delcommand Stop
1119  delcommand Continue
1120  delcommand Frame
1121  delcommand Up
1122  delcommand Down
1123  delcommand Evaluate
1124  delcommand Gdb
1125  delcommand Program
1126  delcommand Source
1127  delcommand Asm
1128  delcommand Var
1129  delcommand Winbar
1130  delcommand RunOrContinue
1131  delcommand ToggleBreak
1132
1133  if exists('s:saved_K_map')
1134    if !empty(s:saved_K_map) && !s:saved_K_map.buffer
1135      nunmap K
1136      call mapset(s:saved_K_map)
1137    elseif empty(s:saved_K_map)
1138      nunmap K
1139    endif
1140    unlet s:saved_K_map
1141  endif
1142  if exists('s:saved_plus_map')
1143    if !empty(s:saved_plus_map) && !s:saved_plus_map.buffer
1144      nunmap +
1145      call mapset(s:saved_plus_map)
1146    elseif empty(s:saved_plus_map)
1147      nunmap +
1148    endif
1149    unlet s:saved_plus_map
1150  endif
1151  if exists('s:saved_minus_map')
1152    if !empty(s:saved_minus_map) && !s:saved_minus_map.buffer
1153      nunmap -
1154      call mapset(s:saved_minus_map)
1155    elseif empty(s:saved_minus_map)
1156      nunmap -
1157    endif
1158    unlet s:saved_minus_map
1159  endif
1160
1161  if has('menu')
1162    " Remove the WinBar entries from all windows where it was added.
1163    " let curwinid = win_getid()
1164    " for winid in s:winbar_winids
1165    "   if win_gotoid(winid)
1166    "     aunmenu WinBar.Step
1167    "     aunmenu WinBar.Next
1168    "     aunmenu WinBar.Finish
1169    "     aunmenu WinBar.Cont
1170    "     aunmenu WinBar.Stop
1171    "     aunmenu WinBar.Eval
1172    "   endif
1173    " endfor
1174    " call win_gotoid(curwinid)
1175    " let s:winbar_winids = []
1176
1177    if exists('s:saved_mousemodel')
1178      let &mousemodel = s:saved_mousemodel
1179      unlet s:saved_mousemodel
1180      aunmenu PopUp.-SEP3-
1181      aunmenu PopUp.Set\ breakpoint
1182      aunmenu PopUp.Clear\ breakpoint
1183      aunmenu PopUp.Run\ until
1184      aunmenu PopUp.Evaluate
1185    endif
1186  endif
1187
1188  call sign_unplace('TermDebug')
1189  unlet s:breakpoints
1190  unlet s:breakpoint_locations
1191
1192  call sign_undefine('debugPC')
1193  call sign_undefine(s:BreakpointSigns->map("'debugBreakpoint' .. v:val"))
1194  let s:BreakpointSigns = []
1195endfunc
1196
1197func s:QuoteArg(x)
1198  " Find all the occurrences of " and \ and escape them and double quote
1199  " the resulting string.
1200  return printf('"%s"', a:x->substitute('[\\"]', '\\&', 'g'))
1201endfunc
1202
1203func s:DefaultBreakpointLocation()
1204  " Use the fname:lnum format, older gdb can't handle --source.
1205  return s:QuoteArg($"{expand('%:p')}:{line('.')}")
1206endfunc
1207
1208func s:TokenizeBreakpointArguments(args)
1209  let tokens = []
1210  let start = -1
1211  let escaped = v:false
1212  let in_quotes = v:false
1213
1214  let i = 0
1215  for ch in a:args
1216    if start < 0 && ch !~# '\s'
1217      let start = i
1218    endif
1219    if start >= 0
1220      if escaped
1221        let escaped = v:false
1222      elseif ch ==# '\'
1223        let escaped = v:true
1224      elseif ch ==# '"'
1225        let in_quotes = !in_quotes
1226      elseif !in_quotes && ch =~# '\s'
1227        eval tokens->add(#{text: a:args->slice(start, i), start: start, end: i - 1})
1228        let start = -1
1229      endif
1230    endif
1231    let i += 1
1232  endfor
1233
1234  if start >= 0
1235    eval tokens->add(#{text: a:args->slice(start), start: start, end: i - 1})
1236  endif
1237  return tokens
1238endfunc
1239
1240func s:BuildBreakpointCommand(at, tbreak)
1241  let args = trim(a:at)
1242  let cmd = '-break-insert'
1243  if a:tbreak
1244    let cmd ..= ' -t'
1245  endif
1246
1247  if empty(args)
1248    return $'{cmd} {s:DefaultBreakpointLocation()}'
1249  endif
1250
1251  let condition = ''
1252  let prefix = args
1253  for token in s:TokenizeBreakpointArguments(args)
1254    if token.text ==# 'if' && token.end < strchars(args) - 1
1255      let condition = trim(args->slice(token.end + 1))
1256      let prefix = token.start > 0 ? trim(args->slice(0, token.start)) : ''
1257      break
1258    endif
1259  endfor
1260
1261  let prefix_tokens = s:TokenizeBreakpointArguments(prefix)
1262  let location = prefix
1263  let thread = ''
1264  if len(prefix_tokens) >= 2
1265        \ && prefix_tokens[-2].text ==# 'thread'
1266        \ && prefix_tokens[-1].text =~# '^\d\+$'
1267    let thread = prefix_tokens[-1].text
1268    let location = join(prefix_tokens[: -3]->mapnew('v:val.text'), ' ')
1269  endif
1270
1271  if empty(trim(location))
1272    let location = s:DefaultBreakpointLocation()
1273  endif
1274  if !empty(thread)
1275    let cmd ..= $' -p {thread}'
1276  endif
1277  if !empty(condition)
1278    let cmd ..= $' -c {s:QuoteArg(condition)}'
1279  endif
1280  return $'{cmd} {trim(location)}'
1281endfunc
1282
1283" :Until - Execute until past a specified position or current line
1284func s:Until(at)
1285  if s:stopped
1286    " reset s:stopped here, it may take a bit of time before we get a response
1287    let s:stopped = v:false
1288    " call ch_log('assume that program is running after this command')
1289    " Use the fname:lnum format
1290    let at = empty(a:at) ? s:QuoteArg($"{expand('%:p')}:{line('.')}") : a:at
1291    call s:SendCommand($'-exec-until {at}')
1292  " else
1293    " call ch_log('dropping command, program is running: exec-until')
1294  endif
1295endfunc
1296
1297" :Break - Set a breakpoint at the cursor position.
1298func s:SetBreakpoint(at, tbreak=v:false)
1299  " Setting a breakpoint may not work while the program is running.
1300  " Interrupt to make it work.
1301  let do_continue = 0
1302  if !s:stopped
1303    let do_continue = 1
1304    Stop
1305    sleep 10m
1306  endif
1307
1308  let cmd = s:BuildBreakpointCommand(a:at, a:tbreak)
1309  call s:SendCommand(cmd)
1310  if do_continue
1311    Continue
1312  endif
1313endfunc
1314
1315" :Clear - Delete a breakpoint at the cursor position.
1316func s:ClearBreakpoint()
1317  let fname = fnameescape(expand('%:p'))
1318  let lnum = line('.')
1319  let bploc = printf('%s:%d', fname, lnum)
1320  if has_key(s:breakpoint_locations, bploc)
1321    let idx = 0
1322    let nr = 0
1323    for id in s:breakpoint_locations[bploc]
1324      if has_key(s:breakpoints, id)
1325        " Assume this always works, the reply is simply "^done".
1326        call s:SendCommand($'-break-delete {id}')
1327        for subid in keys(s:breakpoints[id])
1328          call sign_unplace('TermDebug',
1329                \ #{id: s:Breakpoint2SignNumber(id, subid)})
1330        endfor
1331        unlet s:breakpoints[id]
1332        unlet s:breakpoint_locations[bploc][idx]
1333        let nr = id
1334        break
1335      else
1336        let idx += 1
1337      endif
1338    endfor
1339    if nr != 0
1340      if empty(s:breakpoint_locations[bploc])
1341        unlet s:breakpoint_locations[bploc]
1342      endif
1343      echomsg $'Breakpoint {nr} cleared from line {lnum}.'
1344    else
1345      call s:Echoerr($'Internal error trying to remove breakpoint at line {lnum}!')
1346    endif
1347  else
1348    echomsg $'No breakpoint to remove at line {lnum}.'
1349  endif
1350endfunc
1351
1352func s:ToggleBreak()
1353  let fname = fnameescape(expand('%:p'))
1354  let lnum = line('.')
1355  let bploc = printf('%s:%d', fname, lnum)
1356  if has_key(s:breakpoint_locations, bploc)
1357    while has_key(s:breakpoint_locations, bploc)
1358      call s:ClearBreakpoint()
1359    endwhile
1360  else
1361    call s:SetBreakpoint("")
1362  endif
1363endfunc
1364
1365func s:Run(args)
1366  if a:args != ''
1367    call s:SendResumingCommand($'-exec-arguments {a:args}')
1368  endif
1369  call s:SendResumingCommand('-exec-run')
1370endfunc
1371
1372func s:RunOrContinue()
1373  if s:running
1374    call s:ContinueCommand()
1375  else
1376    call s:Run('')
1377  endif
1378endfunc
1379
1380" :Frame - go to a specific frame in the stack
1381func s:Frame(arg)
1382  " Note: we explicit do not use mi's command
1383  " call s:SendCommand('-stack-select-frame "' . a:arg .'"')
1384  " as we only get a "done" mi response and would have to open the file
1385  " 'manually' - using cli command "frame" provides us with the mi response
1386  " already parsed and allows for more formats
1387  if a:arg =~ '^\d\+$' || a:arg == ''
1388    " specify frame by number
1389    call s:SendCommand($'-interpreter-exec mi "frame {a:arg}"')
1390  elseif a:arg =~ '^0x[0-9a-fA-F]\+$'
1391    " specify frame by stack address
1392    call s:SendCommand($'-interpreter-exec mi "frame address {a:arg}"')
1393  else
1394    " specify frame by function name
1395    call s:SendCommand($'-interpreter-exec mi "frame function {a:arg}"')
1396  endif
1397endfunc
1398
1399" :Up - go a:count frames in the stack "higher"
1400func s:Up(count)
1401  " the 'correct' one would be -stack-select-frame N, but we don't know N
1402  call s:SendCommand($'-interpreter-exec console "up {a:count}"')
1403endfunc
1404
1405" :Down - go a:count frames in the stack "below"
1406func s:Down(count)
1407  " the 'correct' one would be -stack-select-frame N, but we don't know N
1408  call s:SendCommand($'-interpreter-exec console "down {a:count}"')
1409endfunc
1410
1411func s:SendEval(expr)
1412  " check for "likely" boolean expressions, in which case we take it as lhs
1413  if a:expr =~ "[=!<>]="
1414    let exprLHS = a:expr
1415  else
1416    " remove text that is likely an assignment
1417    let exprLHS = substitute(a:expr, ' *=.*', '', '')
1418  endif
1419
1420  " encoding expression to prevent bad errors
1421  let expr_escaped = a:expr
1422        \ ->substitute('\\', '\\\\', 'g')
1423        \ ->substitute('"', '\\"', 'g')
1424  call s:SendCommand($'-data-evaluate-expression "{expr_escaped}"')
1425  let s:evalexpr = exprLHS
1426endfunc
1427
1428" :Evaluate - evaluate what is specified / under the cursor
1429func s:Evaluate(range, arg)
1430  if s:eval_float_win_id > 0 && nvim_win_is_valid(s:eval_float_win_id)
1431        \ && a:range == 0 && empty(a:arg)
1432    call nvim_set_current_win(s:eval_float_win_id)
1433    return
1434  endif
1435  let expr = s:GetEvaluationExpression(a:range, a:arg)
1436  let s:evalFromBalloonExpr = v:true
1437  let s:evalFromBalloonExprResult = ''
1438  let s:ignoreEvalError = v:false
1439  call s:SendEval(expr)
1440endfunc
1441
1442" get what is specified / under the cursor
1443func s:GetEvaluationExpression(range, arg)
1444  if a:arg != ''
1445    " user supplied evaluation
1446    let expr = s:CleanupExpr(a:arg)
1447    let expr = substitute(expr, '"\([^"]*\)": *', '\1=', 'g')
1448  elseif a:range == 2
1449    let pos = getcurpos()
1450    let reg = getreg('v', 1, 1)
1451    let regt = getregtype('v')
1452    normal! gv"vy
1453    let expr = s:CleanupExpr(@v)
1454    call setpos('.', pos)
1455    call setreg('v', reg, regt)
1456    let s:evalFromBalloonExpr = v:true
1457  else
1458    " no evaluation provided: get from C-expression under cursor
1459    " TODO: allow filetype specific lookup #9057
1460    let expr = expand('<cexpr>')
1461    let s:evalFromBalloonExpr = v:true
1462  endif
1463  return expr
1464endfunc
1465
1466" clean up expression that may get in because of range
1467" (newlines and surrounding whitespace)
1468" As it can also be specified via ex-command for assignments this function
1469" may not change the "content" parts (like replacing contained spaces)
1470func s:CleanupExpr(expr)
1471  " replace all embedded newlines/tabs/...
1472  let expr = substitute(a:expr, '\_s', ' ', 'g')
1473
1474  if &filetype ==# 'cobol'
1475    " extra cleanup for COBOL:
1476    " - a semicolon nmay be used instead of a space
1477    " - a trailing comma or period is ignored as it commonly separates/ends
1478    "   multiple expr
1479    let expr = substitute(expr, ';', ' ', 'g')
1480    let expr = substitute(expr, '[,.]\+ *$', '', '')
1481  endif
1482
1483  " get rid of leading and trailing spaces
1484  let expr = substitute(expr, '^ *', '', '')
1485  let expr = substitute(expr, ' *$', '', '')
1486  return expr
1487endfunc
1488
1489let s:ignoreEvalError = v:false
1490let s:evalFromBalloonExpr = v:false
1491let s:evalFromBalloonExprResult = ''
1492
1493let s:eval_float_win_id = -1
1494
1495" Handle the result of data-evaluate-expression
1496func s:HandleEvaluate(msg)
1497  let value = a:msg
1498        \ ->substitute('.*value="\(.*\)"', '\1', '')
1499        \ ->substitute('\\"', '"', 'g')
1500        \ ->substitute('\\\\', '\\', 'g')
1501        "\ multi-byte characters arrive in octal form, replace everything but NULL values
1502        \ ->substitute('\\000', s:NullRepl, 'g')
1503        \ ->substitute('\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
1504        "\ Note: GDB docs also mention hex encodings - the translations below work
1505        "\       but we keep them out for performance-reasons until we actually see
1506        "\       those in mi-returns
1507        "\ ->substitute('\\0x00', s:NullRep, 'g')
1508        "\ ->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
1509        \ ->substitute(s:NullRepl, '\\000', 'g')
1510        \ ->substitute('
', '\1', '')
1511  if s:evalFromBalloonExpr
1512    if s:evalFromBalloonExprResult == ''
1513      let s:evalFromBalloonExprResult = $'{s:evalexpr}: {value}'
1514    else
1515      let s:evalFromBalloonExprResult ..= $' = {value}'
1516    endif
1517    " NEOVIM:
1518    " - Result pretty-printing is not implemented. Vim prettifies the result
1519    "   with balloon_split(), which is not ported to nvim.
1520    " - Manually implement window focusing. Sometimes the result of pointer
1521    "   evaluation arrives in two separate messages, one for the address
1522    "   itself and the other for the value in that address. So with the stock
1523    "   focus option, the second message will focus the window containing the
1524    "   first message.
1525    let s:eval_float_win_id = luaeval('select(2, vim.lsp.util.open_floating_preview(_A))', split(s:evalFromBalloonExprResult, '\\n'))
1526  else
1527    echomsg $'"{s:evalexpr}": {value}'
1528  endif
1529
1530  if s:evalexpr[0] != '*' && value =~ '^0x' && value != '0x0' && value !~ '"$'
1531    " Looks like a pointer, also display what it points to.
1532    let s:ignoreEvalError = v:true
1533    call s:SendEval($'*{s:evalexpr}')
1534  endif
1535endfunc
1536
1537" Handle an error.
1538func s:HandleError(msg)
1539  if s:ignoreEvalError
1540    " Result of s:SendEval() failed, ignore.
1541    let s:ignoreEvalError = v:false
1542    let s:evalFromBalloonExpr = v:false
1543    return
1544  endif
1545  let msgVal = substitute(a:msg, '.*msg="\(.*\)"', '\1', '')
1546  call s:Echoerr(substitute(msgVal, '\\"', '"', 'g'))
1547endfunc
1548
1549func s:GotoSourcewinOrCreateIt()
1550  if !win_gotoid(s:sourcewin)
1551    new
1552    let s:sourcewin = win_getid()
1553    call s:InstallWinbar(0)
1554  endif
1555endfunc
1556
1557func s:GetDisasmWindow()
1558  if exists('g:termdebug_config')
1559    return get(g:termdebug_config, 'disasm_window', 0)
1560  endif
1561  if exists('g:termdebug_disasm_window')
1562    return g:termdebug_disasm_window
1563  endif
1564  return 0
1565endfunc
1566
1567func s:GetDisasmWindowHeight()
1568  if exists('g:termdebug_config')
1569    return get(g:termdebug_config, 'disasm_window_height', 0)
1570  endif
1571  if exists('g:termdebug_disasm_window') && g:termdebug_disasm_window > 1
1572    return g:termdebug_disasm_window
1573  endif
1574  return 0
1575endfunc
1576
1577func s:GotoAsmwinOrCreateIt()
1578  if !win_gotoid(s:asmwin)
1579    let mdf = ''
1580    if win_gotoid(s:sourcewin)
1581      " 60 is approx spaceBuffer * 3
1582      if winwidth(0) > (78 + 60)
1583        let mdf = 'vert'
1584        exe $'{mdf} :60new'
1585      else
1586        exe 'rightbelow new'
1587      endif
1588    else
1589      exe 'new'
1590    endif
1591
1592    let s:asmwin = win_getid()
1593
1594    setlocal nowrap
1595    setlocal number
1596    setlocal noswapfile
1597    setlocal buftype=nofile
1598    setlocal bufhidden=wipe
1599    setlocal signcolumn=no
1600    setlocal modifiable
1601
1602    if s:asmbufnr > 0 && bufexists(s:asmbufnr)
1603      exe $'buffer {s:asmbufnr}'
1604    elseif empty(glob('Termdebug-asm-listing'))
1605      silent file Termdebug-asm-listing
1606      let s:asmbufnr = bufnr('Termdebug-asm-listing')
1607    else
1608      call s:Echoerr("You have a file/folder named 'Termdebug-asm-listing'.
1609          \ Please exit and rename it because Termdebug may not work as expected.")
1610    endif
1611
1612    if mdf != 'vert' && s:GetDisasmWindowHeight() > 0
1613      exe $'resize {s:GetDisasmWindowHeight()}'
1614    endif
1615  endif
1616
1617  if s:asm_addr != ''
1618    let lnum = search($'^{s:asm_addr}')
1619    if lnum == 0
1620      if s:stopped
1621        call s:SendCommand('disassemble $pc')
1622      endif
1623    else
1624      call sign_unplace('TermDebug', #{id: s:asm_id})
1625      call sign_place(s:asm_id, 'TermDebug', 'debugPC', '%', #{lnum: lnum})
1626    endif
1627  endif
1628endfunc
1629
1630func s:GetVariablesWindow()
1631  if exists('g:termdebug_config')
1632    return get(g:termdebug_config, 'variables_window', 0)
1633  endif
1634  if exists('g:termdebug_disasm_window')
1635    return g:termdebug_variables_window
1636  endif
1637  return 0
1638endfunc
1639
1640func s:GetVariablesWindowHeight()
1641  if exists('g:termdebug_config')
1642    return get(g:termdebug_config, 'variables_window_height', 0)
1643  endif
1644  if exists('g:termdebug_variables_window') && g:termdebug_variables_window > 1
1645    return g:termdebug_variables_window
1646  endif
1647  return 0
1648endfunc
1649
1650func s:GotoVariableswinOrCreateIt()
1651  if !win_gotoid(s:varwin)
1652    let mdf = ''
1653    if win_gotoid(s:sourcewin)
1654      " 60 is approx spaceBuffer * 3
1655      if winwidth(0) > (78 + 60)
1656        let mdf = 'vert'
1657        exe $'{mdf} :60new'
1658      else
1659        exe 'rightbelow new'
1660      endif
1661    else
1662      exe 'new'
1663    endif
1664
1665    let s:varwin = win_getid()
1666
1667    setlocal nowrap
1668    setlocal noswapfile
1669    setlocal buftype=nofile
1670    setlocal bufhidden=wipe
1671    setlocal signcolumn=no
1672    setlocal modifiable
1673
1674    if s:varbufnr > 0 && bufexists(s:varbufnr)
1675      exe $'buffer {s:varbufnr}'
1676    elseif empty(glob('Termdebug-variables-listing'))
1677      silent file Termdebug-variables-listing
1678      let s:varbufnr = bufnr('Termdebug-variables-listing')
1679    else
1680      call s:Echoerr("You have a file/folder named 'Termdebug-variables-listing'.
1681          \ Please exit and rename it because Termdebug may not work as expected.")
1682    endif
1683
1684    if mdf != 'vert' && s:GetVariablesWindowHeight() > 0
1685      exe $'resize {s:GetVariablesWindowHeight()}'
1686    endif
1687  endif
1688
1689  if s:running
1690    call s:SendCommand('-stack-list-variables 2')
1691  endif
1692endfunc
1693
1694" Handle stopping and running message from gdb.
1695" Will update the sign that shows the current position.
1696func s:HandleCursor(msg)
1697  let wid = win_getid()
1698
1699  if a:msg =~ '^\*stopped'
1700    "call ch_log('program stopped')
1701    let s:stopped = v:true
1702    if a:msg =~ '^\*stopped,reason="exited-normally"'
1703      let s:running = v:false
1704    endif
1705  elseif a:msg =~ '^\*running'
1706    "call ch_log('program running')
1707    let s:stopped = v:false
1708    let s:running = v:true
1709  endif
1710
1711  if a:msg =~ 'fullname='
1712    let fname = s:GetFullname(a:msg)
1713  else
1714    let fname = ''
1715  endif
1716
1717  if a:msg =~ 'addr='
1718    let asm_addr = s:GetAsmAddr(a:msg)
1719    if asm_addr != ''
1720      let s:asm_addr = asm_addr
1721
1722      let curwinid = win_getid()
1723      if win_gotoid(s:asmwin)
1724        let lnum = search($'^{s:asm_addr}')
1725        if lnum == 0
1726          call s:SendCommand('disassemble $pc')
1727        else
1728          call sign_unplace('TermDebug', #{id: s:asm_id})
1729          call sign_place(s:asm_id, 'TermDebug', 'debugPC', '%', #{lnum: lnum})
1730        endif
1731
1732        call win_gotoid(curwinid)
1733      endif
1734    endif
1735  endif
1736
1737  if s:running && s:stopped && bufwinnr('Termdebug-variables-listing') != -1
1738    call s:SendCommand('-stack-list-variables 2')
1739  endif
1740
1741  if a:msg =~ '^\(\*stopped\|=thread-selected\)' && filereadable(fname)
1742    let lnum = substitute(a:msg, '.*line="\([^"]*\)".*', '\1', '')
1743    if lnum =~ '^[0-9]*$'
1744      call s:GotoSourcewinOrCreateIt()
1745      if expand('%:p') != fnamemodify(fname, ':p')
1746        echomsg $"different fname: '{expand('%:p')}' vs '{fnamemodify(fname, ':p')}'"
1747        augroup Termdebug
1748          " Always open a file read-only instead of showing the ATTENTION
1749          " prompt, since it is unlikely we want to edit the file.
1750          " The file may be changed but not saved, warn for that.
1751          au SwapExists * echohl WarningMsg
1752          \ | echo 'Warning: file is being edited elsewhere'
1753          \ | echohl None
1754          \ | let v:swapchoice = 'o'
1755        augroup END
1756        if &modified
1757          " TODO: find existing window
1758          exe $'split {fnameescape(fname)}'
1759          let s:sourcewin = win_getid()
1760          call s:InstallWinbar(0)
1761        else
1762          exe $'edit {fnameescape(fname)}'
1763        endif
1764        augroup Termdebug
1765          au! SwapExists
1766        augroup END
1767      endif
1768      exe $":{lnum}"
1769      normal! zv
1770      call sign_unplace('TermDebug', #{id: s:pc_id})
1771      call sign_place(s:pc_id, 'TermDebug', 'debugPC', fname,
1772            \ #{lnum: lnum, priority: 110})
1773      if !exists('b:save_signcolumn')
1774        let b:save_signcolumn = &signcolumn
1775        call add(s:signcolumn_buflist, bufnr())
1776      endif
1777      setlocal signcolumn=yes
1778    endif
1779  elseif !s:stopped || fname != ''
1780    call sign_unplace('TermDebug', #{id: s:pc_id})
1781  endif
1782
1783  call win_gotoid(wid)
1784endfunc
1785
1786let s:BreakpointSigns = []
1787
1788func s:CreateBreakpoint(id, subid, enabled)
1789  let nr = printf('%d.%d', a:id, a:subid)
1790  if index(s:BreakpointSigns, nr) == -1
1791    call add(s:BreakpointSigns, nr)
1792    if a:enabled == "n"
1793      let hiName = "debugBreakpointDisabled"
1794    else
1795      let hiName = "debugBreakpoint"
1796    endif
1797    let label = ''
1798    if exists('g:termdebug_config')
1799      if has_key(g:termdebug_config, 'signs')
1800        let label = get(g:termdebug_config.signs, a:id - 1, '')
1801      endif
1802      if label == '' && has_key(g:termdebug_config, 'sign')
1803        let label = g:termdebug_config['sign']
1804      endif
1805      if label == '' && has_key(g:termdebug_config, 'sign_decimal')
1806        let label = printf('%02d', a:id)
1807        if a:id > 99
1808          let label = '9+'
1809        endif
1810      endif
1811    endif
1812    if label == ''
1813      let label = printf('%02X', a:id)
1814      if a:id > 255
1815        let label = 'F+'
1816      endif
1817    endif
1818    call sign_define($'debugBreakpoint{nr}',
1819          \ #{text: slice(label, 0, 2),
1820          \ texthl: hiName})
1821  endif
1822endfunc
1823
1824func! s:SplitMsg(s)
1825  return split(a:s, '{.\{-}}\zs')
1826endfunction
1827
1828" Handle setting a breakpoint
1829" Will update the sign that shows the breakpoint
1830func s:HandleNewBreakpoint(msg, modifiedFlag)
1831  if a:msg !~ 'fullname='
1832    " a watch or a pending breakpoint does not have a file name
1833    if a:msg =~ 'pending='
1834      let nr = substitute(a:msg, '.*number=\"\([0-9.]*\)\".*', '\1', '')
1835      let target = substitute(a:msg, '.*pending=\"\([^"]*\)\".*', '\1', '')
1836      echomsg $'Breakpoint {nr} ({target}) pending.'
1837    endif
1838    return
1839  endif
1840  for msg in s:SplitMsg(a:msg)
1841    let fname = s:GetFullname(msg)
1842    if empty(fname)
1843      continue
1844    endif
1845    let nr = substitute(msg, '.*number="\([0-9.]*\)\".*', '\1', '')
1846    if empty(nr)
1847      return
1848    endif
1849
1850    " If "nr" is 123 it becomes "123.0" and subid is "0".
1851    " If "nr" is 123.4 it becomes "123.4.0" and subid is "4"; "0" is discarded.
1852    let [id, subid; _] = map(split(nr . '.0', '\.'), 'v:val + 0')
1853    let enabled = substitute(msg, '.*enabled="\([yn]\)".*', '\1', '')
1854    call s:CreateBreakpoint(id, subid, enabled)
1855
1856    if has_key(s:breakpoints, id)
1857      let entries = s:breakpoints[id]
1858    else
1859      let entries = {}
1860      let s:breakpoints[id] = entries
1861    endif
1862    if has_key(entries, subid)
1863      let entry = entries[subid]
1864    else
1865      let entry = {}
1866      let entries[subid] = entry
1867    endif
1868
1869    let lnum = substitute(msg, '.*line="\([^"]*\)".*', '\1', '')
1870    let entry['fname'] = fname
1871    let entry['lnum'] = lnum
1872
1873    let bploc = printf('%s:%d', fname, lnum)
1874    if !has_key(s:breakpoint_locations, bploc)
1875      let s:breakpoint_locations[bploc] = []
1876    endif
1877    if s:breakpoint_locations[bploc]->index(id) == -1
1878      " Make sure all ids are unique
1879      let s:breakpoint_locations[bploc] += [id]
1880    endif
1881
1882    if bufloaded(fname)
1883      call s:PlaceSign(id, subid, entry)
1884      let posMsg = $' at line {lnum}.'
1885    else
1886      let posMsg = $' in {fname} at line {lnum}.'
1887    endif
1888    if !a:modifiedFlag
1889      let actionTaken = 'created'
1890    elseif enabled == 'n'
1891      let actionTaken = 'disabled'
1892    else
1893      let actionTaken = 'enabled'
1894    endif
1895    echom $'Breakpoint {nr} {actionTaken}{posMsg}'
1896  endfor
1897endfunc
1898
1899func s:PlaceSign(id, subid, entry)
1900  let nr = printf('%d.%d', a:id, a:subid)
1901  call sign_place(s:Breakpoint2SignNumber(a:id, a:subid), 'TermDebug',
1902        \ $'debugBreakpoint{nr}', a:entry['fname'],
1903        \ #{lnum: a:entry['lnum'], priority: 110})
1904  let a:entry['placed'] = 1
1905endfunc
1906
1907" Handle deleting a breakpoint
1908" Will remove the sign that shows the breakpoint
1909func s:HandleBreakpointDelete(msg)
1910  let id = substitute(a:msg, '.*id="\([0-9]*\)\".*', '\1', '') + 0
1911  if empty(id)
1912    return
1913  endif
1914  if has_key(s:breakpoints, id)
1915    for [subid, entry] in items(s:breakpoints[id])
1916      if has_key(entry, 'placed')
1917        call sign_unplace('TermDebug',
1918              \ #{id: s:Breakpoint2SignNumber(id, subid)})
1919        unlet entry['placed']
1920      endif
1921    endfor
1922    unlet s:breakpoints[id]
1923    echomsg $'Breakpoint {id} cleared.'
1924  endif
1925endfunc
1926
1927" Handle the debugged program starting to run.
1928" Will store the process ID in s:pid
1929func s:HandleProgramRun(msg)
1930  let nr = substitute(a:msg, '.*pid="\([0-9]*\)\".*', '\1', '') + 0
1931  if nr == 0
1932    return
1933  endif
1934  let s:pid = nr
1935  " call ch_log($'Detected process ID: {s:pid}')
1936endfunc
1937
1938" Handle a BufRead autocommand event: place any signs.
1939func s:BufRead()
1940  let fname = expand('<afile>:p')
1941  for [id, entries] in items(s:breakpoints)
1942    for [subid, entry] in items(entries)
1943      if entry['fname'] == fname
1944        call s:PlaceSign(id, subid, entry)
1945      endif
1946    endfor
1947  endfor
1948endfunc
1949
1950" Handle a BufUnloaded autocommand event: unplace any signs.
1951func s:BufUnloaded()
1952  let fname = expand('<afile>:p')
1953  for [id, entries] in items(s:breakpoints)
1954    for [subid, entry] in items(entries)
1955      if entry['fname'] == fname
1956        let entry['placed'] = 0
1957      endif
1958    endfor
1959  endfor
1960endfunc
1961
1962call s:InitHighlight()
1963call s:InitAutocmd()
1964
1965let &cpo = s:keepcpo
1966unlet s:keepcpo
1967
1968" vim: sw=2 sts=2 et