1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! The Run and Debug view: its keys, the Run or Debug button, the paused-state tree (call
//! stack, variables), clicks and the row menu with Copy Value and Copy Call Stack,
//! revealing the view, and how a launch failure shows.
use super::*;
/// Append variable rows to the debug tree, recursing into any expanded
/// (`variablesReference` in `expanded`) container whose children are loaded.
/// Pulled out as a free function so it can borrow the session immutably while
/// the caller mutates the row vector.
pub(in crate::app) fn push_variable_rows(
rows: &mut Vec<crate::widgets::run_debug::DebugRow>,
session: &crate::dap::session::DapSession,
expanded: &std::collections::HashSet<i64>,
vars: &[crate::dap::session::Variable],
indent: u8,
) {
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
for v in vars {
let expandable = v.variables_ref > 0;
let is_open = expandable && expanded.contains(&v.variables_ref);
rows.push(DebugRow {
indent,
kind: DebugRowKind::Variable {
reference: v.variables_ref,
expandable,
expanded: is_open,
name: v.name.clone(),
value: v.value.clone(),
type_name: v.type_name.clone(),
evaluate_name: v.evaluate_name.clone(),
},
});
if is_open && let Some(children) = session.variables.get(&v.variables_ref) {
push_variable_rows(rows, session, expanded, children, indent.saturating_add(1));
}
}
}
impl App {
pub(in crate::app) fn handle_run_debug_key(&mut self, key: KeyEvent) {
// While a session is live the panel is a REPL: text edits the prompt and
// Enter evaluates it. Esc leaves the view. Tab and Shift+Tab hand the
// keys to the rows above (#2748), which have keys of their own.
if self.run_debug.debug_active {
if self.run_debug.row_cursor.is_some() {
self.handle_debug_rows_key(key);
return;
}
match key.code {
KeyCode::Tab => {
self.run_debug.enter_rows(false);
}
KeyCode::BackTab => {
self.run_debug.enter_rows(true);
}
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Enter => {
self.debug_repl_submit();
self.refresh_debug_panel();
}
KeyCode::Left => self.run_debug.move_repl_caret(|t, c| {
crate::widgets::line_edit::caret_left(t, c, key_walks_by_word(key))
}),
KeyCode::Right => self.run_debug.move_repl_caret(|t, c| {
crate::widgets::line_edit::caret_right(t, c, key_walks_by_word(key))
}),
KeyCode::Home => self.run_debug.move_repl_caret(|_, _| 0),
KeyCode::End => self
.run_debug
.move_repl_caret(|t, _| crate::widgets::line_edit::char_len(t)),
KeyCode::Delete => self.run_debug.delete_repl(key_walks_by_word(key)),
KeyCode::Backspace => self.run_debug.backspace_repl(key_walks_by_word(key)),
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
self.run_debug.push_repl_char(c);
}
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => self.set_sidebar_view(SidebarView::Explorer),
KeyCode::Enter => self.run_debug_button_action(),
_ => {}
}
}
/// A key while a row of the debug tree has the keys (#2748), as VS
/// Code's VARIABLES, WATCH and CALL STACK lists take them: the arrows,
/// Home / End and PageUp / PageDown move the cursor, Left / Right close
/// and open a variable or scope, Enter and Space do what a click on the
/// row does, Delete (Cmd+Backspace on a Mac) removes a watch or
/// breakpoint. Tab, Shift+Tab and Esc give the prompt the keys back, and
/// typing, Backspace included, goes to the prompt.
fn handle_debug_rows_key(&mut self, key: KeyEvent) {
use crate::widgets::run_debug::DebugRowKind;
let Some(idx) = self.run_debug.row_cursor else {
return;
};
let Some(row) = self.run_debug.debug_rows.get(idx).cloned() else {
return;
};
let page = self.run_debug.row_page();
let open = match &row.kind {
DebugRowKind::Variable {
expandable: true,
expanded,
..
} => Some(*expanded),
DebugRowKind::Scope { open, .. } => *open,
_ => None,
};
match key.code {
KeyCode::Up => self.run_debug.move_row_cursor(-1),
KeyCode::Down => self.run_debug.move_row_cursor(1),
KeyCode::PageUp => self.run_debug.move_row_cursor(-page),
KeyCode::PageDown => self.run_debug.move_row_cursor(page),
KeyCode::Home => {
self.run_debug.enter_rows(false);
}
KeyCode::End => {
self.run_debug.enter_rows(true);
}
// Open a closed variable or scope; on an open one, step to its
// first child, as a VS Code tree does.
KeyCode::Right => match open {
Some(false) => self.debug_panel_click(idx),
Some(true) => self.run_debug.move_row_cursor(1),
None => {}
},
// Close an open variable or scope; elsewhere, step to the row
// it sits under.
KeyCode::Left => {
if open == Some(true) {
self.debug_panel_click(idx);
} else if let Some(parent) = (0..idx).rev().find(|&i| {
self.run_debug.debug_rows[i].indent < row.indent
&& !matches!(
self.run_debug.debug_rows[i].kind,
DebugRowKind::Header { .. }
)
}) {
self.run_debug.row_cursor = Some(parent);
self.run_debug.scroll_row_cursor_into_view();
}
}
KeyCode::Enter | KeyCode::Char(' ') => match row.kind {
DebugRowKind::Breakpoint { index, .. } => self.breakpoint_list_click(index, false),
_ => self.debug_panel_click(idx),
},
// Delete removes, as VS Code's Delete (Cmd+Backspace on a Mac)
// does. Plain Backspace is an edit of what is typed: it goes to
// the prompt, as typing does, and never removes a row.
KeyCode::Delete | KeyCode::Backspace
if key.code == KeyCode::Delete || has_cmd(key.modifiers) =>
{
match row.kind {
DebugRowKind::Watch { index, .. } => {
self.remove_watch_expression(index);
self.refresh_debug_panel();
// Its row is gone: the keys stay at its place, on the
// row that took it, as a VS Code list's do.
self.run_debug.row_cursor = Some(idx);
}
DebugRowKind::Breakpoint { index, .. } => {
self.breakpoint_list_click(index, true);
self.run_debug.row_cursor = Some(idx);
}
_ => {}
}
}
KeyCode::Tab | KeyCode::BackTab | KeyCode::Esc => self.run_debug.row_cursor = None,
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
self.run_debug.row_cursor = None;
self.run_debug.push_repl_char(c);
}
KeyCode::Backspace => {
self.run_debug.row_cursor = None;
self.run_debug.backspace_repl(false);
}
_ => {}
}
self.run_debug.settle_row_cursor();
}
/// Keep the idle Run & Debug panel in step with the active editor file while
/// the view stays open (#2943). Compares paths first so staying on the same
/// file never re-reads `launch.json` or clears launch feedback, skips while
/// a debug session is live so stepping across files keeps session status,
/// and preserves session-end feedback when applying a deferred sync after a
/// session terminates.
pub(in crate::app) fn sync_run_debug_if_file_changed(&mut self) {
if self.sidebar_view == SidebarView::RunDebug
&& !self.run_debug.debug_active
&& self.run_debug.active_file != self.editor.path
{
if self.run_debug.session_ended {
self.refresh_run_debug_metadata();
} else {
self.refresh_run_debug();
}
}
}
pub(in crate::app) fn refresh_run_debug(&mut self) {
self.refresh_run_debug_metadata();
self.run_debug.feedback = None;
self.run_debug.feedback_is_error = false;
}
/// Update `run_debug`'s active file, runnability, and `launch.json` config
/// summary without clearing `feedback`.
fn refresh_run_debug_metadata(&mut self) {
let path = self.editor.path.clone();
// Decide the button: scripts and executables are "Run" (terminal);
// compiled source (no script runner, but a debug adapter) is "Debug"
// (build + lldb). Files that are neither (e.g. `.git/config`) get no
// button. run_spec_for already covers executables (the +x bit), so a
// compiled binary is "Run" — run it directly.
let (runnable, is_debug) = match path.as_deref() {
Some(p) => {
let ext = p
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
if Self::run_spec_for(
p,
self.roots
.owning_root(p)
.unwrap_or_else(|| self.roots.primary()),
)
.is_some()
{
(true, false)
} else if crate::dap::registry::adapter_for_extension(&ext).is_some() {
(true, true)
} else {
(false, false)
}
}
None => (false, false),
};
self.run_debug.runnable = runnable;
self.run_debug.run_is_debug = is_debug;
self.run_debug.set_active_file(path);
// The launch.json config row (#250): count + F5 selection. Discovery
// re-reads the same two small files once per helper — four reads — and
// this only runs on active-file changes.
// Compounds count too — the row is the documented route to the picker,
// and the picker lists them, so counting only configurations makes the
// row vanish for a compounds-only workspace and undercount otherwise.
//
// A HIDDEN compound is not listed (#318), so it must not be counted
// either: the row and the picker have to agree, or a workspace whose
// only entry is hidden advertises "1 debug entry" over a picker that
// offers nothing. Same filter as `open_debug_config_picker`.
let root = self.active_workspace_root();
// The same filter the picker applies, so the badge and the picker
// cannot disagree: a `presentation.hidden` entry of EITHER kind is
// absent from both (#318).
self.run_debug.config_count = crate::dap::configs::discover_configs(&root)
.iter()
.filter(|c| !c.hidden())
.count()
+ crate::dap::configs::discover_compounds(&root)
.iter()
.filter(|c| !c.hidden())
.count();
self.run_debug.selected_config = self
.selected_debug_compound
.clone()
.or_else(|| self.selected_debug_config.clone());
}
/// Rebuild the Run & Debug panel's paused-state tree from the session, or
/// deactivate it when not paused. Cheap; called after each `poll_dap`.
pub(in crate::app) fn refresh_debug_panel(&mut self) {
let (active, status, rows) = self.build_debug_view();
self.run_debug.debug_active = active;
self.run_debug.debug_paused = self
.debug
.sessions
.focused()
.is_some_and(|s| s.phase == crate::dap::session::SessionPhase::Stopped);
if active {
self.run_debug.debug_status = status;
self.run_debug.replace_rows(rows);
let max_scroll = self.run_debug.debug_rows.len().saturating_sub(1);
if self.run_debug.debug_scroll > max_scroll {
self.run_debug.debug_scroll = max_scroll;
}
// Show the console tail (most recent output / REPL lines).
let n = self.debug.console.len();
self.run_debug.console_tail = self.debug.console[n.saturating_sub(50)..].to_vec();
} else {
self.run_debug.debug_rows.clear();
self.run_debug.debug_scroll = 0;
self.run_debug.row_cursor = None;
self.run_debug.clear_repl();
// Retain the just-ended session's console output until the next run;
// otherwise the idle Run panel shows nothing.
if self.run_debug.session_ended && !self.debug.console.is_empty() {
let n = self.debug.console.len();
self.run_debug.console_tail = self.debug.console[n.saturating_sub(50)..].to_vec();
} else {
self.run_debug.console_tail.clear();
}
}
}
/// Build the (active, status, rows) tuple for the debug panel from the
/// session. `&self` so it can borrow the session and expansion set without
/// conflicting with the `&mut self` assignment in `refresh_debug_panel`.
pub(in crate::app) fn build_debug_view(
&self,
) -> (bool, String, Vec<crate::widgets::run_debug::DebugRow>) {
use crate::dap::session::SessionPhase;
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
let Some(session) = self.debug.sessions.focused() else {
return (false, String::new(), Vec::new());
};
// Active for any live session: while Running the tree is empty but the
// console still shows output; while Stopped the full tree is built.
if session.phase == SessionPhase::Terminated {
return (false, String::new(), Vec::new());
}
if session.phase != SessionPhase::Stopped {
let status = self
.run_debug
.feedback
.clone()
.unwrap_or_else(|| String::from("Running"));
return (
true,
status,
breakpoint_section_rows(&self.breakpoint_items()),
);
}
let mut rows = Vec::new();
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("CALL STACK"),
},
});
// With more than one thread (goroutines, under delve), each gets a
// row and the selected one's frames sit under it, as in VS Code
// (#264). A single thread keeps the plain frame list.
let threaded = session.threads.len() > 1;
let mut frames_at = rows.len();
if threaded {
for (id, name) in &session.threads {
let selected = session.stopped_thread == Some(*id);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Thread {
id: *id,
name: name.clone(),
selected,
},
});
if selected {
frames_at = rows.len();
}
}
}
let mut frame_rows = Vec::new();
for f in &session.stack_frames {
let loc = f
.path
.as_ref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
frame_rows.push(DebugRow {
indent: if threaded { 2 } else { 1 },
kind: DebugRowKind::Frame {
id: f.id,
selected: Some(f.id) == session.selected_frame,
name: f.name.clone(),
location: format!("{loc}:{}", f.line),
},
});
}
rows.splice(frames_at..frames_at, frame_rows);
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("VARIABLES"),
},
});
for (index, scope) in session.scopes.iter().enumerate() {
let open = session.scope_open(index);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Scope {
name: scope.name.clone(),
index,
open: scope.expensive.then_some(open),
},
});
if !open {
continue;
}
if let Some(vars) = session.variables.get(&scope.variables_ref) {
push_variable_rows(&mut rows, session, &self.debug.expanded, vars, 2);
}
}
rows.push(DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("WATCH"),
},
});
for (widx, expr) in self.watch_exprs.iter().enumerate() {
let (value, available, pending) = match self.watch_vals.get(expr) {
Some((v, ok)) => (v.clone(), *ok, false),
None => (String::new(), true, true),
};
let changed = available
&& !pending
&& self.watch_prev.get(expr).is_some_and(|prev| prev != &value);
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::Watch {
index: widx,
expression: expr.clone(),
value,
available,
changed,
pending,
},
});
}
rows.push(DebugRow {
indent: 1,
kind: DebugRowKind::WatchAdd,
});
// Last, so `sync_breakpoint_list` can swap it without a rebuild.
rows.extend(breakpoint_section_rows(&self.breakpoint_items()));
let status = self
.run_debug
.feedback
.clone()
.unwrap_or_else(|| String::from("Paused"));
(true, status, rows)
}
/// Act on a click of debug-panel row `idx`: select a call-stack frame (load
/// its scopes/variables) or toggle an expandable variable open/closed.
pub(in crate::app) fn debug_panel_click(&mut self, idx: usize) {
use crate::widgets::run_debug::DebugRowKind;
let Some(row) = self.run_debug.debug_rows.get(idx) else {
return;
};
match row.kind.clone() {
DebugRowKind::Thread { id, .. } => {
if let Some(session) = self.debug.sessions.focused_mut() {
session.select_thread(id);
}
self.debug.expanded.clear();
}
DebugRowKind::Frame { id, .. } => {
if let Some(session) = self.debug.sessions.focused_mut() {
session.load_frame(id);
}
// Collapse expansions: variable refs are frame-scoped.
self.debug.expanded.clear();
}
DebugRowKind::Variable {
reference,
expandable: true,
..
} => {
if self.debug.expanded.contains(&reference) {
self.debug.expanded.remove(&reference);
} else {
self.debug.expanded.insert(reference);
if let Some(session) = self.debug.sessions.focused_mut() {
session.expand_variable(reference);
}
}
}
DebugRowKind::WatchAdd => {
self.open_add_watch_prompt();
}
// An expensive scope opens (and is fetched) on click (#1421).
DebugRowKind::Scope {
index,
open: Some(_),
..
} => {
if let Some(session) = self.debug.sessions.focused_mut() {
session.toggle_expensive_scope(index);
}
}
_ => {}
}
self.refresh_debug_panel();
}
/// The right-click menu of debug-panel row `idx` (#1546), VS Code's:
/// a variable's Copy Value, Copy as Expression and Add to Watch, a
/// watch's Copy Value, Copy Expression and Remove, and a frame's Copy
/// Call Stack. Empty for a row that has none (a header, a scope).
pub(in crate::app) fn debug_row_menu(&self, idx: usize) -> Vec<(String, MenuAction)> {
use crate::widgets::run_debug::DebugRowKind;
let Some(row) = self.run_debug.debug_rows.get(idx) else {
return Vec::new();
};
match &row.kind {
DebugRowKind::Variable {
value,
evaluate_name,
..
} => {
let mut items = vec![(
String::from("Copy Value"),
MenuAction::CopyDebugValue {
expression: evaluate_name.clone(),
value: value.clone(),
},
)];
if let Some(expr) = evaluate_name {
items.push((
String::from("Copy as Expression"),
MenuAction::CopyDebugExpression(expr.clone()),
));
items.push((
String::from("Add to Watch"),
MenuAction::AddDebugWatch(expr.clone()),
));
}
items
}
DebugRowKind::Watch {
index,
expression,
value,
..
} => vec![
(
String::from("Copy Value"),
MenuAction::CopyDebugValue {
expression: Some(expression.clone()),
value: value.clone(),
},
),
(
String::from("Copy Expression"),
MenuAction::CopyDebugExpression(expression.clone()),
),
(
String::from("Remove Expression"),
MenuAction::RemoveDebugWatch(*index),
),
],
DebugRowKind::Frame { .. } => {
vec![(String::from("Copy Call Stack"), MenuAction::CopyCallStack)]
}
_ => Vec::new(),
}
}
/// Copy Value (#1546). The row's `value` can be cut short by the
/// adapter (debugpy elides a long string), so while paused, with an
/// expression and an adapter that offers it, the value is asked for
/// again in the `clipboard` context, which is not cut, and copied when
/// it lands (`poll_dap`). Otherwise the row's value is copied at once.
pub(in crate::app) fn copy_debug_value(&mut self, expression: Option<String>, value: String) {
use crate::dap::session::SessionPhase;
if let Some(expr) = expression
&& let Some(session) = self
.debug
.sessions
.focused_mut()
.filter(|s| s.phase == SessionPhase::Stopped)
&& session.supports("supportsClipboardContext")
{
session.evaluate(&expr, "clipboard");
self.debug.copy_pending = Some((expr, value));
self.status = String::from("Copying value…");
return;
}
self.status = self.copy_where_pasted(&value).status("value");
}
/// Copy Call Stack (#1546): every frame of the paused thread, innermost
/// first, as `name (path:line)`, VS Code's form.
pub(in crate::app) fn copy_call_stack(&mut self) {
let Some(session) = self.debug.sessions.focused() else {
return;
};
let text = session
.stack_frames
.iter()
.map(|f| match &f.path {
Some(p) => format!("{} ({}:{})", f.name, p.display(), f.line),
None => f.name.clone(),
})
.collect::<Vec<_>>()
.join("\n");
self.status = self.copy_where_pasted(&text).status("call stack");
}
/// The Run/Debug panel button action: debug compiled source (build + lldb),
/// or run scripts/executables in a terminal — matching the button's verb.
pub(in crate::app) fn run_debug_button_action(&mut self) {
if self.run_debug.run_is_debug {
self.debug_start_or_continue();
} else {
self.run_active_file();
}
}
/// Open and focus the Run and Debug view so the call stack, variables,
/// console, and REPL are visible the instant a session starts (VS Code
/// reveals its debug view on launch the same way).
pub(in crate::app) fn reveal_debug_view(&mut self) {
// A fresh session: drop the previous run's retained console + stop
// tracking so the "exited without hitting a breakpoint" hint and the
// console reflect only this run.
self.debug.console_dropped += self.debug.console.len();
self.debug.console.clear();
self.debug.ever_stopped = false;
self.run_debug.session_ended = false;
self.show_tree = true;
self.set_sidebar_view(SidebarView::RunDebug);
self.focus_pane(Pane::Tree);
}
/// Surface a debug-start failure on BOTH the styled Run/Debug panel
/// feedback line AND the always-visible status bar. The panel line only
/// renders while the Run/Debug sidebar is the active view (`reveal_debug_view`
/// is reached only on success), so without the status-bar mirror F5 fails
/// silently whenever the user is looking at any other sidebar — which read
/// as "F5 does nothing" on a remote with no debug adapter installed.
pub(in crate::app) fn debug_error(&mut self, msg: String) {
// A launch that never happened leaves no session to clean up after,
// so any breakpoint croft armed for it comes out here (#373) —
// otherwise it survives in the editor as if the user had set it.
self.disarm_failure_breakpoint();
self.run_debug.feedback = Some(msg.clone());
self.run_debug.feedback_is_error = true;
self.status = msg;
}
}