vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

termdebug.vim (69832B)


      1 vim9script
      2 
      3 # Debugger plugin using gdb.
      4 
      5 # Author: Bram Moolenaar
      6 # Copyright: Vim license applies, see ":help license"
      7 # Last Change: 2026 Sep 25
      8 # Converted to Vim9: Ubaldo Tiberi <ubaldo.tiberi@gmail.com>
      9 
     10 # WORK IN PROGRESS - The basics works stable, more to come
     11 # Note: In general you need at least GDB 7.12 because this provides the
     12 # frame= response in MI thread-selected events we need to sync stack to file.
     13 # The one included with "old" MingW is too old (7.6.1), you may upgrade it or
     14 # use a newer version from http://www.equation.com/servlet/equation.cmd?fa=gdb
     15 
     16 # There are two ways to run gdb:
     17 # - In a terminal window; used if possible, does not work on MS-Windows
     18 #   Not used when g:termdebug_use_prompt is set to true.
     19 # - Using a "prompt" buffer; may use a terminal window for the program
     20 
     21 # For both the current window is used to view source code and shows the
     22 # current statement from gdb.
     23 
     24 # USING A TERMINAL WINDOW
     25 
     26 # Opens two visible terminal windows:
     27 # 1. runs a pty for the debugged program, as with ":term NONE"
     28 # 2. runs gdb, passing the pty of the debugged program
     29 # A third terminal window is hidden, it is used for communication with gdb.
     30 
     31 # USING A PROMPT BUFFER
     32 
     33 # Opens a window with a prompt buffer to communicate with gdb.
     34 # Gdb is run as a job with callbacks for I/O.
     35 # On Unix another terminal window is opened to run the debugged program
     36 # On MS-Windows a separate console is opened to run the debugged program
     37 # but a terminal window is used to run remote debugged programs.
     38 
     39 # The communication with gdb uses GDB/MI.  See:
     40 # https://sourceware.org/gdb/current/onlinedocs/gdb/GDB_002fMI.html
     41 
     42 var DEBUG = false
     43 if exists('g:termdebug_config')
     44   DEBUG = get(g:termdebug_config, 'debug', false)
     45 endif
     46 
     47 def Echoerr(msg: string)
     48   echohl ErrorMsg | echom $'[termdebug] {msg}' | echohl None
     49 enddef
     50 
     51 def Echowarn(msg: string)
     52   echohl WarningMsg | echom $'[termdebug] {msg}' | echohl None
     53 enddef
     54 
     55 # Variables to keep their status among multiple instances of Termdebug
     56 g:termdebug_is_running = false
     57 
     58 
     59 # The command that starts debugging, e.g. ":Termdebug vim".
     60 # To end type "quit" in the gdb window.
     61 command -nargs=* -complete=file -bang Termdebug StartDebug(<bang>0, <f-args>)
     62 command -nargs=+ -complete=file -bang TermdebugCommand StartDebugCommand(<bang>0, <f-args>)
     63 
     64 enum Way
     65   Prompt,
     66   Terminal
     67 endenum
     68 
     69 # Script variables declaration. These variables are re-initialized at every
     70 # Termdebug instance
     71 var way: Way
     72 var err: string
     73 
     74 var pc_id: number
     75 var asm_id: number
     76 var break_id: number
     77 var stopped: bool
     78 var running: bool
     79 
     80 var parsing_disasm_msg: number
     81 var asm_lines: list<string>
     82 var asm_addr: string
     83 
     84 # These shall be constants but cannot be initialized here
     85 # They indicate the buffer numbers of the main buffers used
     86 var gdbbufnr: number
     87 var gdbbufname: string
     88 var varbufnr: number
     89 var varbufname: string
     90 var asmbufnr: number
     91 var asmbufname: string
     92 var promptbufnr: number
     93 # 'pty' refers to the "debugged-program" pty
     94 var ptybufnr: number
     95 var ptybufname: string
     96 var commbufnr: number
     97 var commbufname: string
     98 
     99 var gdbjob: job
    100 var gdb_channel: channel
    101 # These changes because they relate to windows
    102 var pid: number
    103 var gdbwin: number
    104 var varwin: number
    105 var asmwin: number
    106 var ptywin: number
    107 var sourcewin: number
    108 
    109 # Contains breakpoints that have been placed, key is a string with the GDB
    110 # breakpoint number.
    111 # Each entry is a dict, containing the sub-breakpoints.  Key is the subid.
    112 # For a breakpoint that is just a number the subid is zero.
    113 # For a breakpoint "123.4" the id is "123" and subid is "4".
    114 # Example, when breakpoint "44", "123", "123.1" and "123.2" exist:
    115 # {'44': {'0': entry}, '123': {'0': entry, '1': entry, '2': entry}}
    116 var breakpoints: dict<any>
    117 
    118 # Contains breakpoints by file/lnum.  The key is "fname:lnum".
    119 # Each entry is a list of breakpoint IDs at that position.
    120 var breakpoint_locations: dict<any>
    121 var BreakpointSigns: list<string>
    122 
    123 var evalFromBalloonExpr: bool
    124 var evalInPopup: bool
    125 var evalPopupId: number
    126 var evalExprResult: string
    127 var ignoreEvalError: bool
    128 var evalexpr: string
    129 # Remember the old value of 'signcolumn' for each buffer that it's set in, so
    130 # that we can restore the value for all buffers.
    131 var signcolumn_buflist: list<number>
    132 var saved_columns: number
    133 
    134 var allleft: bool
    135 # This was s:vertical but I cannot use vertical as variable name
    136 var vvertical: bool
    137 
    138 var winbar_winids: list<number>
    139 
    140 var saved_mousemodel: string
    141 
    142 var saved_K_map: dict<any>
    143 var saved_visual_K_map: dict<any>
    144 var saved_plus_map: dict<any>
    145 var saved_minus_map: dict<any>
    146 
    147 def InitScriptVariables()
    148   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'use_prompt')
    149     way = g:termdebug_config['use_prompt'] ? Way.Prompt : Way.Terminal
    150   elseif exists('g:termdebug_use_prompt')
    151     way = g:termdebug_use_prompt ? Way.Prompt : Way.Terminal
    152   elseif has('terminal') && !has('win32')
    153     way = Way.Terminal
    154   else
    155     way = Way.Prompt
    156   endif
    157   err = ''
    158 
    159   pc_id = 12
    160   asm_id = 13
    161   break_id = 14  # breakpoint number is added to this
    162   stopped = true
    163   running = false
    164 
    165   parsing_disasm_msg = 0
    166   asm_lines = []
    167   asm_addr = ''
    168 
    169   # They indicate the buffer numbers of the main buffers used
    170   gdbbufnr = 0
    171   gdbbufname = 'gdb'
    172   varbufnr = 0
    173   varbufname = 'Termdebug-variables-listing'
    174   asmbufnr = 0
    175   asmbufname = 'Termdebug-asm-listing'
    176   promptbufnr = 0
    177   # This is for the "debugged-program" thing
    178   ptybufname = "debugged-program"
    179   ptybufnr = 0
    180   commbufname = "gdb-communication"
    181   commbufnr = 0
    182 
    183   gdbjob = null_job
    184   gdb_channel = null_channel
    185   # These changes because they relate to windows
    186   pid = 0
    187   gdbwin = 0
    188   varwin = 0
    189   asmwin = 0
    190   ptywin = 0
    191   sourcewin = 0
    192 
    193   # Contains breakpoints that have been placed, key is a string with the GDB
    194   # breakpoint number.
    195   # Each entry is a dict, containing the sub-breakpoints.  Key is the subid.
    196   # For a breakpoint that is just a number the subid is zero.
    197   # For a breakpoint "123.4" the id is "123" and subid is "4".
    198   # Example, when breakpoint "44", "123", "123.1" and "123.2" exist:
    199   # {'44': {'0': entry}, '123': {'0': entry, '1': entry, '2': entry}}
    200   breakpoints = {}
    201 
    202   # Contains breakpoints by file/lnum.  The key is "fname:lnum".
    203   # Each entry is a list of breakpoint IDs at that position.
    204   breakpoint_locations = {}
    205   BreakpointSigns = []
    206 
    207   evalFromBalloonExpr = false
    208   evalInPopup = false
    209   evalPopupId = -1
    210   evalExprResult = ''
    211   ignoreEvalError = false
    212   evalexpr = ''
    213   # Remember the old value of 'signcolumn' for each buffer that it's set in, so
    214   # that we can restore the value for all buffers.
    215   signcolumn_buflist = [bufnr()]
    216   saved_columns = &columns
    217 
    218   winbar_winids = []
    219 
    220   saved_K_map = maparg('K', 'n', false, true)
    221   saved_plus_map = maparg('+', 'n', false, true)
    222   saved_minus_map = maparg('-', 'n', false, true)
    223   saved_visual_K_map = maparg('K', 'x', false, true)
    224 
    225   if has('menu')
    226     saved_mousemodel = &mousemodel
    227   endif
    228 enddef
    229 
    230 def SanityCheck(): bool
    231   var gdb_cmd = GetCommand()[0]
    232   var cwd = $'{getcwd()}/'
    233   if exists('+shellslash') && !&shellslash
    234     # on windows, need to handle backslash
    235     cwd->substitute('\\', '/', 'g')
    236   endif
    237   var is_check_ok = true
    238   # Need either the +terminal feature or +channel and the prompt buffer.
    239   # The terminal feature does not work with gdb on win32.
    240   if (way is Way.Prompt) && !has('channel')
    241     err = 'Cannot debug, +channel feature is not supported'
    242   elseif (way is Way.Prompt) && !exists('*prompt_setprompt')
    243     err = 'Cannot debug, missing prompt buffer support'
    244   elseif (way is Way.Prompt) && !empty(glob($'{cwd}{gdb_cmd}'))
    245     err = $"You have a file/folder named '{gdb_cmd}' in the current directory Termdebug may not work properly. Please exit and rename such a file/folder."
    246   elseif !empty(glob($'{cwd}{asmbufname}'))
    247     err = $"You have a file/folder named '{asmbufname}' in the current directory Termdebug may not work properly. Please exit and rename such a file/folder."
    248   elseif !empty(glob($'{cwd}{varbufname}'))
    249     err = $"You have a file/folder named '{varbufname}' in the current directory Termdebug may not work properly. Please exit and rename such a file/folder."
    250   elseif !executable(gdb_cmd)
    251     err = $"Cannot execute debugger program '{gdb_cmd}'"
    252   endif
    253 
    254   if !empty(err)
    255     Echoerr(err)
    256     is_check_ok = false
    257   endif
    258   return is_check_ok
    259 enddef
    260 
    261 def DeprecationWarnings()
    262   # TODO Remove the deprecated features after 1 Jan 2025.
    263   var config_param = ''
    264   if exists('g:termdebug_wide')
    265     config_param = 'g:termdebug_wide'
    266   elseif exists('g:termdebug_popup')
    267     config_param = 'g:termdebug_popup'
    268   elseif exists('g:termdebugger')
    269     config_param = 'g:termdebugger'
    270   elseif exists('g:termdebug_variables_window')
    271     config_param = 'g:termdebug_variables_window'
    272   elseif exists('g:termdebug_disasm_window')
    273     config_param = 'g:termdebug_disasm_window'
    274   elseif exists('g:termdebug_map_K')
    275     config_param = 'g:termdebug_map_K'
    276   elseif exists('g:termdebug_use_prompt')
    277     config_param = 'g:termdebug_use_prompt'
    278   endif
    279 
    280   if !empty(config_param)
    281     Echowarn($"Deprecation Warning: '{config_param}' parameter
    282           \ is deprecated and will be removed in the future. See ':h g:termdebug_config' for alternatives.")
    283   endif
    284 
    285   # termdebug config types
    286   if exists('g:termdebug_config') && !empty(g:termdebug_config)
    287     for key in keys(g:termdebug_config)
    288       if index(['disasm_window', 'variables_window', 'use_prompt', 'map_K', 'map_minus', 'map_plus'], key) != -1
    289         if typename(g:termdebug_config[key]) == 'number'
    290           var val = g:termdebug_config[key]
    291           Echowarn($"Deprecation Warning: 'g:termdebug_config[\"{key}\"] = {val}' will be deprecated.
    292                 \ Please use 'g:termdebug_config[\"{key}\"] = {val != 0}'" )
    293         endif
    294       endif
    295     endfor
    296   endif
    297 enddef
    298 
    299 # Take a breakpoint number as used by GDB and turn it into an integer.
    300 # The breakpoint may contain a dot: 123.4 -> 123004
    301 # The main breakpoint has a zero subid.
    302 def Breakpoint2SignNumber(id: number, subid: number): number
    303   return break_id + id * 1000 + subid
    304 enddef
    305 
    306 # Define or adjust the default highlighting, using background "new".
    307 # When the 'background' option is set then "old" has the old value.
    308 def Highlight(init: bool, old: string, new: string)
    309   var default = init ? 'default ' : ''
    310   if new ==# 'light' && old !=# 'light'
    311     exe $"hi {default}debugPC term=reverse ctermbg=lightblue guibg=lightblue"
    312   elseif new ==# 'dark' && old !=# 'dark'
    313     exe $"hi {default}debugPC term=reverse ctermbg=darkblue guibg=darkblue"
    314   endif
    315 enddef
    316 
    317 # Define the default highlighting, using the current 'background' value.
    318 def InitHighlight()
    319   Highlight(true, '', &background)
    320   hi default debugBreakpoint term=reverse ctermbg=red guibg=red
    321   hi default debugBreakpointDisabled term=reverse ctermbg=gray guibg=gray
    322 enddef
    323 
    324 # Setup an autocommand to redefine the default highlight when the colorscheme
    325 # is changed.
    326 def InitAutocmd()
    327   augroup TermDebug
    328     autocmd!
    329     autocmd ColorScheme * InitHighlight()
    330   augroup END
    331 enddef
    332 
    333 # Get the command to execute the debugger as a list, defaults to ["gdb"].
    334 def GetCommand(): list<string>
    335   var cmd: any
    336   if exists('g:termdebug_config')
    337     cmd = get(g:termdebug_config, 'command', 'gdb')
    338   elseif exists('g:termdebugger')
    339     cmd = g:termdebugger
    340   else
    341     cmd = 'gdb'
    342   endif
    343 
    344   return type(cmd) == v:t_list ? copy(cmd) : [cmd]
    345 enddef
    346 
    347 def StartDebug(bang: bool, ...gdb_args: list<string>)
    348   # First argument is the command to debug, second core file or process ID.
    349   StartDebug_internal({gdb_args: gdb_args, bang: bang})
    350 enddef
    351 
    352 def StartDebugCommand(bang: bool, ...args: list<string>)
    353   # First argument is the command to debug, rest are run arguments.
    354   StartDebug_internal({gdb_args: [args[0]], proc_args: args[1 : ], bang: bang})
    355 enddef
    356 
    357 def StartDebug_internal(dict: dict<any>)
    358   if g:termdebug_is_running
    359     Echoerr('Terminal debugger already running, cannot run two')
    360     return
    361   endif
    362 
    363   InitScriptVariables()
    364   if !SanityCheck()
    365     return
    366   endif
    367   DeprecationWarnings()
    368 
    369   if exists('#User#TermdebugStartPre')
    370     doauto <nomodeline> User TermdebugStartPre
    371   endif
    372 
    373   # Uncomment this line to write logging in "debuglog".
    374   # ch_logfile('debuglog', 'w')
    375 
    376   # Assume current window is the source code window
    377   sourcewin = win_getid()
    378   var wide = 0
    379 
    380   if exists('g:termdebug_config')
    381     wide = get(g:termdebug_config, 'wide', 0)
    382   elseif exists('g:termdebug_wide')
    383     wide = g:termdebug_wide
    384   endif
    385   if wide > 0
    386     if &columns < wide
    387       &columns = wide
    388       # If we make the Vim window wider, use the whole left half for the debug
    389       # windows.
    390       allleft = true
    391     endif
    392     vvertical = true
    393   else
    394     vvertical = false
    395   endif
    396 
    397   if way is Way.Prompt
    398     StartDebug_prompt(dict)
    399   else
    400     StartDebug_term(dict)
    401   endif
    402 
    403   if GetDisasmWindow()
    404     var curwinid = win_getid()
    405     GotoAsmwinOrCreateIt()
    406     win_gotoid(curwinid)
    407   endif
    408 
    409   if GetVariablesWindow()
    410     var curwinid = win_getid()
    411     GotoVariableswinOrCreateIt()
    412     win_gotoid(curwinid)
    413   endif
    414 
    415   if exists('#User#TermdebugStartPost')
    416     doauto <nomodeline> User TermdebugStartPost
    417   endif
    418   g:termdebug_is_running = true
    419 enddef
    420 
    421 # Use when debugger didn't start or ended.
    422 def CloseBuffers()
    423   var buf_numbers = [promptbufnr, ptybufnr, commbufnr, asmbufnr, varbufnr]
    424   for buf_nr in buf_numbers
    425     if buf_nr > 0 && bufexists(buf_nr)
    426       exe $'bwipe! {buf_nr}'
    427     endif
    428   endfor
    429 enddef
    430 
    431 def IsGdbStarted(): bool
    432   var gdbproc_status = job_status(term_getjob(gdbbufnr))
    433   if gdbproc_status !=# 'run'
    434     return false
    435   endif
    436   return true
    437 enddef
    438 
    439 # Check if the debugger is running remotely and return a suitable command to pty remotely
    440 def GetRemotePtyCmd(gdb_cmd: list<string>): list<string>
    441   # Check if the user provided a command to launch the program window
    442   var term_cmd = null_list
    443   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'remote_window')
    444     term_cmd = g:termdebug_config['remote_window']
    445     term_cmd = type(term_cmd) == v:t_list ? copy(term_cmd) : [term_cmd]
    446   else
    447     # Check if it is a remote gdb, the program terminal should be started
    448     # on the remote machine.
    449     const remote_pattern = '^\(ssh\|wsl\)'
    450     if gdb_cmd[0] =~? remote_pattern
    451       var gdb_pos = indexof(gdb_cmd, $'v:val =~? "^{GetCommand()[-1]}"')
    452       if gdb_pos > 0
    453         # strip debugger call
    454         term_cmd = gdb_cmd[0 : gdb_pos - 1]
    455         # roundtrip to check if socat is available on the remote side
    456         silent call system(join(term_cmd, ' ') .. ' socat -h')
    457         if v:shell_error != 0
    458           Echowarn('Install socat on the remote machine for a program window better experience')
    459         else
    460           # create a devoted tty slave device and link to stdin/stdout
    461           term_cmd += ['socat', '-dd', '-', 'PTY,raw,echo=0']
    462           ch_log($'launching remote ttys using "{join(term_cmd)}"')
    463         endif
    464       endif
    465     endif
    466   endif
    467   return term_cmd
    468 enddef
    469 
    470 # Retrieve the remote pty device from a remote terminal
    471 # If interact is true, use remote tty command to get the pty device
    472 def GetRemotePtyDev(bufnr: number, interact: bool): string
    473   var pty: string = null_string
    474   var line = null_string
    475 
    476   for _ in range(5)
    477 
    478     if interact
    479       term_sendkeys(bufnr, "tty\<CR>")
    480     endif
    481 
    482     for i in range(0, term_getsize(bufnr)[0])
    483       line = term_getline(bufnr, i)
    484       if line =~? "/dev/pts"
    485           pty = line
    486           break
    487       endif
    488       term_wait(bufnr, 100)
    489     endfor # i
    490 
    491     if pty != null_string
    492       # Clear the terminal window
    493       if interact
    494         term_sendkeys(bufnr, "clear\<CR>")
    495       endif
    496       break
    497     endif
    498 
    499   endfor # j
    500 
    501   return pty
    502 enddef
    503 
    504 def CreateProgramPty(cmd: list<string> = null_list): string
    505   ptybufnr = term_start(!cmd ? 'NONE' : cmd, {
    506     term_name: ptybufname,
    507     vertical: vvertical})
    508   if ptybufnr == 0
    509     return null_string
    510   endif
    511   ptywin = win_getid()
    512 
    513   if vvertical
    514     # Assuming the source code window will get a signcolumn, use two more
    515     # columns for that, thus one less for the terminal window.
    516     exe $":{(&columns / 2 - 1)}wincmd |"
    517     if allleft
    518       # use the whole left column
    519       wincmd H
    520     endif
    521   endif
    522 
    523   if !cmd
    524     return job_info(term_getjob(ptybufnr))['tty_out']
    525   else
    526     var interact = indexof(cmd, 'v:val =~? "^socat"') < 0
    527     var pty = GetRemotePtyDev(ptybufnr, interact)
    528 
    529     if pty !~? "/dev/pts"
    530       Echoerr('Failed to get the program window tty')
    531       exe $'bwipe! {ptybufnr}'
    532       pty = null_string
    533     elseif pty !~? "^/dev/pts"
    534       # remove the prompt
    535       pty = pty->matchstr('/dev/pts/\d\+')
    536     endif
    537 
    538     return pty
    539   endif
    540 enddef
    541 
    542 def CreateCommunicationPty(cmd: list<string> = null_list): string
    543   # Create a hidden terminal window to communicate with gdb
    544   var options: dict<any> = { term_name: commbufname, out_cb: CommOutput, hidden: 1 }
    545 
    546   if !cmd
    547     commbufnr = term_start('NONE', options)
    548   else
    549     # avoid message wrapping that prevents proper parsing
    550     options['term_cols'] = 500
    551     commbufnr = term_start(cmd, options)
    552   endif
    553 
    554   if commbufnr == 0
    555     return null_string
    556   endif
    557 
    558   if !cmd
    559     return job_info(term_getjob(commbufnr))['tty_out']
    560   else
    561     # CommunicationPty only will be reliable with socat
    562     if indexof(cmd, 'v:val =~? "^socat"') < 0
    563       Echoerr('Communication window should be started with socat')
    564       exe $'bwipe! {commbufnr}'
    565       return null_string
    566     endif
    567 
    568     var pty = GetRemotePtyDev(commbufnr, false)
    569 
    570     if pty !~? "/dev/pts"
    571       Echoerr('Failed to get the communication window tty')
    572       exe $'bwipe! {commbufnr}'
    573       pty = null_string
    574     elseif pty !~? "^/dev/pts"
    575       # remove the prompt
    576       pty = pty->matchstr('/dev/pts/\d\+')
    577     endif
    578 
    579     return pty
    580   endif
    581 enddef
    582 
    583 # Convenient filter to workaround remote escaping issues.
    584 # For example, ssh doesn't escape spaces for the gdb arguments.
    585 # Workaround doing:
    586 # let g:termdebug_config['command_filter'] = function('g:Termdebug_escape_whitespace')
    587 def g:Termdebug_escape_whitespace(args: list<string>): list<string>
    588   var new_args: list<string> = []
    589   for arg in args
    590     new_args += [substitute(arg, ' ', '\\ ', 'g')]
    591   endfor
    592   return new_args
    593 enddef
    594 
    595 def CreateGdbConsole(dict: dict<any>, pty: string, commpty: string): string
    596   # Start the gdb buffer
    597   var gdb_args = get(dict, 'gdb_args', [])
    598   var proc_args = get(dict, 'proc_args', [])
    599 
    600   var gdb_cmd = GetCommand()
    601 
    602   gdbbufname = gdb_cmd[0]
    603 
    604   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'command_add_args')
    605     gdb_cmd = g:termdebug_config.command_add_args(gdb_cmd, pty)
    606   else
    607     # Add -quiet to avoid the intro message causing a hit-enter prompt.
    608     gdb_cmd += ['-quiet']
    609     # Disable pagination, it causes everything to stop at the gdb
    610     gdb_cmd += ['-iex', 'set pagination off']
    611     # Interpret commands while the target is running.  This should usually only
    612     # be exec-interrupt, since many commands don't work properly while the
    613     # target is running (so execute during startup).
    614     gdb_cmd += ['-iex', 'set mi-async on']
    615     # Open a terminal window to run the debugger.
    616     gdb_cmd += ['-tty', pty]
    617     # Command executed _after_ startup is done, provides us with the necessary
    618     # feedback
    619     gdb_cmd += ['-ex', 'echo startupdone\n']
    620   endif
    621 
    622   # Escape whitespaces in the gdb arguments for ssh remoting
    623   if exists('g:termdebug_config') && !has_key(g:termdebug_config, 'command_filter') &&
    624       gdb_cmd[0] =~? '^ssh'
    625     g:termdebug_config['command_filter'] = function('g:Termdebug_escape_whitespace')
    626   endif
    627 
    628   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'command_filter')
    629     gdb_cmd = g:termdebug_config.command_filter(gdb_cmd)
    630   endif
    631 
    632   # Adding arguments requested by the user
    633   gdb_cmd += gdb_args
    634 
    635   ch_log($'executing "{join(gdb_cmd)}"')
    636   gdbbufnr = term_start(gdb_cmd, {
    637     term_name: gdbbufname,
    638     term_finish: 'close',
    639   })
    640   if gdbbufnr == 0
    641     return 'Failed to open the gdb terminal window'
    642   endif
    643   gdbwin = win_getid()
    644 
    645   # Wait for the "startupdone" message before sending any commands.
    646   var counter = 0
    647   var counter_max = 300
    648   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'timeout')
    649     counter_max = g:termdebug_config['timeout']
    650   endif
    651 
    652   var success = false
    653   while !success && counter < counter_max
    654     if !IsGdbStarted()
    655       return $'{gdbbufname} exited unexpectedly'
    656     endif
    657 
    658     for lnum in range(1, 200)
    659       if term_getline(gdbbufnr, lnum) =~ 'startupdone'
    660         success = true
    661       endif
    662     endfor
    663 
    664     # Each count is 10ms
    665     counter += 1
    666     sleep 10m
    667   endwhile
    668 
    669   if !success
    670     return 'Failed to startup the gdb program.'
    671   endif
    672 
    673   # ---- gdb started. Next, let's set the MI interface. ---
    674   # Set arguments to be run.
    675   if !empty(proc_args)
    676     term_sendkeys(gdbbufnr, $"server set args {join(proc_args)}\r")
    677   endif
    678 
    679   # Connect gdb to the communication pty, using the GDB/MI interface.
    680   # Prefix "server" to avoid adding this to the history.
    681   term_sendkeys(gdbbufnr, $"server new-ui mi {commpty}\r")
    682 
    683   # Wait for the response to show up, users may not notice the error and wonder
    684   # why the debugger doesn't work.
    685   counter = 0
    686   counter_max = 300
    687   success = false
    688   while !success && counter < counter_max
    689     if !IsGdbStarted()
    690       return $'{gdbbufname} exited unexpectedly'
    691     endif
    692 
    693     var response = ''
    694     for lnum in range(1, 200)
    695       var line1 = term_getline(gdbbufnr, lnum)
    696       var line2 = term_getline(gdbbufnr, lnum + 1)
    697       if line1 =~ 'new-ui mi '
    698         # response can be in the same line or the next line
    699         response = $"{line1}{line2}"
    700         if response =~ 'Undefined command'
    701           # CHECKME: possibly send a "server show version" here
    702           return 'Sorry, your gdb is too old, gdb 7.12 is required'
    703         endif
    704         if response =~ 'New UI allocated'
    705           # Success!
    706           success = true
    707         endif
    708       elseif line1 =~ 'Reading symbols from' && line2 !~ 'new-ui mi '
    709         # Reading symbols might take a while, try more times
    710         counter -= 1
    711       endif
    712     endfor
    713     if response =~ 'New UI allocated'
    714       break
    715     endif
    716     counter += 1
    717     sleep 10m
    718   endwhile
    719 
    720   if !success
    721     return 'Cannot check if your gdb works, continuing anyway'
    722   endif
    723   return ''
    724 enddef
    725 
    726 
    727 # Open a terminal window without a job, to run the debugged program in.
    728 def StartDebug_term(dict: dict<any>)
    729 
    730   # Retrieve command if remote pty is needed
    731   var gdb_cmd = GetCommand()
    732   var term_cmd = GetRemotePtyCmd(gdb_cmd)
    733 
    734   var programpty = CreateProgramPty(term_cmd)
    735   if programpty is null_string
    736     Echoerr('Failed to open the program terminal window')
    737     CloseBuffers()
    738     return
    739   endif
    740 
    741   var commpty = CreateCommunicationPty(term_cmd)
    742   if commpty is null_string
    743     Echoerr('Failed to open the communication terminal window')
    744     CloseBuffers()
    745     return
    746   endif
    747 
    748   var err_message = CreateGdbConsole(dict, programpty, commpty)
    749   if !empty(err_message)
    750     Echoerr(err_message)
    751     CloseBuffers()
    752     return
    753   endif
    754 
    755   job_setoptions(term_getjob(gdbbufnr), {exit_cb: EndDebug})
    756 
    757   # Set the filetype, this can be used to add mappings.
    758   set filetype=termdebug
    759 
    760   StartDebugCommon(dict)
    761 enddef
    762 
    763 # Open a window with a prompt buffer to run gdb in.
    764 def StartDebug_prompt(dict: dict<any>)
    765   var gdb_cmd = GetCommand()
    766   gdbbufname = gdb_cmd[0]
    767 
    768   if vvertical
    769     vertical new
    770   else
    771     new
    772   endif
    773   gdbwin = win_getid()
    774   promptbufnr = bufnr('')
    775   prompt_setprompt(promptbufnr, 'gdb> ')
    776   set buftype=prompt
    777   exe $"file {gdbbufname}"
    778 
    779   prompt_setcallback(promptbufnr, PromptCallback)
    780   prompt_setinterrupt(promptbufnr, PromptInterrupt)
    781 
    782   if vvertical
    783     # Assuming the source code window will get a signcolumn, use two more
    784     # columns for that, thus one less for the terminal window.
    785     exe $":{(&columns / 2 - 1)}wincmd |"
    786   endif
    787 
    788   var gdb_args = get(dict, 'gdb_args', [])
    789   var proc_args = get(dict, 'proc_args', [])
    790 
    791   # directly communicate via mi2. This option must precede any -iex options for proper
    792   # interpretation.
    793   gdb_cmd += ['--interpreter=mi2']
    794   # Disable pagination, it causes everything to stop at the gdb, needs to be run early
    795   gdb_cmd += ['-iex', 'set pagination off']
    796   # Interpret commands while the target is running.  This should usually only
    797   # be exec-interrupt, since many commands don't work properly while the
    798   # target is running (so execute during startup).
    799   gdb_cmd += ['-iex', 'set mi-async on']
    800   # Add -quiet to avoid the intro message causing a hit-enter prompt.
    801   gdb_cmd += ['-quiet']
    802 
    803   # Escape whitespaces in the gdb arguments for ssh remoting
    804   if exists('g:termdebug_config') && !has_key(g:termdebug_config, 'command_filter') &&
    805       gdb_cmd[0] =~? '^ssh'
    806     g:termdebug_config['command_filter'] = function('g:Termdebug_escape_whitespace')
    807   endif
    808 
    809   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'command_filter')
    810     gdb_cmd = g:termdebug_config.command_filter(gdb_cmd)
    811   endif
    812 
    813   # Adding arguments requested by the user
    814   gdb_cmd += gdb_args
    815 
    816   ch_log($'executing "{join(gdb_cmd)}"')
    817   gdbjob = job_start(gdb_cmd, {
    818     exit_cb: EndDebug,
    819     out_cb: GdbOutCallback
    820   })
    821   if job_status(gdbjob) != "run"
    822     Echoerr('Failed to start gdb')
    823     exe $'bwipe! {promptbufnr}'
    824     return
    825   endif
    826   exe $'au BufUnload <buffer={promptbufnr}> ++once ' ..
    827     'call job_stop(gdbjob, ''kill'')'
    828   # Mark the buffer modified so that it's not easy to close.
    829   set modified
    830   gdb_channel = job_getchannel(gdbjob)
    831 
    832   # Retrieve command if remote pty is needed
    833   var term_cmd = GetRemotePtyCmd(gdb_cmd)
    834 
    835   # If we are not using socat maybe is a shell:
    836   var interact = indexof(term_cmd, 'v:val =~? "^socat"') < 0
    837 
    838   if has('terminal') && (term_cmd != null || !has('win32'))
    839 
    840     # Try open terminal twice because sync with gdbjob may not succeed
    841     # the first time (docker daemon for example)
    842     var trials: number = 2
    843     var pty: string = null_string
    844 
    845     while trials > 0
    846 
    847       # Run the debugged program in a window.  Open it below the
    848       # gdb window.
    849       belowright ptybufnr = term_start(
    850         term_cmd != null ? term_cmd : 'NONE', {
    851         term_name: 'debugged program',
    852         vertical: vvertical
    853       })
    854 
    855       if ptybufnr == 0
    856         Echoerr('Failed to open the program terminal window')
    857         job_stop(gdbjob)
    858         return
    859       endif
    860 
    861       ptywin = win_getid()
    862 
    863       if term_cmd is null
    864         pty = job_info(term_getjob(ptybufnr))['tty_out']
    865       else
    866         # Retrieve remote pty value
    867         pty = GetRemotePtyDev(ptybufnr, interact)
    868       endif
    869 
    870       if pty !~? "/dev/pts"
    871         exe $'bwipe! {ptybufnr}'
    872         --trials
    873         pty = null_string
    874       else
    875         break
    876       endif
    877     endwhile
    878 
    879     if pty !~? "/dev/pts"
    880       Echoerr('Failed to get the program windows tty')
    881       job_stop(gdbjob)
    882     elseif pty !~? "^/dev/pts"
    883       # remove the prompt
    884       pty = pty->matchstr('/dev/pts/\d\+')
    885     endif
    886 
    887     SendCommand($'tty {pty}')
    888 
    889     # Since GDB runs in a prompt window, the environment has not been set to
    890     # match a terminal window, need to do that now.
    891     SendCommand('set env TERM = xterm-color')
    892     SendCommand($'set env ROWS = {winheight(ptywin)}')
    893     SendCommand($'set env LINES = {winheight(ptywin)}')
    894     SendCommand($'set env COLUMNS = {winwidth(ptywin)}')
    895     SendCommand($'set env COLORS = {&t_Co}')
    896     SendCommand($'set env VIM_TERMINAL = {v:version}')
    897   elseif has('win32')
    898     # MS-Windows: run in a new console window for maximum compatibility
    899     SendCommand('set new-console on')
    900   else
    901     # TODO: open a new terminal, get the tty name, pass on to gdb
    902     SendCommand('show inferior-tty')
    903   endif
    904   SendCommand('set print pretty on')
    905   SendCommand('set breakpoint pending on')
    906 
    907   # Set arguments to be run
    908   if !empty(proc_args)
    909     SendCommand($'set args {join(proc_args)}')
    910   endif
    911 
    912   StartDebugCommon(dict)
    913   startinsert
    914 enddef
    915 
    916 def StartDebugCommon(dict: dict<any>)
    917   # Sign used to highlight the line where the program has stopped.
    918   # There can be only one.
    919   sign_define('debugPC', {linehl: 'debugPC'})
    920 
    921   # Install debugger commands in the text window.
    922   win_gotoid(sourcewin)
    923   InstallCommands()
    924   win_gotoid(gdbwin)
    925 
    926   # Enable showing a balloon with eval info
    927   if has("balloon_eval") || has("balloon_eval_term")
    928     set balloonexpr=TermDebugBalloonExpr()
    929     if has("balloon_eval")
    930       set ballooneval
    931     endif
    932     if has("balloon_eval_term")
    933       set balloonevalterm
    934     endif
    935   endif
    936 
    937   augroup TermDebug
    938     au BufRead * BufRead()
    939     au BufUnload * BufUnloaded()
    940     au OptionSet background Highlight(0, v:option_old, v:option_new)
    941   augroup END
    942 
    943   # Run the command if the bang attribute was given and got to the debug
    944   # window.
    945   if get(dict, 'bang', 0)
    946     SendResumingCommand('-exec-run')
    947     win_gotoid(ptywin)
    948   endif
    949 enddef
    950 
    951 # Send a command to gdb.  "cmd" is the string without line terminator.
    952 def SendCommand(cmd: string)
    953   ch_log($'sending to gdb: {cmd}')
    954   if way is Way.Prompt
    955     ch_sendraw(gdb_channel, $"{cmd}\n")
    956   else
    957     term_sendkeys(commbufnr, $"{cmd}\r")
    958   endif
    959 enddef
    960 
    961 # Interrupt or stop the program
    962 def StopCommand()
    963   if way is Way.Prompt
    964     PromptInterrupt()
    965   else
    966     SendCommand('-exec-interrupt')
    967   endif
    968 enddef
    969 
    970 # Continue the program
    971 def ContinueCommand()
    972   if way is Way.Prompt
    973     SendCommand('continue')
    974   else
    975     # using -exec-continue results in CTRL-C in the gdb window not working,
    976     # communicating via commbuf (= use of SendCommand) has the same result
    977     SendCommand('-exec-continue')
    978     # command Continue  term_sendkeys(gdbbuf, "continue\r")
    979   endif
    980 enddef
    981 
    982 # This is global so that a user can create their mappings with this.
    983 def g:TermDebugSendCommand(cmd: string)
    984   if way is Way.Prompt
    985     ch_sendraw(gdb_channel, $"{cmd}\n")
    986   else
    987     var do_continue = false
    988     if !stopped
    989       do_continue = true
    990       StopCommand()
    991       sleep 10m
    992     endif
    993     # TODO: should we prepend CTRL-U to clear the command?
    994     term_sendkeys(gdbbufnr, $"{cmd}\r")
    995     if do_continue
    996       ContinueCommand()
    997     endif
    998   endif
    999 enddef
   1000 
   1001 # Send a command that resumes the program.  If the program isn't stopped the
   1002 # command is not sent (to avoid a repeated command to cause trouble).
   1003 # If the command is sent then reset stopped.
   1004 def SendResumingCommand(cmd: string)
   1005   if stopped
   1006     # reset stopped here, it may take a bit of time before we get a response
   1007     stopped = false
   1008     ch_log('assume that program is running after this command')
   1009     SendCommand(cmd)
   1010   else
   1011     ch_log($'dropping command, program is running: {cmd}')
   1012   endif
   1013 enddef
   1014 
   1015 # Function called when entering a line in the prompt buffer.
   1016 def PromptCallback(text: string)
   1017   SendCommand(text)
   1018 enddef
   1019 
   1020 # Function called when pressing CTRL-C in the prompt buffer and when placing a
   1021 # breakpoint.
   1022 def PromptInterrupt()
   1023   ch_log('Interrupting gdb')
   1024   if has('win32')
   1025     # Using job_stop() does not work on MS-Windows, need to send SIGTRAP to
   1026     # the debugger program so that gdb responds again.
   1027     if pid == 0
   1028       Echoerr('Cannot interrupt gdb, did not find a process ID')
   1029     else
   1030       debugbreak(pid)
   1031     endif
   1032   else
   1033     job_stop(gdbjob, 'int')
   1034   endif
   1035 enddef
   1036 
   1037 # Function called when gdb outputs text.
   1038 def GdbOutCallback(channel: channel, text: string)
   1039   ch_log($'received from gdb: {text}')
   1040 
   1041   # Disassembly messages need to be forwarded as-is.
   1042   if parsing_disasm_msg > 0
   1043     CommOutput(channel, text)
   1044     return
   1045   endif
   1046 
   1047   # Drop the gdb prompt, we have our own.
   1048   # Drop status and echo'd commands.
   1049   if text == '(gdb) ' || text == '^done' ||
   1050       (text[0] == '&' && text !~ '^&"disassemble')
   1051     return
   1052   endif
   1053 
   1054   var decoded_text = ''
   1055   if text =~ '^\^error,msg='
   1056     decoded_text = DecodeMessage(text[11 : ], false)
   1057     if !empty(evalexpr) && decoded_text =~ 'A syntax error in expression, near\|No symbol .* in current context'
   1058       # Silently drop evaluation errors.
   1059       evalexpr = ''
   1060       return
   1061     endif
   1062   elseif text[0] == '~'
   1063     decoded_text = DecodeMessage(text[1 : ], false)
   1064   else
   1065     CommOutput(channel, text)
   1066     return
   1067   endif
   1068 
   1069   var curwinid = win_getid()
   1070   win_gotoid(gdbwin)
   1071 
   1072   # Add the output above the current prompt.
   1073   append(line('$') - 1, decoded_text)
   1074   set modified
   1075 
   1076   win_gotoid(curwinid)
   1077 enddef
   1078 
   1079 # Decode a message from gdb.  "quotedText" starts with a ", return the text up
   1080 # to the next unescaped ", unescaping characters:
   1081 # - remove line breaks (unless "literal" is true)
   1082 # - change \" to "
   1083 # - change \\t to \t (unless "literal" is true)
   1084 # - change \0xhh to \xhh (disabled for now)
   1085 # - change \ooo to octal
   1086 # - change \\ to \
   1087 def DecodeMessage(quotedText: string, literal: bool): string
   1088   if quotedText[0] != '"'
   1089     Echoerr($'DecodeMessage(): missing quote in {quotedText}')
   1090     return ''
   1091   endif
   1092   var msg = quotedText
   1093     ->substitute('^"\|[^\\]\zs".*', '', 'g')
   1094     ->substitute('\\"', '"', 'g')
   1095     #\ multi-byte characters arrive in octal form
   1096     #\ NULL-values must be kept encoded as those break the string otherwise
   1097     ->substitute('\\000', NullRepl, 'g')
   1098     ->substitute('\\\(\o\o\o\)', (m) => nr2char(str2nr(m[1], 8)), 'g')
   1099     # You could also  use ->substitute('\\\\\(\o\o\o\)', '\=nr2char(str2nr(submatch(1), 8))', "g")
   1100     #\ Note: GDB docs also mention hex encodings - the translations below work
   1101     #\       but we keep them out for performance-reasons until we actually see
   1102     #\       those in mi-returns
   1103     ->substitute('\\\\', '\', 'g')
   1104     ->substitute(NullRepl, '\\000', 'g')
   1105   if !literal
   1106     return msg
   1107       ->substitute('\\t', "\t", 'g')
   1108       ->substitute('\\n', '', 'g')
   1109   else
   1110     return msg
   1111   endif
   1112 enddef
   1113 const NullRepl = 'XXXNULLXXX'
   1114 
   1115 # Extract the "name" value from a gdb message with fullname="name".
   1116 def GetLocalFullname(msg: string): string
   1117   if msg !~ 'fullname'
   1118     return ''
   1119   endif
   1120 
   1121   var name = DecodeMessage(substitute(msg, '.*fullname=', '', ''), true)
   1122   if has('win32') && name =~ ':\\\\'
   1123     # sometimes the name arrives double-escaped
   1124     name = substitute(name, '\\\\', '\\', 'g')
   1125   endif
   1126 
   1127   return name
   1128 enddef
   1129 
   1130 # Turn a remote machine local path into a remote one.
   1131 def Local2RemotePath(path: string): string
   1132   # If no mappings are provided keep the path.
   1133   if !exists('g:termdebug_config') || !has_key(g:termdebug_config, 'substitute_path')
   1134     return path
   1135   endif
   1136 
   1137   var mappings: list<any> = items(g:termdebug_config['substitute_path'])
   1138 
   1139   # Try to match the longest local path first.
   1140   sort(mappings, (a, b) => len(b[0]) - len(a[0]))
   1141 
   1142   for [local, remote] in mappings
   1143     const pattern = '^' .. escape(local, '\.*~()')
   1144     if path =~ pattern
   1145       return substitute(path, pattern, escape(remote, '\.*~()'), '')
   1146     endif
   1147   endfor
   1148 
   1149   return path
   1150 enddef
   1151 
   1152 # Turn a remote path into a local one to the remote machine.
   1153 def Remote2LocalPath(path: string): string
   1154   # If no mappings are provided keep the path.
   1155   if !exists('g:termdebug_config') || !has_key(g:termdebug_config, 'substitute_path')
   1156     return path
   1157   endif
   1158 
   1159   var mappings: list<any> = items(g:termdebug_config['substitute_path'])
   1160 
   1161   # Try to match the longest remote path first.
   1162   sort(mappings, (a, b) => len(b[1]) - len(a[1]))
   1163 
   1164   for [local, remote] in mappings
   1165     const pattern = '^' .. escape(substitute(remote, '[\/]', '[\\/]', 'g'), '.*~()')
   1166     if path =~ pattern
   1167       return substitute(path, pattern, local, '')
   1168     endif
   1169   endfor
   1170 
   1171   return path
   1172 enddef
   1173 
   1174 # Extract the "addr" value from a gdb message with addr="0x0001234".
   1175 def GetAsmAddr(msg: string): string
   1176   if msg !~ 'addr='
   1177     return ''
   1178   endif
   1179 
   1180   var addr = DecodeMessage(substitute(msg, '.*addr=', '', ''), false)
   1181   return addr
   1182 enddef
   1183 
   1184 def EndDebug(job: any, status: any)
   1185   if exists('#User#TermdebugStopPre')
   1186     doauto <nomodeline> User TermdebugStopPre
   1187   endif
   1188 
   1189   if way is Way.Prompt
   1190     ch_log("Returning from EndDebug()")
   1191   endif
   1192 
   1193   var curwinid = win_getid()
   1194   CloseBuffers()
   1195 
   1196   # Restore 'signcolumn' in all buffers for which it was set.
   1197   win_gotoid(sourcewin)
   1198   var was_buf = bufnr()
   1199   for bufnr in signcolumn_buflist
   1200     if bufexists(bufnr)
   1201       exe $":{bufnr}buf"
   1202       if exists('b:save_signcolumn')
   1203         &signcolumn = b:save_signcolumn
   1204         unlet b:save_signcolumn
   1205       endif
   1206     endif
   1207   endfor
   1208   if bufexists(was_buf)
   1209     exe $":{was_buf}buf"
   1210   endif
   1211 
   1212   DeleteCommands()
   1213 
   1214   win_gotoid(curwinid)
   1215 
   1216   &columns = saved_columns
   1217 
   1218   if has("balloon_eval") || has("balloon_eval_term")
   1219     set balloonexpr=
   1220     if has("balloon_eval")
   1221       set noballooneval
   1222     endif
   1223     if has("balloon_eval_term")
   1224       set noballoonevalterm
   1225     endif
   1226   endif
   1227 
   1228   if exists('#User#TermdebugStopPost')
   1229     doauto <nomodeline> User TermdebugStopPost
   1230   endif
   1231 
   1232   au! TermDebug
   1233   g:termdebug_is_running = false
   1234 enddef
   1235 
   1236 # Disassembly window - added by Michael Sartain
   1237 #
   1238 # - CommOutput: &"disassemble $pc\n"
   1239 # - CommOutput: ~"Dump of assembler code for function main(int, char**):\n"
   1240 # - CommOutput: ~"   0x0000555556466f69 <+0>:\tpush   rbp\n"
   1241 # ...
   1242 # - CommOutput: ~"   0x0000555556467cd0:\tpop    rbp\n"
   1243 # - CommOutput: ~"   0x0000555556467cd1:\tret    \n"
   1244 # - CommOutput: ~"End of assembler dump.\n"
   1245 # - CommOutput: ^done
   1246 
   1247 # - CommOutput: &"disassemble $pc\n"
   1248 # - CommOutput: &"No function contains specified address.\n"
   1249 # - CommOutput: ^error,msg="No function contains specified address."
   1250 def HandleDisasmMsg(msg: string)
   1251   if msg =~ '^\^done'
   1252     var curwinid = win_getid()
   1253     if win_gotoid(asmwin)
   1254       silent! :%delete _
   1255       setline(1, asm_lines)
   1256       set nomodified
   1257       set filetype=asm
   1258 
   1259       var lnum = search($'^{asm_addr}')
   1260       if lnum != 0
   1261         sign_unplace('TermDebug', {id: asm_id})
   1262         sign_place(asm_id, 'TermDebug', 'debugPC', '%', {lnum: lnum})
   1263       endif
   1264 
   1265       win_gotoid(curwinid)
   1266     endif
   1267 
   1268     parsing_disasm_msg = 0
   1269     asm_lines = []
   1270 
   1271   elseif msg =~ '^\^error,msg='
   1272     if parsing_disasm_msg == 1
   1273       # Disassemble call ran into an error. This can happen when gdb can't
   1274       # find the function frame address, so let's try to disassemble starting
   1275       # at current PC
   1276       SendCommand('disassemble $pc,+100')
   1277     endif
   1278     parsing_disasm_msg = 0
   1279   elseif msg =~ '^&"disassemble \$pc'
   1280     if msg =~ '+100'
   1281       # This is our second disasm attempt
   1282       parsing_disasm_msg = 2
   1283     endif
   1284   elseif msg !~ '^&"disassemble'
   1285     var value = substitute(msg, '^\~\"[ ]*', '', '')
   1286       ->substitute('^=>[ ]*', '', '')
   1287       ->substitute('\\n\"\r$', '', '')
   1288       ->substitute('\\n\"$', '', '')
   1289       ->substitute('\r', '', '')
   1290       ->substitute('\\t', ' ', 'g')
   1291 
   1292     if value != '' || !empty(asm_lines)
   1293       add(asm_lines, value)
   1294     endif
   1295   endif
   1296 enddef
   1297 
   1298 
   1299 def ParseVarinfo(varinfo: string): dict<any>
   1300   var dict = {}
   1301   var nameIdx = matchstrpos(varinfo, '{name="\([^"]*\)"')
   1302   dict['name'] = varinfo[nameIdx[1] + 7 : nameIdx[2] - 2]
   1303   var typeIdx = matchstrpos(varinfo, ',type="\([^"]*\)"')
   1304   # 'type' maybe is a url-like string,
   1305   # try to shorten it and show only the /tail
   1306   dict['type'] = (varinfo[typeIdx[1] + 7 : typeIdx[2] - 2])->fnamemodify(':t')
   1307   var valueIdx = matchstrpos(varinfo, ',value="\(.*\)"}')
   1308   if valueIdx[1] == -1
   1309     dict['value'] = 'Complex value'
   1310   else
   1311     dict['value'] = varinfo[valueIdx[1] + 8 : valueIdx[2] - 3]
   1312   endif
   1313   return dict
   1314 enddef
   1315 
   1316 def HandleVariablesMsg(msg: string)
   1317   var curwinid = win_getid()
   1318   if win_gotoid(varwin)
   1319     silent! :%delete _
   1320     var spaces = repeat(' ', 16)
   1321     setline(1, $'Type{spaces}Name{spaces}Value')
   1322     var cnt = 1
   1323     var capture = '{name=".\{-}",\%(arg=".\{-}",\)\{0,1\}type=".\{-}"\%(,value=".\{-}"\)\{0,1\}}'
   1324     var varinfo = matchstr(msg, capture, 0, cnt)
   1325 
   1326     while varinfo != ''
   1327       var vardict = ParseVarinfo(varinfo)
   1328       setline(cnt + 1, vardict['type'] ..
   1329         repeat(' ', max([20 - len(vardict['type']), 1])) ..
   1330         vardict['name'] ..
   1331         repeat(' ', max([20 - len(vardict['name']), 1])) ..
   1332         vardict['value'])
   1333       cnt += 1
   1334       varinfo = matchstr(msg, capture, 0, cnt)
   1335     endwhile
   1336   endif
   1337   win_gotoid(curwinid)
   1338 enddef
   1339 
   1340 
   1341 # Handle a message received from gdb on the GDB/MI interface.
   1342 def CommOutput(chan: channel, message: string)
   1343   # We may use the standard MI message formats? See #10300 on github that mentions
   1344   # the following links:
   1345   # https://sourceware.org/gdb/current/onlinedocs/gdb.html/GDB_002fMI-Input-Syntax.html#GDB_002fMI-Input-Syntax
   1346   # https://sourceware.org/gdb/current/onlinedocs/gdb.html/GDB_002fMI-Output-Syntax.html#GDB_002fMI-Output-Syntax
   1347 
   1348   var msgs = split(message, "\r")
   1349 
   1350   var msg = ''
   1351   for received_msg in msgs
   1352     # remove prefixed NL
   1353     if received_msg[0] == "\n"
   1354       msg = received_msg[1 : ]
   1355     else
   1356       msg = received_msg
   1357     endif
   1358 
   1359     if parsing_disasm_msg > 0
   1360       HandleDisasmMsg(msg)
   1361     elseif msg != ''
   1362       if msg =~ '^\(\*stopped\|\*running\|=thread-selected\)'
   1363         HandleCursor(msg)
   1364       elseif msg =~ '^\^done,bkpt=' || msg =~ '^=breakpoint-created,'
   1365         HandleNewBreakpoint(msg, false)
   1366       elseif msg =~ '^=breakpoint-modified,'
   1367         HandleNewBreakpoint(msg, true)
   1368       elseif msg =~ '^=breakpoint-deleted,'
   1369         HandleBreakpointDelete(msg)
   1370       elseif msg =~ '^=thread-group-started'
   1371         HandleProgramRun(msg)
   1372       elseif msg =~ '^\^done,value='
   1373         HandleEvaluate(msg)
   1374       elseif msg =~ '^\^error,msg='
   1375         HandleError(msg)
   1376       elseif msg =~ '^&"disassemble'
   1377         parsing_disasm_msg = 1
   1378         asm_lines = []
   1379         HandleDisasmMsg(msg)
   1380       elseif msg =~ '^\^done,variables='
   1381         HandleVariablesMsg(msg)
   1382       endif
   1383     endif
   1384   endfor
   1385 enddef
   1386 
   1387 def GotoProgram()
   1388   if has('win32') && !ptywin
   1389     if executable('powershell')
   1390       system(printf('powershell -Command "add-type -AssemblyName microsoft.VisualBasic;[Microsoft.VisualBasic.Interaction]::AppActivate(%d);"', pid))
   1391     endif
   1392   else
   1393     win_gotoid(ptywin)
   1394   endif
   1395 enddef
   1396 
   1397 # Install commands in the current window to control the debugger.
   1398 def InstallCommands()
   1399 
   1400   command -nargs=? Break  SetBreakpoint(<q-args>)
   1401   command -nargs=? Tbreak  SetBreakpoint(<q-args>, true)
   1402   command ToggleBreak ToggleBreak()
   1403   command Clear  ClearBreakpoint()
   1404   command Step  SendResumingCommand('-exec-step')
   1405   command Over  SendResumingCommand('-exec-next')
   1406   command -nargs=? Until  Until(<q-args>)
   1407   command Finish  SendResumingCommand('-exec-finish')
   1408   command -nargs=* Run  Run(<q-args>)
   1409   command -nargs=* Arguments  SendResumingCommand('-exec-arguments ' .. <q-args>)
   1410   command Stop StopCommand()
   1411   command Continue ContinueCommand()
   1412   command RunOrContinue RunOrContinue()
   1413 
   1414   command -nargs=* Frame  Frame(<q-args>)
   1415   command -count=1 Up  Up(<count>)
   1416   command -count=1 Down  Down(<count>)
   1417 
   1418   command -range -nargs=* Evaluate  Evaluate(<range>, <q-args>)
   1419   command Gdb  win_gotoid(gdbwin)
   1420   command Program  GotoProgram()
   1421   command Source  GotoSourcewinOrCreateIt()
   1422   command Asm  GotoAsmwinOrCreateIt()
   1423   command Var  GotoVariableswinOrCreateIt()
   1424   command Winbar  InstallWinbar(true)
   1425 
   1426   var map = true
   1427   if exists('g:termdebug_config')
   1428     map = get(g:termdebug_config, 'map_K', true)
   1429   elseif exists('g:termdebug_map_K')
   1430     map = g:termdebug_map_K
   1431   endif
   1432 
   1433   if map
   1434     if !empty(saved_K_map) && !saved_K_map.buffer || empty(saved_K_map)
   1435       nnoremap K :Evaluate<CR>
   1436     endif
   1437     if !empty(saved_visual_K_map) && !saved_visual_K_map.buffer || empty(saved_visual_K_map)
   1438       xnoremap K :Evaluate<CR>
   1439     endif
   1440   endif
   1441 
   1442   map = true
   1443   if exists('g:termdebug_config')
   1444     map = get(g:termdebug_config, 'map_plus', true)
   1445   endif
   1446   if map
   1447     if !empty(saved_plus_map) && !saved_plus_map.buffer || empty(saved_plus_map)
   1448       nnoremap <expr> + $'<Cmd>{v:count1}Up<CR>'
   1449     endif
   1450   endif
   1451 
   1452   map = true
   1453   if exists('g:termdebug_config')
   1454     map = get(g:termdebug_config, 'map_minus', true)
   1455   endif
   1456   if map
   1457     if !empty(saved_minus_map) && !saved_minus_map.buffer || empty(saved_minus_map)
   1458       nnoremap <expr> - $'<Cmd>{v:count1}Down<CR>'
   1459     endif
   1460   endif
   1461 
   1462 
   1463   if has('menu') && &mouse != ''
   1464     InstallWinbar(false)
   1465 
   1466     var pup = true
   1467     if exists('g:termdebug_config')
   1468       pup = get(g:termdebug_config, 'popup', true)
   1469     elseif exists('g:termdebug_popup')
   1470       pup = g:termdebug_popup
   1471     endif
   1472 
   1473     if pup
   1474       &mousemodel = 'popup_setpos'
   1475       an 1.200 PopUp.-SEP3-	<Nop>
   1476       an 1.210 PopUp.Set\ breakpoint	<cmd>Break<CR>
   1477       an 1.220 PopUp.Clear\ breakpoint	<cmd>Clear<CR>
   1478       an 1.230 PopUp.Run\ until		<cmd>Until<CR>
   1479       an 1.240 PopUp.Evaluate		<cmd>Evaluate<CR>
   1480     endif
   1481   endif
   1482 
   1483 enddef
   1484 
   1485 # Install the window toolbar in the current window.
   1486 def InstallWinbar(force: bool)
   1487   # install the window toolbar by default, can be disabled in the config
   1488   var winbar = true
   1489   if exists('g:termdebug_config')
   1490     winbar = get(g:termdebug_config, 'winbar', true)
   1491   endif
   1492 
   1493   if has('menu') && &mouse != '' && (winbar || force)
   1494     nnoremenu WinBar.Step   :Step<CR>
   1495     nnoremenu WinBar.Next   :Over<CR>
   1496     nnoremenu WinBar.Finish :Finish<CR>
   1497     nnoremenu WinBar.Cont   :Continue<CR>
   1498     nnoremenu WinBar.Stop   :Stop<CR>
   1499     nnoremenu WinBar.Eval   :Evaluate<CR>
   1500     add(winbar_winids, win_getid())
   1501   endif
   1502 enddef
   1503 
   1504 # Delete installed debugger commands in the current window.
   1505 def DeleteCommands()
   1506   delcommand Break
   1507   delcommand Tbreak
   1508   delcommand Clear
   1509   delcommand Step
   1510   delcommand Over
   1511   delcommand Until
   1512   delcommand Finish
   1513   delcommand Run
   1514   delcommand Arguments
   1515   delcommand Stop
   1516   delcommand Continue
   1517   delcommand Frame
   1518   delcommand Up
   1519   delcommand Down
   1520   delcommand Evaluate
   1521   delcommand Gdb
   1522   delcommand Program
   1523   delcommand Source
   1524   delcommand Asm
   1525   delcommand Var
   1526   delcommand Winbar
   1527   delcommand RunOrContinue
   1528   delcommand ToggleBreak
   1529 
   1530 
   1531   if !empty(saved_K_map) && !saved_K_map.buffer
   1532     mapset(saved_K_map)
   1533   elseif empty(saved_K_map)
   1534     silent! nunmap K
   1535   endif
   1536 
   1537   if !empty(saved_visual_K_map) && !saved_visual_K_map.buffer
   1538     mapset(saved_visual_K_map)
   1539   elseif empty(saved_visual_K_map)
   1540     silent! xunmap K
   1541   endif
   1542 
   1543   if !empty(saved_plus_map) && !saved_plus_map.buffer
   1544     mapset(saved_plus_map)
   1545   elseif empty(saved_plus_map)
   1546     silent! nunmap +
   1547   endif
   1548 
   1549   if !empty(saved_minus_map) && !saved_minus_map.buffer
   1550     mapset(saved_minus_map)
   1551   elseif empty(saved_minus_map)
   1552     silent! nunmap -
   1553   endif
   1554 
   1555 
   1556   if has('menu')
   1557     # Remove the WinBar entries from all windows where it was added.
   1558     var curwinid = win_getid()
   1559     for winid in winbar_winids
   1560       if win_gotoid(winid)
   1561         aunmenu WinBar.Step
   1562         aunmenu WinBar.Next
   1563         aunmenu WinBar.Finish
   1564         aunmenu WinBar.Cont
   1565         aunmenu WinBar.Stop
   1566         aunmenu WinBar.Eval
   1567       endif
   1568     endfor
   1569     win_gotoid(curwinid)
   1570 
   1571     &mousemodel = saved_mousemodel
   1572     try
   1573       aunmenu PopUp.-SEP3-
   1574       aunmenu PopUp.Set\ breakpoint
   1575       aunmenu PopUp.Clear\ breakpoint
   1576       aunmenu PopUp.Run\ until
   1577       aunmenu PopUp.Evaluate
   1578     catch
   1579       # ignore any errors in removing the PopUp menu
   1580     endtry
   1581   endif
   1582 
   1583   sign_unplace('TermDebug')
   1584   sign_undefine('debugPC')
   1585   sign_undefine(BreakpointSigns->map("'debugBreakpoint' .. v:val"))
   1586 enddef
   1587 
   1588 def QuoteArg(x: string): string
   1589   # Find all the occurrences of " and \ and escape them and double quote
   1590   # the resulting string.
   1591   return printf('"%s"', x ->substitute('[\\"]', '\\&', 'g'))
   1592 enddef
   1593 
   1594 def DefaultBreakpointLocation(): string
   1595   # Use the fname:lnum format, older gdb can't handle --source.
   1596   var fname = Remote2LocalPath(expand('%:p'))
   1597   return QuoteArg($"{fname}:{line('.')}")
   1598 enddef
   1599 
   1600 def TokenizeBreakpointArguments(args: string): list<dict<any>>
   1601   var tokens: list<dict<any>> = []
   1602   var start = -1
   1603   var escaped = false
   1604   var in_quotes = false
   1605 
   1606   var i = 0
   1607   for ch in args
   1608     if start < 0 && ch !~ '\s'
   1609       start = i
   1610     endif
   1611     if start >= 0
   1612       if escaped
   1613         escaped = false
   1614       elseif ch == '\'
   1615         escaped = true
   1616       elseif ch == '"'
   1617         in_quotes = !in_quotes
   1618       elseif !in_quotes && ch =~ '\s'
   1619         tokens->add({text: args[start : i - 1], start: start, end: i - 1})
   1620         start = -1
   1621       endif
   1622     endif
   1623     i += 1
   1624   endfor
   1625 
   1626   if start >= 0
   1627     tokens->add({text: args[start :], start: start, end: i - 1})
   1628   endif
   1629   return tokens
   1630 enddef
   1631 
   1632 def BuildBreakpointCommand(at: string, tbreak=false): string
   1633   var args = trim(at)
   1634   var cmd = '-break-insert'
   1635   if tbreak
   1636     cmd ..= ' -t'
   1637   endif
   1638 
   1639   if empty(args)
   1640     return $'{cmd} {DefaultBreakpointLocation()}'
   1641   endif
   1642 
   1643   var condition = ''
   1644   var prefix = args
   1645   for token in TokenizeBreakpointArguments(args)
   1646     if token.text == 'if' && token.end < strchars(args) - 1
   1647       condition = trim(args[token.end + 1 :])
   1648       prefix = token.start > 0 ? trim(args[: token.start - 1]) : ''
   1649       break
   1650     endif
   1651   endfor
   1652 
   1653   var prefix_tokens = TokenizeBreakpointArguments(prefix)
   1654   var location = prefix
   1655   var thread = ''
   1656   if len(prefix_tokens) >= 2
   1657       && prefix_tokens[-2].text == 'thread'
   1658       && prefix_tokens[-1].text =~ '^\d\+$'
   1659     thread = prefix_tokens[-1].text
   1660     location = join(prefix_tokens[: -3]->mapnew('v:val.text'), ' ')
   1661   endif
   1662 
   1663   if empty(trim(location))
   1664     location = DefaultBreakpointLocation()
   1665   endif
   1666   if !empty(thread)
   1667     cmd ..= $' -p {thread}'
   1668   endif
   1669   if !empty(condition)
   1670     cmd ..= $' -c {QuoteArg(condition)}'
   1671   endif
   1672   return $'{cmd} {trim(location)}'
   1673 enddef
   1674 
   1675 # :Until - Execute until past a specified position or current line
   1676 def Until(at: string)
   1677 
   1678   if stopped
   1679     # reset stopped here, it may take a bit of time before we get a response
   1680     stopped = false
   1681     ch_log('assume that program is running after this command')
   1682 
   1683     # Use the fname:lnum format
   1684     var fname = Remote2LocalPath(expand('%:p'))
   1685     var AT = empty(at) ? QuoteArg($"{fname}:{line('.')}") : at
   1686     SendCommand($'-exec-until {AT}')
   1687   else
   1688     ch_log('dropping command, program is running: exec-until')
   1689   endif
   1690 enddef
   1691 
   1692 # :Break - Set a breakpoint at the cursor position.
   1693 def SetBreakpoint(at: string, tbreak=false)
   1694   # Setting a breakpoint may not work while the program is running.
   1695   # Interrupt to make it work.
   1696   var do_continue = false
   1697   if !stopped
   1698     do_continue = true
   1699     StopCommand()
   1700     sleep 10m
   1701   endif
   1702 
   1703   var cmd = BuildBreakpointCommand(at, tbreak)
   1704   SendCommand(cmd)
   1705   if do_continue
   1706     ContinueCommand()
   1707   endif
   1708 enddef
   1709 
   1710 def ClearBreakpoint()
   1711   var fname = Remote2LocalPath(expand('%:p'))
   1712   fname = fnameescape(fname)
   1713   var lnum = line('.')
   1714   var bploc = printf('%s:%d', fname, lnum)
   1715   var nr = 0
   1716   if has_key(breakpoint_locations, bploc)
   1717     var idx = 0
   1718     for id in breakpoint_locations[bploc]
   1719       if has_key(breakpoints, id)
   1720         # Assume this always works, the reply is simply "^done".
   1721         SendCommand($'-break-delete {id}')
   1722         for subid in keys(breakpoints[id])
   1723           sign_unplace('TermDebug',
   1724             {id: Breakpoint2SignNumber(id, str2nr(subid))})
   1725         endfor
   1726         remove(breakpoints, id)
   1727         remove(breakpoint_locations[bploc], idx)
   1728         nr = id
   1729         break
   1730       else
   1731         idx += 1
   1732       endif
   1733     endfor
   1734 
   1735     if nr != 0
   1736       if empty(breakpoint_locations[bploc])
   1737         remove(breakpoint_locations, bploc)
   1738       endif
   1739       echomsg $'Breakpoint {nr} cleared from line {lnum}.'
   1740     else
   1741       Echoerr($'Internal error trying to remove breakpoint at line {lnum}!')
   1742     endif
   1743   else
   1744     echomsg $'No breakpoint to remove at line {lnum}.'
   1745   endif
   1746 enddef
   1747 
   1748 def ToggleBreak()
   1749   var fname = Remote2LocalPath(expand('%:p'))
   1750   fname = fnameescape(fname)
   1751   var lnum = line('.')
   1752   var bploc = printf('%s:%d', fname, lnum)
   1753   if has_key(breakpoint_locations, bploc)
   1754     while has_key(breakpoint_locations, bploc)
   1755         ClearBreakpoint()
   1756     endwhile
   1757   else
   1758     SetBreakpoint("")
   1759   endif
   1760 enddef
   1761 
   1762 def Run(args: string)
   1763   if args != ''
   1764     SendResumingCommand($'-exec-arguments {args}')
   1765   endif
   1766   SendResumingCommand('-exec-run')
   1767 enddef
   1768 
   1769 def RunOrContinue()
   1770     if running
   1771       ContinueCommand()
   1772     else
   1773       Run('')
   1774     endif
   1775 enddef
   1776 
   1777 # :Frame - go to a specific frame in the stack
   1778 def Frame(arg: string)
   1779   # Note: we explicit do not use mi's command
   1780   # call SendCommand('-stack-select-frame "' . arg .'"')
   1781   # as we only get a "done" mi response and would have to open the file
   1782   # 'manually' - using cli command "frame" provides us with the mi response
   1783   # already parsed and allows for more formats
   1784   if arg =~ '^\d\+$' || arg == ''
   1785     # specify frame by number
   1786     SendCommand($'-interpreter-exec mi "frame {arg}"')
   1787   elseif arg =~ '^0x[0-9a-fA-F]\+$'
   1788     # specify frame by stack address
   1789     SendCommand($'-interpreter-exec mi "frame address {arg}"')
   1790   else
   1791     # specify frame by function name
   1792     SendCommand($'-interpreter-exec mi "frame function {arg}"')
   1793   endif
   1794 enddef
   1795 
   1796 # :Up - go count frames in the stack "higher"
   1797 def Up(count: number)
   1798   # the 'correct' one would be -stack-select-frame N, but we don't know N
   1799   SendCommand($'-interpreter-exec console "up {count}"')
   1800 enddef
   1801 
   1802 # :Down - go count frames in the stack "below"
   1803 def Down(count: number)
   1804   # the 'correct' one would be -stack-select-frame N, but we don't know N
   1805   SendCommand($'-interpreter-exec console "down {count}"')
   1806 enddef
   1807 
   1808 def SendEval(expr: string)
   1809   # check for "likely" boolean expressions, in which case we take it as lhs
   1810   var exprLHS = substitute(expr, ' *=.*', '', '')
   1811   if expr =~ "[=!<>]="
   1812     exprLHS = expr
   1813   endif
   1814 
   1815   # encoding expression to prevent bad errors
   1816   var expr_escaped = expr
   1817     ->substitute('\\', '\\\\', 'g')
   1818     ->substitute('"', '\\"', 'g')
   1819   SendCommand($'-data-evaluate-expression "{expr_escaped}"')
   1820   evalexpr = exprLHS
   1821 enddef
   1822 
   1823 # Returns whether to evaluate in a popup or not, defaults to false.
   1824 def EvaluateInPopup(): bool
   1825   if exists('g:termdebug_config')
   1826     return get(g:termdebug_config, 'evaluate_in_popup', false)
   1827   endif
   1828   return false
   1829 enddef
   1830 
   1831 # :Evaluate - evaluate what is specified / under the cursor
   1832 def Evaluate(range: number, arg: string)
   1833   var expr = GetEvaluationExpression(range, arg)
   1834   if EvaluateInPopup()
   1835     evalInPopup = true
   1836     evalExprResult = ''
   1837   else
   1838     echomsg $'expr: {expr}'
   1839   endif
   1840   ignoreEvalError = false
   1841   SendEval(expr)
   1842 enddef
   1843 
   1844 
   1845 # get what is specified / under the cursor
   1846 def GetEvaluationExpression(range: number, arg: string): string
   1847   var expr = ''
   1848   if arg != ''
   1849     # user supplied evaluation
   1850     expr = CleanupExpr(arg)
   1851     expr = substitute(expr, '"\([^"]*\)": *', '\1=', 'g')
   1852   elseif range == 2
   1853     # no evaluation but provided but range set
   1854     var pos = getcurpos()
   1855     var regst = getreg('v', 1, 1)
   1856     var regt = getregtype('v')
   1857     normal! gv"vy
   1858     expr = CleanupExpr(@v)
   1859     setpos('.', pos)
   1860     setreg('v', regst, regt)
   1861   else
   1862     # no evaluation provided: get from C-expression under cursor
   1863     # TODO: allow filetype specific lookup #9057
   1864     expr = expand('<cexpr>')
   1865   endif
   1866   return expr
   1867 enddef
   1868 
   1869 # clean up expression that may get in because of range
   1870 # (newlines and surrounding whitespace)
   1871 # As it can also be specified via ex-command for assignments this function
   1872 # may not change the "content" parts (like replacing contained spaces)
   1873 def CleanupExpr(passed_expr: string): string
   1874   # replace all embedded newlines/tabs/...
   1875   var expr = substitute(passed_expr, '\_s', ' ', 'g')
   1876 
   1877   if &filetype ==# 'cobol'
   1878     # extra cleanup for COBOL:
   1879     # - a semicolon nmay be used instead of a space
   1880     # - a trailing comma or period is ignored as it commonly separates/ends
   1881     #   multiple expr
   1882     expr = substitute(expr, ';', ' ', 'g')
   1883     expr = substitute(expr, '[,.]\+ *$', '', '')
   1884   endif
   1885 
   1886   # get rid of leading and trailing spaces
   1887   expr = substitute(expr, '^ *', '', '')
   1888   expr = substitute(expr, ' *$', '', '')
   1889   return expr
   1890 enddef
   1891 
   1892 def Balloon_show(expr: string)
   1893   if has("balloon_eval") || has("balloon_eval_term")
   1894     balloon_show(expr)
   1895   endif
   1896 enddef
   1897 
   1898 def Popup_format(expr: string): list<string>
   1899   var lines = expr
   1900     ->substitute('{', '{\n', 'g')
   1901     ->substitute('}', '\n}', 'g')
   1902     ->substitute(',', ',\n', 'g')
   1903     ->split('\n')
   1904   var indentation = 0
   1905   var formatted_lines = []
   1906   for line in lines
   1907     var stripped = line->substitute('^\s\+', '', '')
   1908     if stripped =~ '^}'
   1909       indentation -= 2
   1910     endif
   1911     formatted_lines->add(repeat(' ', indentation) .. stripped)
   1912     if stripped =~ '{$'
   1913       indentation += 2
   1914     endif
   1915   endfor
   1916   return formatted_lines
   1917 enddef
   1918 
   1919 def Popup_show(expr: string)
   1920   var formatted = Popup_format(expr)
   1921   if evalPopupId != -1
   1922     popup_close(evalPopupId)
   1923   endif
   1924   # Specifying the line is necessary, as the winbar seems to cause issues
   1925   # otherwise. I.e., the popup would be shown one line too high.
   1926   evalPopupId = popup_atcursor(formatted, {'line': 'cursor-1'})
   1927 enddef
   1928 
   1929 def HandleEvaluate(msg: string)
   1930   var value = msg
   1931     ->substitute('.*value="\(.*\)"', '\1', '')
   1932     ->substitute('\\"', '"', 'g')
   1933     ->substitute('\\\\', '\\', 'g')
   1934     #\ multi-byte characters arrive in octal form, replace everything but NULL values
   1935     ->substitute('\\000', NullRepl, 'g')
   1936     ->substitute('\\\(\o\o\o\)', (m) => nr2char(str2nr(m[1], 8)), 'g')
   1937     #\ Note: GDB docs also mention hex encodings - the translations below work
   1938     #\       but we keep them out for performance-reasons until we actually see
   1939     #\       those in mi-returns
   1940     #\ ->substitute('\\0x00', NullRep, 'g')
   1941     #\ ->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
   1942     ->substitute(NullRepl, '\\000', 'g')
   1943   if evalFromBalloonExpr || evalInPopup
   1944     if empty(evalExprResult)
   1945       evalExprResult = $'{evalexpr}: {value}'
   1946     else
   1947       evalExprResult ..= $' = {value}'
   1948     endif
   1949   else
   1950     echomsg $'"{evalexpr}": {value}'
   1951   endif
   1952 
   1953   if evalexpr[0] != '*' && value =~ '^0x' && value != '0x0' && value !~ '"$'
   1954     # Looks like a pointer, also display what it points to.
   1955     ignoreEvalError = true
   1956     SendEval($'*{evalexpr}')
   1957   elseif evalFromBalloonExpr
   1958     Balloon_show(evalExprResult)
   1959     evalFromBalloonExpr = false
   1960   elseif evalInPopup
   1961     Popup_show(evalExprResult)
   1962     evalInPopup = false
   1963   endif
   1964 enddef
   1965 
   1966 
   1967 # Show a balloon with information of the variable under the mouse pointer,
   1968 # if there is any.
   1969 def TermDebugBalloonExpr(): string
   1970   if v:beval_winid != sourcewin
   1971     return ''
   1972   endif
   1973   if !stopped
   1974     # Only evaluate when stopped, otherwise setting a breakpoint using the
   1975     # mouse triggers a balloon.
   1976     return ''
   1977   endif
   1978   evalFromBalloonExpr = true
   1979   evalExprResult = ''
   1980   ignoreEvalError = true
   1981   var expr = CleanupExpr(v:beval_text)
   1982   SendEval(expr)
   1983   return ''
   1984 enddef
   1985 
   1986 # Handle an error.
   1987 def HandleError(msg: string)
   1988   if ignoreEvalError
   1989     # Result of SendEval() failed, ignore.
   1990     ignoreEvalError = false
   1991     evalFromBalloonExpr = true
   1992     return
   1993   endif
   1994   var msgVal = substitute(msg, '.*msg="\(.*\)"', '\1', '')
   1995   Echoerr(substitute(msgVal, '\\"', '"', 'g'))
   1996 enddef
   1997 
   1998 def GotoSourcewinOrCreateIt()
   1999   if !win_gotoid(sourcewin)
   2000     new
   2001     sourcewin = win_getid()
   2002     InstallWinbar(false)
   2003   endif
   2004 enddef
   2005 
   2006 
   2007 def GetDisasmWindow(): bool
   2008   # TODO Remove the deprecated features after 1 Jan 2025.
   2009   var val: any
   2010   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'disasm_window')
   2011     val = g:termdebug_config['disasm_window']
   2012   elseif exists('g:termdebug_disasm_window')
   2013     val = g:termdebug_disasm_window
   2014   else
   2015     val = false
   2016   endif
   2017   return typename(val) == 'number' ? val != 0 : val
   2018 enddef
   2019 
   2020 def GetDisasmWindowHeight(): number
   2021   if exists('g:termdebug_config')
   2022     return get(g:termdebug_config, 'disasm_window_height', 0)
   2023   endif
   2024   if exists('g:termdebug_disasm_window') && g:termdebug_disasm_window > 1
   2025     return g:termdebug_disasm_window
   2026   endif
   2027   return 0
   2028 enddef
   2029 
   2030 def GotoAsmwinOrCreateIt()
   2031   var mdf = ''
   2032   if !win_gotoid(asmwin)
   2033     if win_gotoid(sourcewin)
   2034       # 60 is approx spaceBuffer * 3
   2035       if winwidth(0) > (78 + 60)
   2036         mdf = 'vert'
   2037         exe $'{mdf} :60new'
   2038       else
   2039         exe 'rightbelow new'
   2040       endif
   2041     else
   2042       exe 'new'
   2043     endif
   2044 
   2045     asmwin = win_getid()
   2046 
   2047     setlocal nowrap
   2048     setlocal number
   2049     setlocal noswapfile
   2050     setlocal buftype=nofile
   2051     setlocal bufhidden=wipe
   2052     setlocal signcolumn=no
   2053     setlocal modifiable
   2054 
   2055     if asmbufnr > 0 && bufexists(asmbufnr)
   2056       exe $'buffer {asmbufnr}'
   2057     else
   2058       exe $"silent file {asmbufname}"
   2059       asmbufnr = bufnr(asmbufname)
   2060     endif
   2061 
   2062     if mdf != 'vert' && GetDisasmWindowHeight() > 0
   2063       exe $'resize {GetDisasmWindowHeight()}'
   2064     endif
   2065   endif
   2066 
   2067   if asm_addr != ''
   2068     var lnum = search($'^{asm_addr}')
   2069     if lnum == 0
   2070       if stopped
   2071         SendCommand('disassemble $pc')
   2072       endif
   2073     else
   2074       sign_unplace('TermDebug', {id: asm_id})
   2075       sign_place(asm_id, 'TermDebug', 'debugPC', '%', {lnum: lnum})
   2076     endif
   2077   endif
   2078 enddef
   2079 
   2080 def GetVariablesWindow(): bool
   2081   # TODO Remove the deprecated features after 1 Jan 2025.
   2082   var val: any
   2083   if exists('g:termdebug_config') && has_key(g:termdebug_config, 'variables_window')
   2084     val = g:termdebug_config['variables_window']
   2085   elseif exists('g:termdebug_variables_window')
   2086     val = g:termdebug_variables_window
   2087   else
   2088     val = false
   2089   endif
   2090   return typename(val) == 'number' ? val != 0 : val
   2091 enddef
   2092 
   2093 def GetVariablesWindowHeight(): number
   2094   if exists('g:termdebug_config')
   2095     return get(g:termdebug_config, 'variables_window_height', 0)
   2096   endif
   2097   if exists('g:termdebug_variables_window') && g:termdebug_variables_window > 1
   2098     return g:termdebug_variables_window
   2099   endif
   2100   return 0
   2101 enddef
   2102 
   2103 
   2104 def GotoVariableswinOrCreateIt()
   2105   var mdf = ''
   2106   if !win_gotoid(varwin)
   2107     if win_gotoid(sourcewin)
   2108       # 60 is approx spaceBuffer * 3
   2109       if winwidth(0) > (78 + 60)
   2110         mdf = 'vert'
   2111         exe $'{mdf} :60new'
   2112       else
   2113         exe 'rightbelow new'
   2114       endif
   2115     else
   2116       exe 'new'
   2117     endif
   2118 
   2119     varwin = win_getid()
   2120 
   2121     setlocal nowrap
   2122     setlocal noswapfile
   2123     setlocal buftype=nofile
   2124     setlocal bufhidden=wipe
   2125     setlocal signcolumn=no
   2126     setlocal modifiable
   2127 
   2128     # If exists, then open, otherwise create
   2129     if varbufnr > 0 && bufexists(varbufnr)
   2130       exe $'buffer {varbufnr}'
   2131     else
   2132       exe $"silent file {varbufname}"
   2133       varbufnr = bufnr(varbufname)
   2134     endif
   2135 
   2136     if mdf != 'vert' && GetVariablesWindowHeight() > 0
   2137       exe $'resize {GetVariablesWindowHeight()}'
   2138     endif
   2139   endif
   2140 
   2141   if running
   2142     SendCommand('-stack-list-variables 2')
   2143   endif
   2144 enddef
   2145 
   2146 # Handle stopping and running message from gdb.
   2147 # Will update the sign that shows the current position.
   2148 def HandleCursor(msg: string)
   2149   var wid = win_getid()
   2150 
   2151   if msg =~ '^\*stopped'
   2152     ch_log('program stopped')
   2153     stopped = true
   2154     if msg =~ '^\*stopped,reason="exited-normally"'
   2155       running = false
   2156     endif
   2157   elseif msg =~ '^\*running'
   2158     ch_log('program running')
   2159     stopped = false
   2160     running = true
   2161   endif
   2162 
   2163   var fname = ''
   2164   if msg =~ 'fullname='
   2165     fname = GetLocalFullname(msg)
   2166   endif
   2167 
   2168   if msg =~ 'addr='
   2169     var asm_addr_local = GetAsmAddr(msg)
   2170     if asm_addr_local != ''
   2171       asm_addr = asm_addr_local
   2172 
   2173       var curwinid = win_getid()
   2174       var lnum = 0
   2175       if win_gotoid(asmwin)
   2176         lnum = search($'^{asm_addr}')
   2177         if lnum == 0
   2178           SendCommand('disassemble $pc')
   2179         else
   2180           sign_unplace('TermDebug', {id: asm_id})
   2181           sign_place(asm_id, 'TermDebug', 'debugPC', '%', {lnum: lnum})
   2182         endif
   2183 
   2184         win_gotoid(curwinid)
   2185       endif
   2186     endif
   2187   endif
   2188 
   2189   if running && stopped && bufwinnr(varbufname) != -1
   2190     SendCommand('-stack-list-variables 2')
   2191   endif
   2192 
   2193   # Translate to remote file name if needed.
   2194   const fremote = Local2RemotePath(fname)
   2195 
   2196   if msg =~ '^\(\*stopped\|=thread-selected\)' && (fremote != fname || filereadable(fname))
   2197     var lnum = substitute(msg, '.*line="\([^"]*\)".*', '\1', '')
   2198     if lnum =~ '^[0-9]*$'
   2199       GotoSourcewinOrCreateIt()
   2200       if expand('%:p') != fnamemodify(fremote, ':p')
   2201         echomsg $"different fname: '{expand('%:p')}' vs '{fnamemodify(fremote, ':p')}'"
   2202         augroup Termdebug
   2203           # Always open a file read-only instead of showing the ATTENTION
   2204           # prompt, since it is unlikely we want to edit the file.
   2205           # The file may be changed but not saved, warn for that.
   2206           au SwapExists * echohl WarningMsg
   2207             | echo 'Warning: file is being edited elsewhere'
   2208             | echohl None
   2209             | v:swapchoice = 'o'
   2210         augroup END
   2211         if &modified
   2212           # TODO: find existing window
   2213           exe $'split {fnameescape(fremote)}'
   2214           sourcewin = win_getid()
   2215           InstallWinbar(false)
   2216         else
   2217           exe $'edit {fnameescape(fremote)}'
   2218         endif
   2219         augroup Termdebug
   2220           au! SwapExists
   2221         augroup END
   2222       endif
   2223       exe $":{lnum}"
   2224       normal! zv
   2225       sign_unplace('TermDebug', {id: pc_id})
   2226       sign_place(pc_id, 'TermDebug', 'debugPC', fremote,
   2227         {lnum: str2nr(lnum), priority: 110})
   2228       if !exists('b:save_signcolumn')
   2229         b:save_signcolumn = &signcolumn
   2230         add(signcolumn_buflist, bufnr())
   2231       endif
   2232       setlocal signcolumn=yes
   2233     endif
   2234   elseif !stopped || fname != ''
   2235     sign_unplace('TermDebug', {id: pc_id})
   2236   endif
   2237 
   2238   win_gotoid(wid)
   2239 enddef
   2240 
   2241 # Create breakpoint sign
   2242 def CreateBreakpoint(id: number, subid: number, enabled: string)
   2243   var nr = printf('%d.%d', id, subid)
   2244   if index(BreakpointSigns, nr) == -1
   2245     add(BreakpointSigns, nr)
   2246     var hiName = ''
   2247     if enabled == "n"
   2248       hiName = "debugBreakpointDisabled"
   2249     else
   2250       hiName = "debugBreakpoint"
   2251     endif
   2252     var label = ''
   2253     if exists('g:termdebug_config')
   2254       if has_key(g:termdebug_config, 'signs')
   2255         label = get(g:termdebug_config.signs, id - 1, '')
   2256       endif
   2257       if label == '' && has_key(g:termdebug_config, 'sign')
   2258         label = g:termdebug_config['sign']
   2259       endif
   2260       if label == '' && has_key(g:termdebug_config, 'sign_decimal')
   2261         label = printf('%02d', id)
   2262         if id > 99
   2263           label = '9+'
   2264         endif
   2265       endif
   2266     endif
   2267     if label == ''
   2268       label = printf('%02X', id)
   2269       if id > 255
   2270         label = 'F+'
   2271       endif
   2272     endif
   2273     sign_define($'debugBreakpoint{nr}',
   2274       {text: slice(label, 0, 2),
   2275         texthl: hiName})
   2276   endif
   2277 enddef
   2278 
   2279 def SplitMsg(str: string): list<string>
   2280   return split(str, '{.\{-}}\zs')
   2281 enddef
   2282 
   2283 
   2284 # Handle setting a breakpoint
   2285 # Will update the sign that shows the breakpoint
   2286 def HandleNewBreakpoint(msg: string, modifiedFlag: bool)
   2287   var nr = ''
   2288 
   2289   if msg !~ 'fullname='
   2290     # a watch or a pending breakpoint does not have a file name
   2291     if msg =~ 'pending='
   2292       nr = substitute(msg, '.*number=\"\([0-9.]*\)\".*', '\1', '')
   2293       var target = substitute(msg, '.*pending=\"\([^"]*\)\".*', '\1', '')
   2294       echomsg $'Breakpoint {nr} ({target}) pending.'
   2295     endif
   2296     return
   2297   endif
   2298 
   2299   for mm in SplitMsg(msg)
   2300     var fname = GetLocalFullname(mm)
   2301     if empty(fname)
   2302       continue
   2303     endif
   2304     var fremote = Local2RemotePath(fname)
   2305     nr = substitute(mm, '.*number="\([0-9.]*\)\".*', '\1', '')
   2306     if empty(nr)
   2307       return
   2308     endif
   2309 
   2310     # If "nr" is 123 it becomes "123.0" and subid is "0".
   2311     # If "nr" is 123.4 it becomes "123.4.0" and subid is "4"; "0" is discarded.
   2312     var [id, subid; _] = map(split(nr .. '.0', '\.'), 'str2nr(v:val) + 0')
   2313     # var [id, subid; _] = map(split(nr .. '.0', '\.'), 'v:val + 0')
   2314     var enabled = substitute(mm, '.*enabled="\([yn]\)".*', '\1', '')
   2315     CreateBreakpoint(id, subid, enabled)
   2316 
   2317     var entries = {}
   2318     var entry = {}
   2319     if has_key(breakpoints, id)
   2320       entries = breakpoints[id]
   2321     else
   2322       breakpoints[id] = entries
   2323     endif
   2324     if has_key(entries, subid)
   2325       entry = entries[subid]
   2326     else
   2327       entries[subid] = entry
   2328     endif
   2329 
   2330     var lnum = str2nr(substitute(mm, '.*line="\([^"]*\)".*', '\1', ''))
   2331     entry['fname'] = fname
   2332     entry['lnum'] = lnum
   2333 
   2334     var bploc = printf('%s:%d', fname, lnum)
   2335     if !has_key(breakpoint_locations, bploc)
   2336       breakpoint_locations[bploc] = []
   2337     endif
   2338     if breakpoint_locations[bploc]->index(id) == -1
   2339       # Make sure all ids are unique
   2340       breakpoint_locations[bploc] += [id]
   2341     endif
   2342 
   2343     var posMsg = ''
   2344     if bufloaded(fremote)
   2345       PlaceSign(id, subid, entry)
   2346       posMsg = $' at line {lnum}.'
   2347     else
   2348       posMsg = $' in {fremote} at line {lnum}.'
   2349     endif
   2350     var actionTaken = ''
   2351     if !modifiedFlag
   2352       actionTaken = 'created'
   2353     elseif enabled == 'n'
   2354       actionTaken = 'disabled'
   2355     else
   2356       actionTaken = 'enabled'
   2357     endif
   2358     echom $'Breakpoint {nr} {actionTaken}{posMsg}'
   2359   endfor
   2360 enddef
   2361 
   2362 
   2363 def PlaceSign(id: number, subid: number, entry: dict<any>)
   2364   var nr = printf('%d.%d', id, subid)
   2365   var remote = Local2RemotePath(entry['fname'])
   2366   sign_place(Breakpoint2SignNumber(id, subid), 'TermDebug',
   2367     $'debugBreakpoint{nr}', remote,
   2368     {lnum: entry['lnum'], priority: 110})
   2369   entry['placed'] = 1
   2370 enddef
   2371 
   2372 # Handle deleting a breakpoint
   2373 # Will remove the sign that shows the breakpoint
   2374 def HandleBreakpointDelete(msg: string)
   2375   var id = substitute(msg, '.*id="\([0-9]*\)\".*', '\1', '')
   2376   if empty(id)
   2377     return
   2378   endif
   2379   if has_key(breakpoints, id)
   2380     for [subid, entry] in items(breakpoints[id])
   2381       if has_key(entry, 'placed')
   2382         sign_unplace('TermDebug',
   2383           {id: Breakpoint2SignNumber(str2nr(id), str2nr(subid))})
   2384         remove(entry, 'placed')
   2385       endif
   2386     endfor
   2387     remove(breakpoints, id)
   2388     echomsg $'Breakpoint {id} cleared.'
   2389   endif
   2390 enddef
   2391 
   2392 # Handle the debugged program starting to run.
   2393 # Will store the process ID in pid
   2394 def HandleProgramRun(msg: string)
   2395   var nr = str2nr(substitute(msg, '.*pid="\([0-9]*\)\".*', '\1', ''))
   2396   if nr == 0
   2397     return
   2398   endif
   2399   pid = nr
   2400   ch_log($'Detected process ID: {pid}')
   2401 enddef
   2402 
   2403 # Handle a BufRead autocommand event: place any signs.
   2404 def BufRead()
   2405   var fname = expand('<afile>:p')
   2406   for [id, entries] in items(breakpoints)
   2407     for [subid, entry] in items(entries)
   2408       if entry['fname'] == fname
   2409         PlaceSign(str2nr(id), str2nr(subid), entry)
   2410       endif
   2411     endfor
   2412   endfor
   2413 enddef
   2414 
   2415 # Handle a BufUnloaded autocommand event: unplace any signs.
   2416 def BufUnloaded()
   2417   var fname = expand('<afile>:p')
   2418   for entries in values(breakpoints)
   2419     for entry in values(entries)
   2420       if entry['fname'] == fname
   2421         entry['placed'] = 0
   2422       endif
   2423     endfor
   2424   endfor
   2425 enddef
   2426 
   2427 InitHighlight()
   2428 InitAutocmd()
   2429 
   2430 # vim: sw=2 sts=2 et