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
use crate::{
Exit,
app::{self, App, Focus, KeyCode, Split, Status},
};
impl App {
/// Walking the list: the cursor skips file headings, and moving it moves
/// the hunk on screen, so marking always acts on what you are looking at.
///
/// `v` or `V` starts a visual selection at the cursor; moving then
/// stretches it, and a digit puts every hunk in it in that commit at
/// once (`V G 1`, `V ] 2`). The selection is a run of hunks in diff
/// order, so unlike `a` it can span files.
fn overview_key(&mut self, code: KeyCode, ctrl: bool) -> Option<Exit> {
let rows = self.overview_rows();
let at = self.overview?;
// Only hunk rows can hold the cursor; work in hunk numbers, which
// are also the split's, and map back to rows at the end.
let hunk_rows: Vec<usize> = rows
.iter()
.enumerate()
.filter(|(_, r)| r.hunk.is_some())
.map(|(i, _)| i)
.collect();
let here = hunk_rows.iter().position(|&r| r == at)?;
let last = hunk_rows.len().saturating_sub(1);
let files: Vec<usize> = hunk_rows
.iter()
.filter_map(|&r| rows[r].hunk.map(|h| h.file))
.collect();
let half = self.diff.half_page();
let mut to = here;
match code {
// Motions, which also stretch a selection.
KeyCode::Char('d') if ctrl => to = (here + half).min(last),
KeyCode::Char('u') if ctrl => to = here.saturating_sub(half),
KeyCode::Char('j') | KeyCode::Down => to = (here + 1).min(last),
KeyCode::Char('k') | KeyCode::Up => to = here.saturating_sub(1),
KeyCode::Char('g') | KeyCode::Home => to = 0,
KeyCode::Char('G') | KeyCode::End => to = last,
KeyCode::Char(']') => to = file_jump(&files, here, true),
KeyCode::Char('[') => to = file_jump(&files, here, false),
// Selecting.
KeyCode::Char('v' | 'V') => {
self.visual = if self.visual.is_some() {
None
} else {
Some(here)
};
}
// Vim's `o`: jump to the other end of the selection.
KeyCode::Char('o') if self.visual.is_some() => {
to = self.visual.replace(here).unwrap_or(here);
}
KeyCode::Esc if self.visual.is_some() => self.visual = None,
// `Enter` goes back to reading the hunk under the cursor; the
// others just close the list. Same effect, since the cursor has
// been moving the hunk on screen all along.
KeyCode::Char('f' | 'q') | KeyCode::Esc | KeyCode::Enter => {
self.overview = None;
self.visual = None;
}
// Assigning works exactly as it does on the hunk itself, or on
// the whole selection when there is one. Either way a selection
// ends once it has been used, as in Vim.
KeyCode::Char(c @ ('1'..='9' | ' ')) => {
let commit = if c == ' ' { 1 } else { digit(c) };
let split = self.split.as_mut()?;
match self.visual.take() {
Some(from) => split.toggle_range(from, here, commit),
None => split.toggle(commit),
}
}
KeyCode::Char('0') => {
let split = self.split.as_mut()?;
match self.visual.take() {
Some(from) => split.assign_range(from, here, None),
None => split.assign(None),
}
}
// `d`/`x` on a selection take it out, as Vim's would delete it.
KeyCode::Char('d' | 'x') if self.visual.is_some() => {
let from = self.visual.take()?;
self.split.as_mut()?.assign_range(from, here, None);
}
KeyCode::Char('a') => {
self.visual = None;
let commit = self.split.as_ref()?.box_of().unwrap_or(1);
self.split.as_mut()?.assign_file(Some(commit));
}
KeyCode::Char('d') => self.split.as_mut()?.assign_file(None),
KeyCode::Char('A') => {
self.visual = None;
self.split.as_mut()?.assign_all(Some(1));
}
KeyCode::Char('C') => {
self.visual = None;
self.split.as_mut()?.assign_all(None);
}
_ => return None,
}
// Keep the hunk on screen in step with the row under the cursor.
if self.overview.is_some() {
self.overview = hunk_rows.get(to).copied();
}
if let (Some(at), Some(split)) = (self.overview, self.split.as_mut()) {
if let Some(id) = rows.get(at).and_then(|r| r.hunk) {
split.go_to(id);
}
let hunk = split.at();
self.diff.show_hunk(hunk);
}
None
}
/// Open the list with the cursor on the hunk on screen, optionally
/// starting a visual selection there.
fn open_overview(&mut self, select: bool) {
let rows = self.overview_rows();
let at = self.split.as_ref().map_or(0, Split::at);
self.overview = rows
.iter()
.enumerate()
.filter(|(_, r)| r.hunk.is_some())
.nth(at)
.map(|(i, _)| i);
self.visual = (select && self.overview.is_some()).then_some(at);
// The symbols cost a subprocess each, so only now are they wanted.
if self.symbols.is_empty() {
self.pending = Some(app::Request::Symbols);
}
}
/// Deciding one hunk at a time: add it, skip it, or move around.
pub(super) fn split_key(&mut self, code: KeyCode, ctrl: bool) -> Option<Exit> {
if self.overview.is_some() {
return self.overview_key(code, ctrl);
}
// A divided hunk takes the keys over: the cursor is a line now, and
// a digit decides that line rather than the whole hunk.
if self.split.as_ref().is_some_and(Split::is_divided) {
return self.divided_key(code, ctrl);
}
match code {
KeyCode::Char('f') => {
self.open_overview(false);
return None;
}
// Selecting happens in the list, so `V` opens it already
// selecting from the hunk on screen.
KeyCode::Char('v' | 'V') => {
self.open_overview(true);
return None;
}
// Open this hunk up so its lines can go to different commits.
KeyCode::Char('e') => {
let at = self.split.as_ref()?.at();
let lines = self.hunk_lines(at);
let count = lines.len();
self.visual_line = None;
self.split.as_mut()?.divide(lines);
if self.split.as_ref().is_some_and(Split::is_divided) {
self.diff.show_hunk(at);
} else {
self.status = Some(Status::Info(format!(
"nothing to divide: this hunk changes {count} line{}",
if count == 1 { "" } else { "s" }
)));
}
return None;
}
_ => {}
}
// Scrolling, for a hunk taller than the pane.
match code {
KeyCode::Char('d') if ctrl => {
self.diff.scroll_down(self.diff.half_page());
return None;
}
KeyCode::Char('u') if ctrl => {
self.diff.scroll_up(self.diff.half_page());
return None;
}
KeyCode::Char('j') | KeyCode::Down => {
self.diff.scroll_down(1);
return None;
}
KeyCode::Char('k') | KeyCode::Up => {
self.diff.scroll_up(1);
return None;
}
KeyCode::Esc | KeyCode::Char('q') => {
self.cancel_split();
return None;
}
// Done marking, whether or not every hunk has been seen.
KeyCode::Enter => {
self.write_message();
return None;
}
_ => {}
}
let split = self.split.as_mut()?;
match code {
// A digit is the box; the same digit again takes it back out.
KeyCode::Char(c @ '1'..='9') => split.toggle(digit(c)),
KeyCode::Char(' ') => split.toggle(1),
KeyCode::Char('0') => split.assign(None),
// `y` reads as it does in `git add -p`, except that it is not
// final: a hunk can be moved or taken out later.
KeyCode::Char('y') => {
split.assign(Some(1));
split.next();
}
KeyCode::Char('n' | '}') | KeyCode::Right => split.next(),
KeyCode::Char('p' | '{') | KeyCode::Left => split.prev(),
// The file joins whichever commit this hunk is already in.
KeyCode::Char('a') => {
let commit = split.box_of().unwrap_or(1);
split.assign_file(Some(commit));
}
KeyCode::Char('d') => split.assign_file(None),
KeyCode::Char('A') => split.assign_all(Some(1)),
KeyCode::Char('C') => split.assign_all(None),
KeyCode::Char('g') => split.first(),
KeyCode::Char('G') => split.last(),
_ => return None,
}
if let Some(at) = self.split.as_ref().map(Split::at) {
self.diff.show_hunk(at);
}
None
}
/// The `+`/`-` lines of one hunk, as [`Split::divide`] wants them.
fn hunk_lines(&self, at: usize) -> Vec<usize> {
let Some(id) = self.diff.hunks().get(at).map(|h| h.id) else {
return Vec::new();
};
let patch = self.diff.patch();
patch
.files()
.get(id.file)
.and_then(|f| f.hunks.get(id.hunk))
.map_or_else(Vec::new, |hunk| patch.changed_lines(hunk))
}
/// Deciding one line at a time, inside a hunk that has been opened up.
///
/// Only the keys that mean something here are handled: `j`/`k` move
/// between the hunk's own lines, so the pane no longer scrolls, and
/// `Ctrl-d`/`Ctrl-u` are what a hunk taller than the pane is read with.
fn divided_key(&mut self, code: KeyCode, ctrl: bool) -> Option<Exit> {
let half = self.diff.half_page();
match code {
// Close it. Lines that all agree fold back into the hunk.
KeyCode::Char('e') => {
self.visual_line = None;
self.split.as_mut()?.undivide();
if self.split.as_ref().is_some_and(Split::is_divided) {
self.status = Some(Status::Info(
"the lines of this hunk go to different commits, so it stays divided"
.into(),
));
}
}
// Selecting a run of lines. A `-`/`+` pair is the common one:
// `v j 1` sends a rename to commit 1 in one gesture.
KeyCode::Char('v' | 'V') => {
let at = self.split.as_ref()?.line_at();
self.visual_line = if self.visual_line.is_some() {
None
} else {
Some(at)
};
}
// Vim's `o`: jump to the other end of the selection.
KeyCode::Char('o') if self.visual_line.is_some() => {
let at = self.split.as_ref()?.line_at();
let other = self.visual_line.replace(at)?;
self.split.as_mut()?.go_to_line(other);
}
// Motions. A selection stretches as the cursor moves, so these
// need no special case.
KeyCode::Char('d') if ctrl => {
let to = self.split.as_ref()?.line_at() + half;
self.split.as_mut()?.go_to_line(to);
}
KeyCode::Char('u') if ctrl => {
let to = self.split.as_ref()?.line_at().saturating_sub(half);
self.split.as_mut()?.go_to_line(to);
}
KeyCode::Char('j' | 'n') | KeyCode::Down => self.split.as_mut()?.next_line(),
KeyCode::Char('k' | 'p') | KeyCode::Up => self.split.as_mut()?.prev_line(),
KeyCode::Char('g') | KeyCode::Home => self.split.as_mut()?.first_line(),
KeyCode::Char('G') | KeyCode::End => self.split.as_mut()?.last_line(),
// Assigning, to the line or to the whole selection. Either way
// the selection ends once it has been used, as in Vim.
KeyCode::Char(c @ ('1'..='9' | ' ')) => {
let commit = if c == ' ' { 1 } else { digit(c) };
let at = self.split.as_ref()?.line_at();
let split = self.split.as_mut()?;
match self.visual_line.take() {
Some(from) => split.toggle_line_range(from, at, commit),
None => split.toggle_line(commit),
}
}
KeyCode::Char('0') => {
let at = self.split.as_ref()?.line_at();
let split = self.split.as_mut()?;
match self.visual_line.take() {
Some(from) => split.assign_line_range(from, at, None),
None => split.assign_line(None),
}
}
// `d`/`x` on a selection take it out, as Vim's would delete it.
KeyCode::Char('d' | 'x') if self.visual_line.is_some() => {
let at = self.split.as_ref()?.line_at();
let from = self.visual_line.take()?;
self.split.as_mut()?.assign_line_range(from, at, None);
}
// As in the hunk view: not final, just quicker.
KeyCode::Char('y') => {
self.visual_line = None;
let split = self.split.as_mut()?;
split.assign_line(Some(1));
split.next_line();
}
// `Esc` drops the selection first, and only then leaves.
KeyCode::Esc if self.visual_line.is_some() => self.visual_line = None,
KeyCode::Esc | KeyCode::Char('q') => {
self.visual_line = None;
self.cancel_split();
}
KeyCode::Enter => {
self.visual_line = None;
self.write_message();
}
_ => {}
}
None
}
pub(super) fn start_split(&mut self) {
match Split::new(self.splittable()) {
Some(split) => self.enter_split(split),
None => {
self.status = Some(Status::Error(
"nothing to split: this change has one hunk with one change in it".into(),
));
}
}
}
fn cancel_split(&mut self) {
self.visual_line = None;
self.split = None;
self.zoomed = false;
self.focus = Focus::Editor;
self.status = Some(Status::Info("Left split mode.".into()));
}
/// Leave the plan as it is and go write the next commit's message.
fn write_message(&mut self) {
let (commit, held, planned) = self.split.as_ref().map_or((0, 0, 0), |split| {
(
split.next_box().unwrap_or(0),
split.next_box().map_or(0, |n| split.count(n)),
split.pending().len(),
)
});
self.zoomed = false;
self.focus = Focus::Editor;
self.status = Some(Status::Info(if planned == 0 {
"Nothing assigned yet. 1-9 puts the hunk on screen in a commit.".to_owned()
} else {
format!(
"Describing commit {commit} of {planned}: {held} {}. ^s commits it.",
app::plural(held, "hunk")
)
}));
}
/// Start choosing hunks for a commit, showing the first on its own.
/// The warning to open with when this revision is protected history.
pub(super) fn immutable_warning(&self) -> Option<Status> {
if !self.target.immutable {
return None;
}
let tags: Vec<&str> = self.at_risk.iter().map(|t| t.tag.as_str()).collect();
Some(Status::Error(if tags.is_empty() {
"immutable revision: rewriting it gives every later commit a new hash".to_owned()
} else {
format!(
"immutable revision: a rewrite strands {} {} ({})",
tags.len(),
app::plural(tags.len(), "tag"),
tags.join(", ")
)
}))
}
}
/// Where `]` (forward) or `[` lands from hunk `here`, given each hunk's
/// file: the next file's first hunk, or this file's first hunk (the
/// previous file's, if already there). Past either end it stops on the
/// first or last hunk, so `V ]` on the last file selects to the end.
fn file_jump(files: &[usize], here: usize, forward: bool) -> usize {
let last = files.len().saturating_sub(1);
let start_of = |k: usize| {
(0..=k)
.rev()
.take_while(|&i| files[i] == files[k])
.last()
.unwrap_or(k)
};
if forward {
(here..=last)
.find(|&k| files[k] != files[here])
.unwrap_or(last)
} else {
let first = start_of(here);
if first < here {
first
} else {
first.checked_sub(1).map_or(0, start_of)
}
}
}
/// A digit key as the commit number it names.
fn digit(c: char) -> u8 {
u8::try_from(c.to_digit(10).unwrap_or(1)).unwrap_or(1)
}
#[cfg(test)]
mod tests {
use super::file_jump;
#[test]
fn file_jumps_land_on_file_boundaries() {
// Hunks 0-2 in file 0, 3-4 in file 1, 5 in file 2.
let files = [0, 0, 0, 1, 1, 2];
assert_eq!(file_jump(&files, 1, true), 3);
assert_eq!(file_jump(&files, 3, true), 5);
assert_eq!(
file_jump(&files, 5, true),
5,
"the last file stops at its end"
);
assert_eq!(file_jump(&files, 4, false), 3, "this file's start");
assert_eq!(file_jump(&files, 3, false), 0, "then the previous file's");
assert_eq!(file_jump(&files, 0, false), 0);
}
}