robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
e4876d8126
master
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 ) 48echohl ErrorMsg |echom $ '[termdebug] {a:msg}' | echohlNone 49endfunc 50 51" In case this gets sourced twice. 52if exists ( ':Termdebug' ) 53call s: Echoerr ( 'Termdebug already loaded.' ) 54finish 55endif 56 57" The terminal feature does not work with gdb on win32. 58if ! has ( 'win32' ) 59let s: way = 'terminal' 60else 61let 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 ) 89return 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 ) 95let default = a: init ? 'default ' : '' 96if a: new ==# 'light' && a: old !=# 'light' 97exe $ "hi {default}debugPC term=reverse ctermbg=lightblue guibg=lightblue" 98elseif a: new ==# 'dark' && a: old !=# 'dark' 99exe $ "hi {default}debugPC term=reverse ctermbg=darkblue guibg=darkblue" 100endif 101endfunc 102 103" Define the default highlighting, using the current 'background' value. 104func s: InitHighlight () 105call s: Highlight ( 1 , '' , & background ) 106hi default debugBreakpoint term = reverse ctermbg = red guibg = red 107hi 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 () 113augroup TermDebug 114autocmd ! 115autocmd ColorScheme * call s: InitHighlight () 116augroup END 117endfunc 118 119" Get the command to execute the debugger as a list, defaults to ["gdb"]. 120func s: GetCommand () 121if exists ( 'g:termdebug_config' ) 122let cmd = get ( g: termdebug_config , 'command' , 'gdb' ) 123elseif exists ( 'g:termdebugger' ) 124let cmd = g: termdebugger 125else 126let cmd = 'gdb' 127endif 128 129return 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. 134call 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. 139call s: StartDebug_internal ({ 'gdb_args' : [ a: 1 ], 'proc_args' : a: 000 [ 1 :], 'bang' : a: bang }) 140endfunc 141 142func s: StartDebug_internal ( dict ) 143if get ( g:, 'termdebug_is_running' , v: false ) || exists ( 's:gdbwin' ) 144call s: Echoerr ( 'Terminal debugger already running, cannot run two' ) 145return 146endif 147let gdbcmd = s: GetCommand () 148if ! executable ( gdbcmd [ 0 ]) 149call s: Echoerr ( $ 'Cannot execute debugger program "{gdbcmd[0]}"') 150return 151endif 152 153let s: ptywin = 0 154let s: pid = 0 155let s: asmwin = 0 156let s: asmbufnr = 0 157let s: varwin = 0 158let s: varbufnr = 0 159 160if exists ( '#User#TermdebugStartPre' ) 161doauto <nomodeline> User TermdebugStartPre 162endif 163 164" Uncomment this line to write logging in "debuglog". 165" call ch_logfile('debuglog', 'w') 166 167let 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. 171let b: save_signcolumn = & signcolumn 172let s: signcolumn_buflist = [ bufnr ()] 173 174let s: saved_columns = 0 175let s: allleft = v: false 176let wide = 0 177if exists ( 'g:termdebug_config' ) 178let wide = get ( g: termdebug_config , 'wide' , 0 ) 179elseif exists ( 'g:termdebug_wide' ) 180let wide = g: termdebug_wide 181endif 182if wide > 0 183if & columns < wide 184let s: saved_columns = & columns 185let & columns = wide 186" If we make the Vim window wider, use the whole left half for the debug 187" windows. 188let s: allleft = v: true 189endif 190let s: vertical = v: true 191else 192let s: vertical = v: false 193endif 194 195" Override using a terminal window by setting g:termdebug_use_prompt to 1. 196let use_prompt = 0 197if exists ( 'g:termdebug_config' ) 198let use_prompt = get ( g: termdebug_config , 'use_prompt' , 0 ) 199elseif exists ( 'g:termdebug_use_prompt' ) 200let use_prompt = g: termdebug_use_prompt 201endif 202if ! has ( 'win32' ) && ! use_prompt 203let s: way = 'terminal' 204else 205let s: way = 'prompt' 206endif 207 208if s: way == 'prompt' 209call s: StartDebug_prompt ( a: dict ) 210else 211call s: StartDebug_term ( a: dict ) 212endif 213 214if s: GetDisasmWindow () 215let curwinid = win_getid () 216call s: GotoAsmwinOrCreateIt () 217call win_gotoid ( curwinid ) 218endif 219 220if s: GetVariablesWindow () 221let curwinid = win_getid () 222call s: GotoVariableswinOrCreateIt () 223call win_gotoid ( curwinid ) 224endif 225 226if exists ( '#User#TermdebugStartPost' ) 227doauto <nomodeline> User TermdebugStartPost 228endif 229let g: termdebug_is_running = v: true 230endfunc 231 232" Use when debugger didn't start or ended. 233func s: CloseBuffers () 234for bufnr in [ get ( s:, 'promptbufnr' , 0 ), get ( s:, 'ptybufnr' , 0 ), get ( s:, 'asmbufnr' , 0 ), get ( s:, 'varbufnr' , 0 )] 235if bufnr > 0 && bufexists ( bufnr ) 236execute $ 'bwipe! {bufnr}' 237endif 238endfor 239if exists ( 's:comm_job_id' ) 240let commbufnr = get ( nvim_get_chan_info ( s: comm_job_id ), 'buffer' , 0 ) 241if commbufnr > 0 && bufexists ( commbufnr ) 242execute $ 'bwipe! {commbufnr}' 243endif 244endif 245let s: running = v: false 246unlet ! s: gdbwin 247endfunc 248 249func s: IsGdbStarted () 250if ! s: gdb_running 251let cmd_name = string ( s: GetCommand ()[ 0 ]) 252call s: Echoerr ( $ '{cmd_name} exited unexpectedly') 253call s: CloseBuffers () 254return v: false 255endif 256return v: true 257endfunc 258 259" Open a terminal window without a job, to run the debugged program in. 260func s: StartDebug_term ( dict ) 261execute s: vertical ? 'vnew' : 'new' 262let s: pty_job_id = jobstart ( 'tail -f /dev/null;#gdb program' , { 'term' : v: true }) 263if s: pty_job_id == 0 264call s: Echoerr ( 'Invalid argument (or job table is full) while opening terminal window' ) 265return 266elseif s: pty_job_id == -1 267call s: Echoerr ( 'Failed to open the program terminal window' ) 268return 269endif 270let pty_job_info = nvim_get_chan_info ( s: pty_job_id ) 271let s: ptybufnr = pty_job_info [ 'buffer' ] 272let pty = pty_job_info [ 'pty' ] 273let s: ptywin = win_getid () 274if 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. 277exe $ ":{(&columns /2 -1)}wincmd |" 278if s: allleft 279" use the whole left column 280wincmd H 281endif 282endif 283 284" Create a hidden terminal window to communicate with gdb 285let 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 290if s: comm_job_id == 0 291call s: Echoerr ( 'Invalid argument (or job table is full) while opening communication terminal window' ) 292exe 'bwipe! ' . s: ptybufnr 293return 294elseif s: comm_job_id == -1 295call s: Echoerr ( 'Failed to open the communication terminal window' ) 296exe $ 'bwipe! {s: ptybufnr }' 297return 298endif 299let comm_job_info = nvim_get_chan_info ( s: comm_job_id ) 300let commpty = comm_job_info [ 'pty' ] 301 302let gdb_args = get ( a: dict , 'gdb_args' , []) 303let proc_args = get ( a: dict , 'proc_args' , []) 304 305let gdb_cmd = s: GetCommand () 306 307if exists ( 'g:termdebug_config' ) && has_key ( g: termdebug_config , 'command_add_args' ) 308let gdb_cmd = g: termdebug_config . command_add_args ( gdb_cmd , pty ) 309else 310" Add -quiet to avoid the intro message causing a hit-enter prompt. 311let gdb_cmd += [ '-quiet' ] 312" Disable pagination, it causes everything to stop at the gdb 313let 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). 317let gdb_cmd += [ '-iex' , 'set mi-async on' ] 318" Open a terminal window to run the debugger. 319let gdb_cmd += [ '-tty' , pty ] 320" Command executed _after_ startup is done, provides us with the necessary 321" feedback 322let gdb_cmd += [ '-ex' , 'echo startupdone\n' ] 323endif 324 325if exists ( 'g:termdebug_config' ) && has_key ( g: termdebug_config , 'command_filter' ) 326let gdb_cmd = g: termdebug_config . command_filter ( gdb_cmd ) 327endif 328 329" Adding arguments requested by the user 330let gdb_cmd += gdb_args 331 332execute 'new' 333" call ch_log($'executing "{join(gdb_cmd)}"') 334let s: gdb_job_id = jobstart ( gdb_cmd , { 'term' : v: true , 'on_exit' : function ( 's:EndTermDebug' )}) 335if s: gdb_job_id == 0 336call s: Echoerr ( 'Invalid argument (or job table is full) while opening gdb terminal window' ) 337exe 'bwipe! ' . s: ptybufnr 338return 339elseif s: gdb_job_id == -1 340call s: Echoerr ( 'Failed to open the gdb terminal window' ) 341call s: CloseBuffers () 342return 343endif 344let s: gdb_running = v: true 345let s: starting = v: true 346let gdb_job_info = nvim_get_chan_info ( s: gdb_job_id ) 347let s: gdbbufnr = gdb_job_info [ 'buffer' ] 348let s: gdbwin = win_getid () 349 350" Wait for the "startupdone" message before sending any commands. 351let try_count = 0 352while 1 353if ! s: IsGdbStarted () 354return 355endif 356 357for lnum in range ( 1 , 200 ) 358if get ( getbufline ( s: gdbbufnr , lnum ), 0 , '' ) =~ 'startupdone' 359let try_count = 9999 360break 361endif 362endfor 363let try_count += 1 364if try_count > 300 365" done or give up after five seconds 366break 367endif 368sleep 10m 369endwhile 370 371" Set arguments to be run. 372if ! empty ( proc_args ) 373call chansend ( s: gdb_job_id , $ "server set args {join(proc_args)}\r") 374endif 375 376" Connect gdb to the communication pty, using the GDB/MI interface. 377" Prefix "server" to avoid adding this to the history. 378call 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. 382let try_count = 0 383while 1 384if ! s: IsGdbStarted () 385return 386endif 387 388let response = '' 389for lnum in range ( 1 , 200 ) 390let line1 = get ( getbufline ( s: gdbbufnr , lnum ), 0 , '' ) 391let line2 = get ( getbufline ( s: gdbbufnr , lnum + 1 ), 0 , '' ) 392if line1 =~ 'new-ui mi ' 393" response can be in the same line or the next line 394let response = line1 . line2 395if response =~ 'Undefined command' 396call s: Echoerr ( 'Sorry, your gdb is too old, gdb 7.12 is required' ) 397" CHECKME: possibly send a "server show version" here 398call s: CloseBuffers () 399return 400endif 401if response =~ 'New UI allocated' 402" Success! 403break 404endif 405elseif line1 =~ 'Reading symbols from' && line2 !~ 'new-ui mi ' 406" Reading symbols might take a while, try more times 407let try_count -= 1 408endif 409endfor 410if response =~ 'New UI allocated' 411break 412endif 413let try_count += 1 414if try_count > 100 415call s: Echoerr ( 'Cannot check if your gdb works, continuing anyway' ) 416break 417endif 418sleep 10m 419endwhile 420 421let s: starting = v: false 422 423" Set the filetype, this can be used to add mappings. 424set filetype = termdebug 425 426call s: StartDebugCommon ( a: dict ) 427endfunc 428 429" Open a window with a prompt buffer to run gdb in. 430func s: StartDebug_prompt ( dict ) 431if s: vertical 432vertical new 433else 434new 435endif 436let s: gdbwin = win_getid () 437let s: promptbufnr = bufnr ( '' ) 438call prompt_setprompt ( s: promptbufnr , 'gdb> ' ) 439set buftype = prompt 440 441if empty ( glob ( 'gdb' )) 442file gdb 443elseif empty ( glob ( 'Termdebug-gdb-console' )) 444file Termdebug-gdb-console 445else 446call 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." ) 449endif 450 451call prompt_setcallback ( s: promptbufnr , function ( 's:PromptCallback' )) 452call prompt_setinterrupt ( s: promptbufnr , function ( 's:PromptInterrupt' )) 453 454if 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. 457exe $ ":{(&columns /2 -1)}wincmd |" 458endif 459 460let gdb_args = get ( a: dict , 'gdb_args' , []) 461let proc_args = get ( a: dict , 'proc_args' , []) 462 463let gdb_cmd = s: GetCommand () 464" Add -quiet to avoid the intro message causing a hit-enter prompt. 465let gdb_cmd += [ '-quiet' ] 466" Disable pagination, it causes everything to stop at the gdb, needs to be run early 467let 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). 471let gdb_cmd += [ '-iex' , 'set mi-async on' ] 472" directly communicate via mi2 473let gdb_cmd += [ '--interpreter=mi2' ] 474 475" Adding arguments requested by the user 476let gdb_cmd += gdb_args 477 478" call ch_log($'executing "{join(gdb_cmd)}"') 479let 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 \}) 483if s: gdbjob == 0 484call s: Echoerr ( 'Invalid argument (or job table is full) while starting gdb job' ) 485if s: promptbufnr > 0 && bufexists ( s: promptbufnr ) 486exe $ 'bwipe! {s: promptbufnr }' 487endif 488return 489elseif s: gdbjob == -1 490call s: Echoerr ( 'Failed to start the gdb job' ) 491call s: CloseBuffers () 492return 493endif 494exe $ 'auBufUnload <buffer={s: promptbufnr }> ++once call jobstop(s: gdbjob )' 495 496let s: ptybufnr = 0 497if has ( 'win32' ) 498" MS-Windows: run in a new console window for maximum compatibility 499call s: SendCommand ( 'set new-console on' ) 500else 501" Unix: Run the debugged program in a terminal window. Open it below the 502" gdb window. 503belowright new 504let s: pty_job_id = jobstart ( 'tail -f /dev/null;#gdb program' , { 'term' : v: true }) 505if s: pty_job_id == 0 506call s: Echoerr ( 'Invalid argument (or job table is full) while opening terminal window' ) 507return 508elseif s: pty_job_id == -1 509call s: Echoerr ( 'Failed to open the program terminal window' ) 510return 511endif 512let pty_job_info = nvim_get_chan_info ( s: pty_job_id ) 513let s: ptybufnr = pty_job_info [ 'buffer' ] 514let pty = pty_job_info [ 'pty' ] 515let s: ptywin = win_getid () 516call 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. 520call s: SendCommand ( 'set env TERM = xterm-color' ) 521call s: SendCommand ( $ 'set envROWS = {winheight(s: ptywin )} ') 522call s: SendCommand ( $ 'set envLINES = {winheight(s: ptywin )} ') 523call s: SendCommand ( $ 'set envCOLUMNS = {winwidth(s: ptywin )} ') 524call s: SendCommand ( $ 'set envCOLORS = {&t_Co}') 525call s: SendCommand ( $ 'set envVIM_TERMINAL = {v: version } ') 526endif 527call s: SendCommand ( 'set print pretty on' ) 528call s: SendCommand ( 'set breakpoint pending on' ) 529 530" Set arguments to be run 531if ! empty ( proc_args ) 532call s: SendCommand ( $ 'set args {join(proc_args)}') 533endif 534 535call s: StartDebugCommon ( a: dict ) 536startinsert 537endfunc 538 539func s: StartDebugCommon ( dict ) 540" Sign used to highlight the line where the program has stopped. 541" There can be only one. 542call sign_define ( 'debugPC' , #{ linehl : 'debugPC' }) 543 544" Install debugger commands in the text window. 545call win_gotoid ( s: sourcewin ) 546call s: InstallCommands () 547call 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}} 556let 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. 560let s: breakpoint_locations = {} 561 562augroup TermDebug 563au BufRead * call s: BufRead () 564au BufUnload * call s: BufUnloaded () 565au OptionSet background call s: Highlight ( 0 , v: option_old , v: option_new ) 566augroup END 567 568" Run the command if the bang attribute was given and got to the debug 569" window. 570if get ( a: dict , 'bang' , 0 ) 571call s: SendResumingCommand ( '-exec-run' ) 572call win_gotoid ( s: ptywin ) 573endif 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}') 579if s: way == 'prompt' 580call chansend ( s: gdbjob , $ "{a:cmd}\n") 581else 582call chansend ( s: comm_job_id , $ "{a:cmd}\r") 583endif 584endfunc 585 586func s: StopCommand () 587if s: way == 'prompt' 588call s: PromptInterrupt () 589else 590call s: SendCommand ( '-exec-interrupt' ) 591endif 592endfunc 593 594func s: ContinueCommand () 595if s: way == 'prompt' 596call s: SendCommand ( 'continue' ) 597else 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') 601call chansend ( s: gdb_job_id , "continue\r" ) 602endif 603endfunc 604 605" This is global so that a user can create their mappings with this. 606func TermDebugSendCommand ( cmd ) 607if s: way == 'prompt' 608call chansend ( s: gdbjob , $ "{a:cmd}\n") 609else 610let do_continue = 0 611if ! s: stopped 612let do_continue = 1 613if s: way == 'prompt' 614" Need to send a signal to get the UI to listen. Strangely this is only 615" needed once. 616call jobstop ( s: gdbjob ) 617else 618Stop 619endif 620sleep 10m 621endif 622" TODO: should we prepend CTRL-U to clear the command? 623call chansend ( s: gdb_job_id , $ "{a:cmd}\r") 624if do_continue 625Continue 626endif 627endif 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 ) 634if s: stopped 635" reset s:stopped here, it may take a bit of time before we get a response 636let s: stopped = v: false 637" call ch_log('assume that program is running after this command') 638call s: SendCommand ( a: cmd ) 639" else 640" call ch_log($'dropping command, program is running: {a:cmd}') 641endif 642endfunc 643 644" Function called when entering a line in the prompt buffer. 645func s: PromptCallback ( text ) 646call 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') 653if 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. 656if s: pid == 0 657call s: Echoerr ( 'Cannot interrupt gdb, did not find a process ID' ) 658else 659call debugbreak ( s: pid ) 660endif 661else 662call v: lua . vim . uv . kill ( jobpid ( s: gdbjob ), 'sigint' ) 663endif 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 671let eof = ( a: data == [ '' ]) 672let msgs = a: data 673let msgs [ 0 ] = self . last_line .. msgs [ 0 ] 674if eof 675let self . last_line = '' 676else 677let self . last_line = msgs [ -1 ] 678unlet msgs [ -1 ] 679endif 680call 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 687let comm_msgs = [] 688let lines = [] 689 690for msg in a: msgs 691" Disassembly messages need to be forwarded as-is. 692if s: parsing_disasm_msg || msg =~ '^&"disassemble' 693call s: CommOutput ( a: job_id , [ msg ], a: event ) 694continue 695endif 696 697" Drop the gdb prompt, we have our own. 698" Drop status and echo'd commands. 699if msg == '(gdb) ' || msg == '^done' || msg [ 0 ] == '&' 700continue 701endif 702 703if msg =~ '^\^error,msg=' 704if 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. 708unlet s: evalexpr 709continue 710endif 711elseif msg [ 0 ] == '~' 712call add ( lines , s: DecodeMessage ( msg [ 1 :], v: false )) 713continue 714endif 715 716call add ( comm_msgs , msg ) 717endfor 718 719let curwinid = win_getid () 720call win_gotoid ( s: gdbwin ) 721 722" Add the output above the current prompt. 723for line in lines 724" Nvim supports multi-line input in prompt-buffer, so the prompt line is 725" not always the last line. 726call append ( line ( "':" ) - 1 , line ) 727endfor 728if ! empty ( lines ) 729set modified 730endif 731 732call win_gotoid ( curwinid ) 733call 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 ) 745if a: quotedText [ 0 ] != '"' 746call s: Echoerr ( $ 'DecodeMessage(): missing quote in {a:quotedText}') 747return 748endif 749let 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') 763if ! a: literal 764return msg 765 \ ->substitute ( '\\t' , "\t" , 'g' ) 766 \ ->substitute ( '\\n' , '' , 'g' ) 767else 768return msg 769endif 770endfunc 771const s: NullRepl = 'XXXNULLXXX' 772 773" Extract the "name" value from a gdb message with fullname="name". 774func s: GetFullname ( msg ) 775if a: msg !~ 'fullname' 776return '' 777endif 778let name = s: DecodeMessage ( substitute ( a: msg , '.*fullname=' , '' , '' ), v: true ) 779if has ( 'win32' ) && name =~ ':\\\\' 780" sometimes the name arrives double-escaped 781let name = substitute ( name , '\\\\' , '\\' , 'g' ) 782endif 783return name 784endfunc 785 786" Extract the "addr" value from a gdb message with addr="0x0001234". 787func s: GetAsmAddr ( msg ) 788if a: msg !~ 'addr=' 789return '' 790endif 791let addr = s: DecodeMessage ( substitute ( a: msg , '.*addr=' , '' , '' ), v: false ) 792return addr 793endfunc 794 795func s: EndTermDebug ( job_id , exit_code , event ) 796let s: gdb_running = v: false 797if s: starting 798return 799endif 800 801if exists ( '#User#TermdebugStopPre' ) 802doauto <nomodeline> User TermdebugStopPre 803endif 804 805unlet s: gdbwin 806call s: EndDebugCommon () 807endfunc 808 809func s: EndDebugCommon () 810let curwinid = win_getid () 811call s: CloseBuffers () 812 813" Restore 'signcolumn' in all buffers for which it was set. 814call win_gotoid ( s: sourcewin ) 815let was_buf = bufnr () 816for bufnr in s: signcolumn_buflist 817if bufexists ( bufnr ) 818exe $ ":{bufnr}buf" 819if exists ( 'b:save_signcolumn' ) 820let & signcolumn = b: save_signcolumn 821unlet b: save_signcolumn 822endif 823endif 824endfor 825if bufexists ( was_buf ) 826exe $ ":{was_buf}buf" 827endif 828 829call s: DeleteCommands () 830 831call win_gotoid ( curwinid ) 832 833if s: saved_columns > 0 834let & columns = s: saved_columns 835endif 836 837if exists ( '#User#TermdebugStopPost' ) 838doauto <nomodeline> User TermdebugStopPost 839endif 840 841au ! TermDebug 842let g: termdebug_is_running = v: false 843endfunc 844 845func s: EndPromptDebug ( job_id , exit_code , event ) 846if exists ( '#User#TermdebugStopPre' ) 847doauto <nomodeline> User TermdebugStopPre 848endif 849 850call s: EndDebugCommon () 851unlet ! 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 ) 868if a: msg =~ '^\^done' 869let curwinid = win_getid () 870if win_gotoid ( s: asmwin ) 871silent ! %delete _ 872call setline ( 1 , s: asm_lines ) 873set nomodified 874set filetype = asm 875 876let lnum = search ( $ '^{s: asm_addr } ') 877if lnum != 0 878call sign_unplace ( 'TermDebug' , #{ id : s: asm_id }) 879call sign_place ( s: asm_id , 'TermDebug' , 'debugPC' , '%' , #{ lnum : lnum }) 880endif 881 882call win_gotoid ( curwinid ) 883endif 884 885let s: parsing_disasm_msg = 0 886let s: asm_lines = [] 887elseif a: msg =~ '^\^error,msg=' 888if 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 892call s: SendCommand ( 'disassemble $pc,+100' ) 893endif 894let s: parsing_disasm_msg = 0 895elseif a: msg =~ '^&"disassemble \$pc' 896if a: msg =~ '+100' 897" This is our second disasm attempt 898let s: parsing_disasm_msg = 2 899endif 900elseif a: msg !~ '^&"disassemble' 901let value = substitute ( a: msg , '^\~\"[ ]*' , '' , '' ) 902let value = substitute ( value , '^=>[ ]*' , '' , '' ) 903" Nvim already trims the final "\r" in s:CommOutput() 904" let value = substitute(value, '\\n\"\r$', '', '') 905let value = substitute ( value , '\\n\"$' , '' , '' ) 906let value = substitute ( value , '\r' , '' , '' ) 907let value = substitute ( value , '\\t' , ' ' , 'g' ) 908 909if value != '' || ! empty ( s: asm_lines ) 910call add ( s: asm_lines , value ) 911endif 912endif 913endfunc 914 915func s: ParseVarinfo ( varinfo ) 916let dict = {} 917let nameIdx = matchstrpos ( a: varinfo , '{name="\([^"]*\)"' ) 918let dict [ 'name' ] = a: varinfo [ nameIdx [ 1 ] + 7 : nameIdx [ 2 ] - 2 ] 919let typeIdx = matchstrpos ( a: varinfo , ',type="\([^"]*\)"' ) 920" 'type' maybe is a url-like string, 921" try to shorten it and show only the /tail 922let dict [ 'type' ] = ( a: varinfo [ typeIdx [ 1 ] + 7 : typeIdx [ 2 ] - 2 ]) ->fnamemodify ( ':t' ) 923let valueIdx = matchstrpos ( a: varinfo , ',value="\(.*\)"}' ) 924if valueIdx [ 1 ] == -1 925let dict [ 'value' ] = 'Complex value' 926else 927let dict [ 'value' ] = a: varinfo [ valueIdx [ 1 ] + 8 : valueIdx [ 2 ] - 3 ] 928endif 929return dict 930endfunc 931 932func s: HandleVariablesMsg ( msg ) 933let curwinid = win_getid () 934if win_gotoid ( s: varwin ) 935 936silent ! %delete _ 937let spaceBuffer = 20 938let spaces = repeat ( ' ' , 16 ) 939call setline ( 1 , $ 'Type{spaces}Name{spaces}Value') 940let cnt = 1 941let capture = '{name=".\{-}",\%(arg=".\{-}",\)\{0,1\}type=".\{-}"\%(,value=".\{-}"\)\{0,1\}}' 942let varinfo = matchstr ( a: msg , capture , 0 , cnt ) 943while varinfo != '' 944let vardict = s: ParseVarinfo ( varinfo ) 945call 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' ]) 950let cnt += 1 951let varinfo = matchstr ( a: msg , capture , 0 , cnt ) 952endwhile 953endif 954call win_gotoid ( curwinid ) 955endfunc 956 957func s: CommOutput ( job_id , msgs , event ) 958for msg in a: msgs 959" Nvim job lines are split on "\n", so trim a suffixed CR. 960if msg [ -1 :] == "\r" 961let msg = msg [: -2 ] 962endif 963 964if s: parsing_disasm_msg 965call s: HandleDisasmMsg ( msg ) 966elseif msg != '' 967if msg =~ '^\(\*stopped\|\*running\|=thread-selected\)' 968call s: HandleCursor ( msg ) 969elseif msg =~ '^\^done,bkpt=' || msg =~ '^=breakpoint-created,' 970call s: HandleNewBreakpoint ( msg , 0 ) 971elseif msg =~ '^=breakpoint-modified,' 972call s: HandleNewBreakpoint ( msg , 1 ) 973elseif msg =~ '^=breakpoint-deleted,' 974call s: HandleBreakpointDelete ( msg ) 975elseif msg =~ '^=thread-group-started' 976call s: HandleProgramRun ( msg ) 977elseif msg =~ '^\^done,value=' 978call s: HandleEvaluate ( msg ) 979elseif msg =~ '^\^error,msg=' 980call s: HandleError ( msg ) 981elseif msg =~ '^&"disassemble' 982let s: parsing_disasm_msg = 1 983let s: asm_lines = [] 984call s: HandleDisasmMsg ( msg ) 985elseif msg =~ '^\^done,variables=' 986call s: HandleVariablesMsg ( msg ) 987endif 988endif 989endfor 990endfunc 991 992func s: GotoProgram () 993if has ( 'win32' ) 994if executable ( 'powershell' ) 995call system ( printf ( 'powershell -Command "add-type -AssemblyName microsoft.VisualBasic;[Microsoft.VisualBasic.Interaction]::AppActivate(%d);"' , s: pid )) 996endif 997else 998call win_gotoid ( s: ptywin ) 999endif 1000endfunc 1001 1002" Install commands in the current window to control the debugger. 1003func s: InstallCommands () 1004let save_cpo = & cpo 1005set cpo & vim 1006 1007command -nargs = ? Break call s:SetBreakpoint(<q-args>) 1008command -nargs = ? Tbreak call s:SetBreakpoint(<q-args>, v:true) 1009command ToggleBreak call s:ToggleBreak() 1010command Clear call s:ClearBreakpoint() 1011command Step call s:SendResumingCommand('-exec-step') 1012command Over call s:SendResumingCommand('-exec-next') 1013command -nargs = ? Until call s:Until(<q-args>) 1014command Finish call s:SendResumingCommand('-exec-finish') 1015command -nargs = * Run call s:Run(<q-args>) 1016command -nargs = * Arguments call s:SendResumingCommand('-exec-arguments ' . <q-args>) 1017command Stop call s:StopCommand() 1018command Continue call s:ContinueCommand() 1019command RunOrContinue call s:RunOrContinue() 1020 1021command -nargs = * Frame call s:Frame(<q-args>) 1022command -count = 1 Up call s:Up(<count>) 1023command -count = 1 Down call s:Down(<count>) 1024 1025command -range -nargs = * Evaluate call s:Evaluate(<range>, <q-args>) 1026command Gdb call win_gotoid(s:gdbwin) 1027command Program call s:GotoProgram() 1028command Source call s:GotoSourcewinOrCreateIt() 1029command Asm call s:GotoAsmwinOrCreateIt() 1030command Var call s:GotoVariableswinOrCreateIt() 1031command Winbar call s:InstallWinbar(1) 1032 1033let map = 1 1034if exists ( 'g:termdebug_config' ) 1035let map = get ( g: termdebug_config , 'map_K' , 1 ) 1036elseif exists ( 'g:termdebug_map_K' ) 1037let map = g: termdebug_map_K 1038endif 1039if map 1040let s: saved_K_map = maparg ( 'K' , 'n' , 0 , 1 ) 1041if ! empty ( s: saved_K_map ) && ! s: saved_K_map . buffer || empty ( s: saved_K_map ) 1042nnoremap K :Evaluate< CR > 1043endif 1044endif 1045 1046let map = 1 1047if exists ( 'g:termdebug_config' ) 1048let map = get ( g: termdebug_config , 'map_plus' , 1 ) 1049endif 1050if map 1051let s: saved_plus_map = maparg ( '+' , 'n' , 0 , 1 ) 1052if ! empty ( s: saved_plus_map ) && ! s: saved_plus_map . buffer || empty ( s: saved_plus_map ) 1053 nnoremap<expr> +$ '<Cmd>{v:count1}Up<CR>' 1054endif 1055endif 1056 1057let map = 1 1058if exists ( 'g:termdebug_config' ) 1059let map = get ( g: termdebug_config , 'map_minus' , 1 ) 1060endif 1061if map 1062let s: saved_minus_map = maparg ( '-' , 'n' , 0 , 1 ) 1063if ! empty ( s: saved_minus_map ) && ! s: saved_minus_map . buffer || empty ( s: saved_minus_map ) 1064 nnoremap<expr> -$ '<Cmd>{v:count1}Down<CR>' 1065endif 1066endif 1067 1068 1069if has ( 'menu' ) && & mouse != '' 1070call s: InstallWinbar ( 0 ) 1071 1072let popup = 1 1073if exists ( 'g:termdebug_config' ) 1074let popup = get ( g: termdebug_config , 'popup' , 1 ) 1075elseif exists ( 'g:termdebug_popup' ) 1076let popup = g: termdebug_popup 1077endif 1078if popup 1079let s: saved_mousemodel = & mousemodel 1080let & mousemodel = 'popup_setpos' 1081an 1.200 PopUp.-SEP3- <Nop> 1082an 1.210 PopUp.Set\ breakpoint :Break<CR> 1083an 1.220 PopUp.Clear\ breakpoint :Clear<CR> 1084an 1.230 PopUp.Run\ until :Until<CR> 1085an 1.240 PopUp.Evaluate :Evaluate<CR> 1086endif 1087endif 1088 1089let & 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 () 1109delcommand Break 1110delcommand Tbreak 1111delcommand Clear 1112delcommand Step 1113delcommand Over 1114delcommand Until 1115delcommand Finish 1116delcommand Run 1117delcommand Arguments 1118delcommand Stop 1119delcommand Continue 1120delcommand Frame 1121delcommand Up 1122delcommand Down 1123delcommand Evaluate 1124delcommand Gdb 1125delcommand Program 1126delcommand Source 1127delcommand Asm 1128delcommand Var 1129delcommand Winbar 1130delcommand RunOrContinue 1131delcommand ToggleBreak 1132 1133if exists ( 's:saved_K_map' ) 1134if ! empty ( s: saved_K_map ) && ! s: saved_K_map . buffer 1135nunmap K 1136call mapset ( s: saved_K_map ) 1137elseif empty ( s: saved_K_map ) 1138nunmap K 1139endif 1140unlet s: saved_K_map 1141endif 1142if exists ( 's:saved_plus_map' ) 1143if ! empty ( s: saved_plus_map ) && ! s: saved_plus_map . buffer 1144nunmap + 1145call mapset ( s: saved_plus_map ) 1146elseif empty ( s: saved_plus_map ) 1147nunmap + 1148endif 1149unlet s: saved_plus_map 1150endif 1151if exists ( 's:saved_minus_map' ) 1152if ! empty ( s: saved_minus_map ) && ! s: saved_minus_map . buffer 1153nunmap - 1154call mapset ( s: saved_minus_map ) 1155elseif empty ( s: saved_minus_map ) 1156nunmap - 1157endif 1158unlet s: saved_minus_map 1159endif 1160 1161if 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 1177if exists ( 's:saved_mousemodel' ) 1178let & mousemodel = s: saved_mousemodel 1179unlet s: saved_mousemodel 1180aunmenu PopUp.-SEP3- 1181aunmenu PopUp.Set\ breakpoint 1182aunmenu PopUp.Clear\ breakpoint 1183aunmenu PopUp.Run\ until 1184aunmenu PopUp.Evaluate 1185endif 1186endif 1187 1188call sign_unplace ( 'TermDebug' ) 1189unlet s: breakpoints 1190unlet s: breakpoint_locations 1191 1192call sign_undefine ( 'debugPC' ) 1193call sign_undefine ( s: BreakpointSigns ->map ( "'debugBreakpoint' .. v:val" )) 1194let 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. 1200return printf ( '"%s"' , a: x ->substitute ( '[\\"]' , '\\&' , 'g' )) 1201endfunc 1202 1203func s: DefaultBreakpointLocation () 1204" Use the fname:lnum format, older gdb can't handle --source. 1205return s: QuoteArg ( $ "{expand('%:p')}:{line('.')}") 1206endfunc 1207 1208func s: TokenizeBreakpointArguments ( args ) 1209let tokens = [] 1210let start = -1 1211let escaped = v: false 1212let in_quotes = v: false 1213 1214let i = 0 1215for ch in a: args 1216if start < 0 && ch !~# '\s' 1217let start = i 1218endif 1219if start >= 0 1220if escaped 1221let escaped = v: false 1222elseif ch ==# '\' 1223let escaped = v: true 1224elseif ch ==# '"' 1225let in_quotes = ! in_quotes 1226elseif ! in_quotes && ch =~# '\s' 1227eval tokens ->add (#{ text : a: args ->slice ( start , i ), start : start , end : i - 1 }) 1228let start = -1 1229endif 1230endif 1231let i += 1 1232endfor 1233 1234if start >= 0 1235eval tokens ->add (#{ text : a: args ->slice ( start ), start : start , end : i - 1 }) 1236endif 1237return tokens 1238endfunc 1239 1240func s: BuildBreakpointCommand ( at , tbreak ) 1241let args = trim ( a: at ) 1242let cmd = '-break-insert' 1243if a: tbreak 1244let cmd ..= ' -t' 1245endif 1246 1247if empty ( args ) 1248return $ '{cmd} {s: DefaultBreakpointLocation ()} ' 1249endif 1250 1251let condition = '' 1252let prefix = args 1253for token in s: TokenizeBreakpointArguments ( args ) 1254if token . text ==# 'if' && token . end < strchars ( args ) - 1 1255let condition = trim ( args ->slice ( token . end + 1 )) 1256let prefix = token . start > 0 ? trim ( args ->slice ( 0 , token . start )) : '' 1257break 1258endif 1259endfor 1260 1261let prefix_tokens = s: TokenizeBreakpointArguments ( prefix ) 1262let location = prefix 1263let thread = '' 1264if len ( prefix_tokens ) >= 2 1265 \&& prefix_tokens [ -2 ]. text ==# 'thread' 1266 \&& prefix_tokens [ -1 ]. text =~# '^\d\+$' 1267let thread = prefix_tokens [ -1 ]. text 1268let location = join ( prefix_tokens [: -3 ] ->mapnew ( 'v:val.text' ), ' ' ) 1269endif 1270 1271if empty ( trim ( location )) 1272let location = s: DefaultBreakpointLocation () 1273endif 1274if ! empty ( thread ) 1275let cmd ..= $ ' -p {thread}' 1276endif 1277if ! empty ( condition ) 1278let cmd ..= $ ' -c {s: QuoteArg ( condition )} ' 1279endif 1280return $ '{cmd} {trim(location)}' 1281endfunc 1282 1283" :Until - Execute until past a specified position or current line 1284func s: Until ( at ) 1285if s: stopped 1286" reset s:stopped here, it may take a bit of time before we get a response 1287let s: stopped = v: false 1288" call ch_log('assume that program is running after this command') 1289" Use the fname:lnum format 1290let at = empty ( a: at ) ?s: QuoteArg ( $ "{expand('%:p')}:{line('.')}") : a:at 1291call s: SendCommand ( $ '-exec-until {at}') 1292" else 1293" call ch_log('dropping command, program is running: exec-until') 1294endif 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. 1301let do_continue = 0 1302if ! s: stopped 1303let do_continue = 1 1304Stop 1305sleep 10m 1306endif 1307 1308let cmd = s: BuildBreakpointCommand ( a: at , a: tbreak ) 1309call s: SendCommand ( cmd ) 1310if do_continue 1311Continue 1312endif 1313endfunc 1314 1315" :Clear - Delete a breakpoint at the cursor position. 1316func s: ClearBreakpoint () 1317let fname = fnameescape ( expand ( '%:p' )) 1318let lnum = line ( '.' ) 1319let bploc = printf ( '%s:%d' , fname , lnum ) 1320if has_key ( s: breakpoint_locations , bploc ) 1321let idx = 0 1322let nr = 0 1323for id in s: breakpoint_locations [ bploc ] 1324if has_key ( s: breakpoints , id ) 1325" Assume this always works, the reply is simply "^done". 1326call s: SendCommand ( $ '-break-delete {id}') 1327for subid in keys ( s: breakpoints [ id ]) 1328call sign_unplace ( 'TermDebug' , 1329 \#{ id : s: Breakpoint2SignNumber ( id , subid )}) 1330endfor 1331unlet s: breakpoints [ id ] 1332unlet s: breakpoint_locations [ bploc ][ idx ] 1333let nr = id 1334break 1335else 1336let idx += 1 1337endif 1338endfor 1339if nr != 0 1340if empty ( s: breakpoint_locations [ bploc ]) 1341unlet s: breakpoint_locations [ bploc ] 1342endif 1343echomsg $ 'Breakpoint {nr} cleared from line {lnum}.' 1344else 1345call s: Echoerr ( $ 'Internal error trying to remove breakpoint at line {lnum}!') 1346endif 1347else 1348echomsg $ 'No breakpoint to remove at line {lnum}.' 1349endif 1350endfunc 1351 1352func s: ToggleBreak () 1353let fname = fnameescape ( expand ( '%:p' )) 1354let lnum = line ( '.' ) 1355let bploc = printf ( '%s:%d' , fname , lnum ) 1356if has_key ( s: breakpoint_locations , bploc ) 1357while has_key ( s: breakpoint_locations , bploc ) 1358call s: ClearBreakpoint () 1359endwhile 1360else 1361call s: SetBreakpoint ( "" ) 1362endif 1363endfunc 1364 1365func s: Run ( args ) 1366if a: args != '' 1367call s: SendResumingCommand ( $ '-exec-arguments {a:args}') 1368endif 1369call s: SendResumingCommand ( '-exec-run' ) 1370endfunc 1371 1372func s: RunOrContinue () 1373if s: running 1374call s: ContinueCommand () 1375else 1376call s: Run ( '' ) 1377endif 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 1387if a: arg =~ '^\d\+$' || a: arg == '' 1388" specify frame by number 1389call s: SendCommand ( $ '-interpreter-exec mi "frame {a:arg}"') 1390elseif a: arg =~ '^0x[0-9a-fA-F]\+$' 1391" specify frame by stack address 1392call s: SendCommand ( $ '-interpreter-exec mi "frame address {a:arg}"') 1393else 1394" specify frame by function name 1395call s: SendCommand ( $ '-interpreter-exec mi "framefunction {a:arg}"') 1396endif 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 1402call 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 1408call 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 1413if a: expr =~ "[=!<>]=" 1414let exprLHS = a: expr 1415else 1416" remove text that is likely an assignment 1417let exprLHS = substitute ( a: expr , ' *=.*' , '' , '' ) 1418endif 1419 1420" encoding expression to prevent bad errors 1421let expr_escaped = a: expr 1422 \ ->substitute ( '\\' , '\\\\' , 'g' ) 1423 \ ->substitute ( '"' , '\\"' , 'g' ) 1424call s: SendCommand ( $ '-data-evaluate-expression "{expr_escaped}"') 1425let s: evalexpr = exprLHS 1426endfunc 1427 1428" :Evaluate - evaluate what is specified / under the cursor 1429func s: Evaluate ( range , arg ) 1430if s: eval_float_win_id > 0 && nvim_win_is_valid ( s: eval_float_win_id ) 1431 \&& a: range == 0 && empty ( a: arg ) 1432call nvim_set_current_win ( s: eval_float_win_id ) 1433return 1434endif 1435let expr = s: GetEvaluationExpression ( a: range , a: arg ) 1436let s: evalFromBalloonExpr = v: true 1437let s: evalFromBalloonExprResult = '' 1438let s: ignoreEvalError = v: false 1439call s: SendEval ( expr ) 1440endfunc 1441 1442" get what is specified / under the cursor 1443func s: GetEvaluationExpression ( range , arg ) 1444if a: arg != '' 1445" user supplied evaluation 1446let expr = s: CleanupExpr ( a: arg ) 1447let expr = substitute ( expr , '"\([^"]*\)": *' , '\1=' , 'g' ) 1448elseif a: range == 2 1449let pos = getcurpos () 1450let reg = getreg ( 'v' , 1 , 1 ) 1451let regt = getregtype ( 'v' ) 1452normal ! gv"vy 1453let expr = s: CleanupExpr ( @v) 1454call setpos ( '.' , pos ) 1455call setreg ( 'v' , reg , regt ) 1456let s: evalFromBalloonExpr = v: true 1457else 1458" no evaluation provided: get from C-expression under cursor 1459" TODO: allow filetype specific lookup #9057 1460let expr = expand ( '<cexpr>' ) 1461let s: evalFromBalloonExpr = v: true 1462endif 1463return 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/... 1472let expr = substitute ( a: expr , '\_s' , ' ' , 'g' ) 1473 1474if & 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 1479let expr = substitute ( expr , ';' , ' ' , 'g' ) 1480let expr = substitute ( expr , '[,.]\+ *$' , '' , '' ) 1481endif 1482 1483" get rid of leading and trailing spaces 1484let expr = substitute ( expr , '^ *' , '' , '' ) 1485let expr = substitute ( expr , ' *$' , '' , '' ) 1486return 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 ) 1497let 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', '') 1511if s: evalFromBalloonExpr 1512if s: evalFromBalloonExprResult == '' 1513let s: evalFromBalloonExprResult = $ '{s: evalexpr } : {value}' 1514else 1515let s: evalFromBalloonExprResult ..= $ ' = {value}' 1516endif 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. 1525let s: eval_float_win_id = luaeval ( 'select(2, vim.lsp.util.open_floating_preview(_A))' , split ( s: evalFromBalloonExprResult , '\\n' )) 1526else 1527echomsg $ '"{s: evalexpr }": {value}' 1528endif 1529 1530if s: evalexpr [ 0 ] != '*' && value =~ '^0x' && value != '0x0' && value !~ '"$' 1531" Looks like a pointer, also display what it points to. 1532let s: ignoreEvalError = v: true 1533call s: SendEval ( $ '*{s: evalexpr } ') 1534endif 1535endfunc 1536 1537" Handle an error. 1538func s: HandleError ( msg ) 1539if s: ignoreEvalError 1540" Result of s:SendEval() failed, ignore. 1541let s: ignoreEvalError = v: false 1542let s: evalFromBalloonExpr = v: false 1543return 1544endif 1545let msgVal = substitute ( a: msg , '.*msg="\(.*\)"' , '\1' , '' ) 1546call s: Echoerr ( substitute ( msgVal , '\\"' , '"' , 'g' )) 1547endfunc 1548 1549func s: GotoSourcewinOrCreateIt () 1550if ! win_gotoid ( s: sourcewin ) 1551new 1552let s: sourcewin = win_getid () 1553call s: InstallWinbar ( 0 ) 1554endif 1555endfunc 1556 1557func s: GetDisasmWindow () 1558if exists ( 'g:termdebug_config' ) 1559return get ( g: termdebug_config , 'disasm_window' , 0 ) 1560endif 1561if exists ( 'g:termdebug_disasm_window' ) 1562return g: termdebug_disasm_window 1563endif 1564return 0 1565endfunc 1566 1567func s: GetDisasmWindowHeight () 1568if exists ( 'g:termdebug_config' ) 1569return get ( g: termdebug_config , 'disasm_window_height' , 0 ) 1570endif 1571if exists ( 'g:termdebug_disasm_window' ) && g: termdebug_disasm_window > 1 1572return g: termdebug_disasm_window 1573endif 1574return 0 1575endfunc 1576 1577func s: GotoAsmwinOrCreateIt () 1578if ! win_gotoid ( s: asmwin ) 1579let mdf = '' 1580if win_gotoid ( s: sourcewin ) 1581" 60 is approx spaceBuffer * 3 1582if winwidth ( 0 ) > ( 78 + 60 ) 1583let mdf = 'vert' 1584exe $ '{mdf} :60new' 1585else 1586exe 'rightbelow new' 1587endif 1588else 1589exe 'new' 1590endif 1591 1592let s: asmwin = win_getid () 1593 1594setlocal nowrap 1595setlocal number 1596setlocal noswapfile 1597setlocal buftype = nofile 1598setlocal bufhidden = wipe 1599setlocal signcolumn = no 1600setlocal modifiable 1601 1602if s: asmbufnr > 0 && bufexists ( s: asmbufnr ) 1603exe $ 'buffer {s: asmbufnr }' 1604elseif empty ( glob ( 'Termdebug-asm-listing' )) 1605silent file Termdebug-asm-listing 1606let s: asmbufnr = bufnr ( 'Termdebug-asm-listing' ) 1607else 1608call s: Echoerr ( "You have a file/folder named 'Termdebug-asm-listing'. 1609\ Please exit and rename it because Termdebug may not work as expected." ) 1610endif 1611 1612if mdf != 'vert' && s: GetDisasmWindowHeight () > 0 1613exe $ 'resize {s: GetDisasmWindowHeight () }' 1614endif 1615endif 1616 1617if s: asm_addr != '' 1618let lnum = search ( $ '^{s: asm_addr } ') 1619if lnum == 0 1620if s: stopped 1621call s: SendCommand ( 'disassemble $pc' ) 1622endif 1623else 1624call sign_unplace ( 'TermDebug' , #{ id : s: asm_id }) 1625call sign_place ( s: asm_id , 'TermDebug' , 'debugPC' , '%' , #{ lnum : lnum }) 1626endif 1627endif 1628endfunc 1629 1630func s: GetVariablesWindow () 1631if exists ( 'g:termdebug_config' ) 1632return get ( g: termdebug_config , 'variables_window' , 0 ) 1633endif 1634if exists ( 'g:termdebug_disasm_window' ) 1635return g: termdebug_variables_window 1636endif 1637return 0 1638endfunc 1639 1640func s: GetVariablesWindowHeight () 1641if exists ( 'g:termdebug_config' ) 1642return get ( g: termdebug_config , 'variables_window_height' , 0 ) 1643endif 1644if exists ( 'g:termdebug_variables_window' ) && g: termdebug_variables_window > 1 1645return g: termdebug_variables_window 1646endif 1647return 0 1648endfunc 1649 1650func s: GotoVariableswinOrCreateIt () 1651if ! win_gotoid ( s: varwin ) 1652let mdf = '' 1653if win_gotoid ( s: sourcewin ) 1654" 60 is approx spaceBuffer * 3 1655if winwidth ( 0 ) > ( 78 + 60 ) 1656let mdf = 'vert' 1657exe $ '{mdf} :60new' 1658else 1659exe 'rightbelow new' 1660endif 1661else 1662exe 'new' 1663endif 1664 1665let s: varwin = win_getid () 1666 1667setlocal nowrap 1668setlocal noswapfile 1669setlocal buftype = nofile 1670setlocal bufhidden = wipe 1671setlocal signcolumn = no 1672setlocal modifiable 1673 1674if s: varbufnr > 0 && bufexists ( s: varbufnr ) 1675exe $ 'buffer {s: varbufnr }' 1676elseif empty ( glob ( 'Termdebug-variables-listing' )) 1677silent file Termdebug-variables-listing 1678let s: varbufnr = bufnr ( 'Termdebug-variables-listing' ) 1679else 1680call s: Echoerr ( "You have a file/folder named 'Termdebug-variables-listing'. 1681\ Please exit and rename it because Termdebug may not work as expected." ) 1682endif 1683 1684if mdf != 'vert' && s: GetVariablesWindowHeight () > 0 1685exe $ 'resize {s: GetVariablesWindowHeight () }' 1686endif 1687endif 1688 1689if s: running 1690call s: SendCommand ( '-stack-list-variables 2' ) 1691endif 1692endfunc 1693 1694" Handle stopping and running message from gdb. 1695" Will update the sign that shows the current position. 1696func s: HandleCursor ( msg ) 1697let wid = win_getid () 1698 1699if a: msg =~ '^\*stopped' 1700"call ch_log('program stopped') 1701let s: stopped = v: true 1702if a: msg =~ '^\*stopped,reason="exited-normally"' 1703let s: running = v: false 1704endif 1705elseif a: msg =~ '^\*running' 1706"call ch_log('program running') 1707let s: stopped = v: false 1708let s: running = v: true 1709endif 1710 1711if a: msg =~ 'fullname=' 1712let fname = s: GetFullname ( a: msg ) 1713else 1714let fname = '' 1715endif 1716 1717if a: msg =~ 'addr=' 1718let asm_addr = s: GetAsmAddr ( a: msg ) 1719if asm_addr != '' 1720let s: asm_addr = asm_addr 1721 1722let curwinid = win_getid () 1723if win_gotoid ( s: asmwin ) 1724let lnum = search ( $ '^{s: asm_addr } ') 1725if lnum == 0 1726call s: SendCommand ( 'disassemble $pc' ) 1727else 1728call sign_unplace ( 'TermDebug' , #{ id : s: asm_id }) 1729call sign_place ( s: asm_id , 'TermDebug' , 'debugPC' , '%' , #{ lnum : lnum }) 1730endif 1731 1732call win_gotoid ( curwinid ) 1733endif 1734endif 1735endif 1736 1737if s: running && s: stopped && bufwinnr ( 'Termdebug-variables-listing' ) != -1 1738call s: SendCommand ( '-stack-list-variables 2' ) 1739endif 1740 1741if a: msg =~ '^\(\*stopped\|=thread-selected\)' && filereadable ( fname ) 1742let lnum = substitute ( a: msg , '.*line="\([^"]*\)".*' , '\1' , '' ) 1743if lnum =~ '^[0-9]*$' 1744call s: GotoSourcewinOrCreateIt () 1745if expand ( '%:p' ) != fnamemodify ( fname , ':p' ) 1746echomsg $ "different fname: '{expand('%:p')}' vs '{fnamemodify(fname, ':p')}'" 1747augroup 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. 1751au SwapExists * echohl WarningMsg 1752 \ |echo 'Warning: file is being edited elsewhere' 1753 \ |echohl None 1754 \ |let v: swapchoice = 'o' 1755augroup END 1756if & modified 1757" TODO: find existing window 1758exe $ 'split {fnameescape(fname)}' 1759let s: sourcewin = win_getid () 1760call s: InstallWinbar ( 0 ) 1761else 1762exe $ 'edit {fnameescape(fname)}' 1763endif 1764augroup Termdebug 1765au ! SwapExists 1766augroup END 1767endif 1768exe $ ":{lnum}" 1769normal ! zv 1770call sign_unplace ( 'TermDebug' , #{ id : s: pc_id }) 1771call sign_place ( s: pc_id , 'TermDebug' , 'debugPC' , fname , 1772 \#{ lnum : lnum , priority : 110 }) 1773if ! exists ( 'b:save_signcolumn' ) 1774let b: save_signcolumn = & signcolumn 1775call add ( s: signcolumn_buflist , bufnr ()) 1776endif 1777setlocal signcolumn = yes 1778endif 1779elseif ! s: stopped || fname != '' 1780call sign_unplace ( 'TermDebug' , #{ id : s: pc_id }) 1781endif 1782 1783call win_gotoid ( wid ) 1784endfunc 1785 1786let s: BreakpointSigns = [] 1787 1788func s: CreateBreakpoint ( id , subid , enabled ) 1789let nr = printf ( '%d.%d' , a: id , a: subid ) 1790if index ( s: BreakpointSigns , nr ) == -1 1791call add ( s: BreakpointSigns , nr ) 1792if a: enabled == "n" 1793let hiName = "debugBreakpointDisabled" 1794else 1795let hiName = "debugBreakpoint" 1796endif 1797let label = '' 1798if exists ( 'g:termdebug_config' ) 1799if has_key ( g: termdebug_config , 'signs' ) 1800let label = get ( g: termdebug_config . signs , a: id - 1 , '' ) 1801endif 1802if label == '' && has_key ( g: termdebug_config , 'sign' ) 1803let label = g: termdebug_config [ 'sign' ] 1804endif 1805if label == '' && has_key ( g: termdebug_config , 'sign_decimal' ) 1806let label = printf ( '%02d' , a: id ) 1807if a: id > 99 1808let label = '9+' 1809endif 1810endif 1811endif 1812if label == '' 1813let label = printf ( '%02X' , a: id ) 1814if a: id > 255 1815let label = 'F+' 1816endif 1817endif 1818call sign_define ( $ 'debugBreakpoint{nr}', 1819 \ #{text: slice(label,0, 2), 1820 \ texthl: hiName}) 1821endif 1822endfunc 1823 1824func ! s: SplitMsg ( s ) 1825return 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 ) 1831if a: msg !~ 'fullname=' 1832" a watch or a pending breakpoint does not have a file name 1833if a: msg =~ 'pending=' 1834let nr = substitute ( a: msg , '.*number=\"\([0-9.]*\)\".*' , '\1' , '' ) 1835let target = substitute ( a: msg , '.*pending=\"\([^"]*\)\".*' , '\1' , '' ) 1836echomsg $ 'Breakpoint {nr} ({target}) pending.' 1837endif 1838return 1839endif 1840for msg in s: SplitMsg ( a: msg ) 1841let fname = s: GetFullname ( msg ) 1842if empty ( fname ) 1843continue 1844endif 1845let nr = substitute ( msg , '.*number="\([0-9.]*\)\".*' , '\1' , '' ) 1846if empty ( nr ) 1847return 1848endif 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. 1852let [ id , subid ;_ ] = map ( split ( nr . '.0' , '\.' ), 'v:val + 0' ) 1853let enabled = substitute ( msg , '.*enabled="\([yn]\)".*' , '\1' , '' ) 1854call s: CreateBreakpoint ( id , subid , enabled ) 1855 1856if has_key ( s: breakpoints , id ) 1857let entries = s: breakpoints [ id ] 1858else 1859let entries = {} 1860let s: breakpoints [ id ] = entries 1861endif 1862if has_key ( entries , subid ) 1863let entry = entries [ subid ] 1864else 1865let entry = {} 1866let entries [ subid ] = entry 1867endif 1868 1869let lnum = substitute ( msg , '.*line="\([^"]*\)".*' , '\1' , '' ) 1870let entry [ 'fname' ] = fname 1871let entry [ 'lnum' ] = lnum 1872 1873let bploc = printf ( '%s:%d' , fname , lnum ) 1874if ! has_key ( s: breakpoint_locations , bploc ) 1875let s: breakpoint_locations [ bploc ] = [] 1876endif 1877if s: breakpoint_locations [ bploc ] ->index ( id ) == -1 1878" Make sure all ids are unique 1879let s: breakpoint_locations [ bploc ] += [ id ] 1880endif 1881 1882if bufloaded ( fname ) 1883call s: PlaceSign ( id , subid , entry ) 1884let posMsg = $ ' at line {lnum}.' 1885else 1886let posMsg = $ ' in {fname} at line {lnum}.' 1887endif 1888if ! a: modifiedFlag 1889let actionTaken = 'created' 1890elseif enabled == 'n' 1891let actionTaken = 'disabled' 1892else 1893let actionTaken = 'enabled' 1894endif 1895echom $ 'Breakpoint {nr} {actionTaken}{posMsg}' 1896endfor 1897endfunc 1898 1899func s: PlaceSign ( id , subid , entry ) 1900let nr = printf ( '%d.%d' , a: id , a: subid ) 1901call sign_place ( s: Breakpoint2SignNumber ( a: id , a: subid ), 'TermDebug' , 1902 \$ 'debugBreakpoint{nr}', a:entry['fname'], 1903 \ #{lnum: a:entry['lnum'], priority:110}) 1904let a: entry [ 'placed' ] = 1 1905endfunc 1906 1907" Handle deleting a breakpoint 1908" Will remove the sign that shows the breakpoint 1909func s: HandleBreakpointDelete ( msg ) 1910let id = substitute ( a: msg , '.*id="\([0-9]*\)\".*' , '\1' , '' ) + 0 1911if empty ( id ) 1912return 1913endif 1914if has_key ( s: breakpoints , id ) 1915for [ subid , entry ] in items ( s: breakpoints [ id ]) 1916if has_key ( entry , 'placed' ) 1917call sign_unplace ( 'TermDebug' , 1918 \#{ id : s: Breakpoint2SignNumber ( id , subid )}) 1919unlet entry [ 'placed' ] 1920endif 1921endfor 1922unlet s: breakpoints [ id ] 1923echomsg $ 'Breakpoint {id} cleared.' 1924endif 1925endfunc 1926 1927" Handle the debugged program starting to run. 1928" Will store the process ID in s:pid 1929func s: HandleProgramRun ( msg ) 1930let nr = substitute ( a: msg , '.*pid="\([0-9]*\)\".*' , '\1' , '' ) + 0 1931if nr == 0 1932return 1933endif 1934let 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 () 1940let fname = expand ( '<afile>:p' ) 1941for [ id , entries ] in items ( s: breakpoints ) 1942for [ subid , entry ] in items ( entries ) 1943if entry [ 'fname' ] == fname 1944call s: PlaceSign ( id , subid , entry ) 1945endif 1946endfor 1947endfor 1948endfunc 1949 1950" Handle a BufUnloaded autocommand event: unplace any signs. 1951func s: BufUnloaded () 1952let fname = expand ( '<afile>:p' ) 1953for [ id , entries ] in items ( s: breakpoints ) 1954for [ subid , entry ] in items ( entries ) 1955if entry [ 'fname' ] == fname 1956let entry [ 'placed' ] = 0 1957endif 1958endfor 1959endfor 1960endfunc 1961 1962call s: InitHighlight () 1963call s: InitAutocmd () 1964 1965let & cpo = s: keepcpo 1966unlet s: keepcpo 1967 1968" vim: sw=2 sts=2 et