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
mod app;
mod config;
mod error;
mod handler;
mod input;
mod model;
mod output;
mod persistence;
mod syntax;
mod text_edit;
mod theme;
mod tuicrignore;
mod ui;
mod update;
mod vcs;
use std::fs::File;
use std::io::{self, Write};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use crossterm::{
event::{
self, Event, KeyEventKind, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
PushKeyboardEnhancementFlags,
},
execute,
terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
supports_keyboard_enhancement,
},
};
use ratatui::{Terminal, backend::CrosstermBackend};
use app::{App, FocusedPanel, InputMode};
use handler::{
handle_command_action, handle_comment_action, handle_commit_select_action,
handle_commit_selector_action, handle_confirm_action, handle_diff_action,
handle_file_list_action, handle_help_action, handle_search_action, handle_visual_action,
};
use input::{Action, map_key_to_action};
use theme::{parse_cli_args, resolve_theme_with_config};
/// Timeout for the "press Ctrl+C again to exit" feature
const CTRL_C_EXIT_TIMEOUT: Duration = Duration::from_secs(2);
/// Hide the file list by default on narrow terminals.
const MIN_WIDTH_FOR_FILE_LIST: u16 = 100;
fn main() -> anyhow::Result<()> {
// Setup panic hook to restore terminal on panic
let original_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
let _ = execute!(io::stdout(), PopKeyboardEnhancementFlags);
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen);
original_hook(panic_info);
}));
// Parse CLI arguments and resolve theme
// This also configures syntax highlighting colors before diff parsing
let mut cli_args = parse_cli_args();
// Check keyboard enhancement support before enabling raw mode.
// Skip when --stdout is used because the probe writes escape sequences to stdout,
// which would leak into the captured export output.
let keyboard_enhancement_supported = if cli_args.output_to_stdout {
false
} else {
matches!(supports_keyboard_enhancement(), Ok(true))
};
// --file is mutually exclusive with --path, -r, and -w
if cli_args.file_path.is_some() {
if cli_args.path_filter.is_some() {
eprintln!("Error: --file cannot be combined with --path");
std::process::exit(2);
}
if cli_args.revisions.is_some() {
eprintln!("Error: --file cannot be combined with -r/--revisions");
std::process::exit(2);
}
if cli_args.working_tree {
eprintln!("Error: --file cannot be combined with -w/--working-tree");
std::process::exit(2);
}
}
// --path implies --working-tree unless -r is explicitly provided
if cli_args.path_filter.is_some() && !cli_args.working_tree && cli_args.revisions.is_none() {
cli_args.working_tree = true;
}
let mut startup_warnings = Vec::new();
let config_outcome = match config::load_config() {
Ok(outcome) => outcome,
Err(e) => {
startup_warnings.push(format!("Failed to load config: {e}"));
config::ConfigLoadOutcome::default()
}
};
startup_warnings.extend(config_outcome.warnings);
let (theme, theme_warnings) = resolve_theme_with_config(
cli_args.theme,
cli_args.appearance,
config_outcome
.config
.as_ref()
.and_then(|cfg| cfg.theme.as_deref()),
config_outcome
.config
.as_ref()
.and_then(|cfg| cfg.theme_dark.as_deref()),
config_outcome
.config
.as_ref()
.and_then(|cfg| cfg.theme_light.as_deref()),
config_outcome
.config
.as_ref()
.and_then(|cfg| cfg.appearance.as_deref()),
);
startup_warnings.extend(theme_warnings);
// Start update check in background (non-blocking)
let update_rx = if !cli_args.no_update_check {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let result = update::check_for_updates();
let _ = tx.send(result); // Ignore send error if receiver dropped
});
Some(rx)
} else {
None
};
// Initialize app
let mut app = match App::new(
theme,
config_outcome
.config
.as_ref()
.and_then(|cfg| cfg.comment_types.clone()),
cli_args.output_to_stdout,
cli_args.revisions.as_deref(),
cli_args.working_tree,
cli_args.path_filter.as_deref(),
cli_args.file_path.as_deref(),
) {
Ok(mut app) => {
app.supports_keyboard_enhancement = keyboard_enhancement_supported;
if let Some(message) = startup_warnings.first() {
app.set_warning(message.clone());
}
app
}
Err(e) => {
eprintln!("Error: {e}");
eprintln!(
"\nMake sure you're in a git, jujutsu, or mercurial repository with commits or staged/unstaged changes."
);
std::process::exit(1);
}
};
// Setup terminal
// When --stdout is used, render TUI to /dev/tty so stdout is free for export output
enable_raw_mode()?;
let mut tty_output: Box<dyn Write> = if cli_args.output_to_stdout {
Box::new(File::options().write(true).open("/dev/tty")?)
} else {
Box::new(io::stdout())
};
execute!(tty_output, EnterAlternateScreen)?;
// Enable keyboard enhancement for better modifier key detection (e.g., Alt+Enter)
// This is supported by modern terminals like Kitty, iTerm2, WezTerm, etc.
if keyboard_enhancement_supported {
let _ = execute!(
tty_output,
PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
);
}
let backend = CrosstermBackend::new(tty_output);
let mut terminal = Terminal::new(backend)?;
// Apply config-driven defaults
if let Some(ref cfg) = config_outcome.config {
if cfg.show_file_list == Some(false) {
app.show_file_list = false;
app.focused_panel = FocusedPanel::Diff;
}
if cfg.diff_view.as_deref() == Some("side-by-side") {
app.diff_view_mode = app::DiffViewMode::SideBySide;
}
if cfg.wrap == Some(true) {
app.set_diff_wrap(true);
}
if cfg.export_legend == Some(false) {
app.export_legend = false;
}
}
// On narrow terminals, start with only the diff panel visible.
if let Ok((width, _)) = crossterm::terminal::size()
&& width < MIN_WIDTH_FOR_FILE_LIST
{
app.show_file_list = false;
app.focused_panel = FocusedPanel::Diff;
}
// Track pending z command for zz centering
let mut pending_z = false;
// Track pending Z command for ZZ export+quit / ZQ quit
let mut pending_shift_z = false;
// Track pending d command for dd delete
let mut pending_d = false;
// Track pending ; command for ;e toggle file list
let mut pending_semicolon = false;
// Track pending Ctrl+C for "press twice to exit" (with timestamp for 2s timeout)
let mut pending_ctrl_c: Option<Instant> = None;
// Main loop
loop {
// Render
terminal.draw(|frame| {
ui::render(frame, &mut app);
})?;
// Check for update result (non-blocking)
if let Some(ref rx) = update_rx
&& let Ok(
update::UpdateCheckResult::UpdateAvailable(info)
| update::UpdateCheckResult::AheadOfRelease(info),
) = rx.try_recv()
{
app.update_info = Some(info);
}
// Auto-clear expired pending Ctrl+C state and message
if let Some(first_press) = pending_ctrl_c
&& first_press.elapsed() >= CTRL_C_EXIT_TIMEOUT
{
pending_ctrl_c = None;
app.message = None;
}
// Handle events
if event::poll(Duration::from_millis(100))? {
let event = event::read()?;
match event {
Event::Key(key) if key.kind == KeyEventKind::Press => {
// Handle Ctrl+C twice to exit (works across all input modes)
// In Comment mode, first Ctrl+C also cancels the comment
if key.code == crossterm::event::KeyCode::Char('c')
&& key
.modifiers
.contains(crossterm::event::KeyModifiers::CONTROL)
{
// If in comment mode, cancel the comment first
if app.input_mode == InputMode::Comment {
app.exit_comment_mode();
}
if let Some(first_press) = pending_ctrl_c
&& first_press.elapsed() < CTRL_C_EXIT_TIMEOUT
{
// Second Ctrl+C within timeout - exit immediately
app.should_quit = true;
continue;
}
// First Ctrl+C (or timeout expired) - show warning and start timer
pending_ctrl_c = Some(Instant::now());
app.set_message("Press Ctrl+C again to exit");
continue;
}
// Any other key clears the pending Ctrl+C state and message
if pending_ctrl_c.is_some() {
pending_ctrl_c = None;
app.message = None;
}
// Handle pending z command for zz centering
if pending_z {
pending_z = false;
if key.code == crossterm::event::KeyCode::Char('z') {
app.center_cursor();
continue;
}
// Otherwise fall through to normal handling
}
// Handle pending Z command for ZZ (export+quit) / ZQ (quit)
if pending_shift_z {
pending_shift_z = false;
match key.code {
crossterm::event::KeyCode::Char('Z') => {
// ZZ: save session, export, and quit (same as :wq)
let _ = persistence::save_session(&app.session);
app.dirty = false;
if app.session.has_comments() {
handler::handle_export_and_quit(&mut app);
} else {
app.should_quit = true;
}
continue;
}
crossterm::event::KeyCode::Char('Q') => {
// ZQ: quit without exporting (same as q)
app.should_quit = true;
continue;
}
_ => {} // Fall through to normal handling
}
}
// Handle pending d command for dd delete comment
if pending_d {
pending_d = false;
if key.code == crossterm::event::KeyCode::Char('d') {
if !app.delete_comment_at_cursor() {
app.set_message("No comment at cursor");
}
continue;
}
// Otherwise fall through to normal handling
}
// Handle pending ; command for panel focus, file list toggle, and review comments
if pending_semicolon {
pending_semicolon = false;
match key.code {
crossterm::event::KeyCode::Char('e') => {
app.toggle_file_list();
continue;
}
crossterm::event::KeyCode::Char('h') => {
app.focused_panel = app::FocusedPanel::FileList;
continue;
}
crossterm::event::KeyCode::Char('l') => {
app.focused_panel = app::FocusedPanel::Diff;
continue;
}
crossterm::event::KeyCode::Char('k') => {
if app.has_inline_commit_selector() {
app.focused_panel = app::FocusedPanel::CommitSelector;
}
continue;
}
crossterm::event::KeyCode::Char('j') => {
app.focused_panel = app::FocusedPanel::Diff;
continue;
}
crossterm::event::KeyCode::Char('c') => {
app.enter_review_comment_mode();
continue;
}
_ => {}
}
// Otherwise fall through to normal handling
}
let action = map_key_to_action(key, app.input_mode);
// Handle pending command setters (these work in any mode)
match action {
Action::PendingZCommand => {
pending_z = true;
app.pending_count = None;
continue;
}
Action::PendingShiftZCommand => {
pending_shift_z = true;
app.pending_count = None;
continue;
}
Action::PendingDCommand => {
pending_d = true;
app.pending_count = None;
continue;
}
Action::PendingSemicolonCommand => {
pending_semicolon = true;
app.pending_count = None;
continue;
}
_ => {}
}
// Handle digit accumulation for {N}G jump-to-line (Normal mode only)
if app.input_mode == InputMode::Normal {
match action {
Action::Digit(d) => {
let n = app.pending_count.unwrap_or(0);
app.pending_count = Some(
(n.saturating_mul(10).saturating_add(d as usize)).min(999_999),
);
continue;
}
Action::GoToBottom if app.pending_count.is_some() => {
// Clamp to 1 since source lines are 1-indexed; 0G behaves like 1G
let count = app.pending_count.unwrap().max(1);
app.pending_count = None;
// Safe cast: count is clamped to 999_999 which fits in u32
app.go_to_source_line(count as u32);
continue;
}
_ => {
app.pending_count = None;
}
}
}
// Dispatch by input mode
match app.input_mode {
InputMode::Help => handle_help_action(&mut app, action),
InputMode::Command => handle_command_action(&mut app, action),
InputMode::Search => handle_search_action(&mut app, action),
InputMode::Comment => handle_comment_action(&mut app, action),
InputMode::Confirm => handle_confirm_action(&mut app, action),
InputMode::CommitSelect => handle_commit_select_action(&mut app, action),
InputMode::VisualSelect => handle_visual_action(&mut app, action),
InputMode::Normal => match app.focused_panel {
FocusedPanel::FileList => handle_file_list_action(&mut app, action),
FocusedPanel::Diff => handle_diff_action(&mut app, action),
FocusedPanel::CommitSelector => {
handle_commit_selector_action(&mut app, action)
}
},
}
}
_ => {}
}
}
if app.should_quit {
break;
}
}
// Restore terminal
let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
// Print pending stdout output if --stdout was used
if let Some(output) = app.pending_stdout_output {
print!("{output}");
}
Ok(())
}