Decorate replaced commits
[tig.git] / tig.c
blobc9e8d1d9388c36d5c6d008c069602e096ac1a20a
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24 char id[SIZEOF_REV]; /* Commit SHA1 ID */
25 unsigned int head:1; /* Is it the current HEAD? */
26 unsigned int tag:1; /* Is it a tag? */
27 unsigned int ltag:1; /* If so, is the tag local? */
28 unsigned int remote:1; /* Is it a remote ref? */
29 unsigned int replace:1; /* Is it a replace ref? */
30 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
31 char name[1]; /* Ref name; tag or head names are shortened. */
34 struct ref_list {
35 char id[SIZEOF_REV]; /* Commit SHA1 ID */
36 size_t size; /* Number of refs. */
37 struct ref **refs; /* References for this ID. */
40 static struct ref *get_ref_head();
41 static struct ref_list *get_ref_list(const char *id);
42 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
43 static int load_refs(void);
45 enum input_status {
46 INPUT_OK,
47 INPUT_SKIP,
48 INPUT_STOP,
49 INPUT_CANCEL
52 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
54 static char *prompt_input(const char *prompt, input_handler handler, void *data);
55 static bool prompt_yesno(const char *prompt);
57 struct menu_item {
58 int hotkey;
59 const char *text;
60 void *data;
63 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
65 #define GRAPHIC_ENUM(_) \
66 _(GRAPHIC, ASCII), \
67 _(GRAPHIC, DEFAULT), \
68 _(GRAPHIC, UTF_8)
70 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
72 #define DATE_ENUM(_) \
73 _(DATE, NO), \
74 _(DATE, DEFAULT), \
75 _(DATE, LOCAL), \
76 _(DATE, RELATIVE), \
77 _(DATE, SHORT)
79 DEFINE_ENUM(date, DATE_ENUM);
81 struct time {
82 time_t sec;
83 int tz;
86 static inline int timecmp(const struct time *t1, const struct time *t2)
88 return t1->sec - t2->sec;
91 static const char *
92 mkdate(const struct time *time, enum date date)
94 static char buf[DATE_COLS + 1];
95 static const struct enum_map reldate[] = {
96 { "second", 1, 60 * 2 },
97 { "minute", 60, 60 * 60 * 2 },
98 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
99 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
100 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
101 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
103 struct tm tm;
105 if (!date || !time || !time->sec)
106 return "";
108 if (date == DATE_RELATIVE) {
109 struct timeval now;
110 time_t date = time->sec + time->tz;
111 time_t seconds;
112 int i;
114 gettimeofday(&now, NULL);
115 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
116 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
117 if (seconds >= reldate[i].value)
118 continue;
120 seconds /= reldate[i].namelen;
121 if (!string_format(buf, "%ld %s%s %s",
122 seconds, reldate[i].name,
123 seconds > 1 ? "s" : "",
124 now.tv_sec >= date ? "ago" : "ahead"))
125 break;
126 return buf;
130 if (date == DATE_LOCAL) {
131 time_t date = time->sec + time->tz;
132 localtime_r(&date, &tm);
134 else {
135 gmtime_r(&time->sec, &tm);
137 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
141 #define AUTHOR_ENUM(_) \
142 _(AUTHOR, NO), \
143 _(AUTHOR, FULL), \
144 _(AUTHOR, ABBREVIATED)
146 DEFINE_ENUM(author, AUTHOR_ENUM);
148 static const char *
149 get_author_initials(const char *author)
151 static char initials[AUTHOR_COLS * 6 + 1];
152 size_t pos = 0;
153 const char *end = strchr(author, '\0');
155 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
157 memset(initials, 0, sizeof(initials));
158 while (author < end) {
159 unsigned char bytes;
160 size_t i;
162 while (author < end && is_initial_sep(*author))
163 author++;
165 bytes = utf8_char_length(author, end);
166 if (bytes >= sizeof(initials) - 1 - pos)
167 break;
168 while (bytes--) {
169 initials[pos++] = *author++;
172 i = pos;
173 while (author < end && !is_initial_sep(*author)) {
174 bytes = utf8_char_length(author, end);
175 if (bytes >= sizeof(initials) - 1 - i) {
176 while (author < end && !is_initial_sep(*author))
177 author++;
178 break;
180 while (bytes--) {
181 initials[i++] = *author++;
185 initials[i++] = 0;
188 return initials;
191 #define author_trim(cols) (cols == 0 || cols > 5)
193 static const char *
194 mkauthor(const char *text, int cols, enum author author)
196 bool trim = author_trim(cols);
197 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
199 if (author == AUTHOR_NO)
200 return "";
201 if (abbreviate && text)
202 return get_author_initials(text);
203 return text;
206 static const char *
207 mkmode(mode_t mode)
209 if (S_ISDIR(mode))
210 return "drwxr-xr-x";
211 else if (S_ISLNK(mode))
212 return "lrwxrwxrwx";
213 else if (S_ISGITLINK(mode))
214 return "m---------";
215 else if (S_ISREG(mode) && mode & S_IXUSR)
216 return "-rwxr-xr-x";
217 else if (S_ISREG(mode))
218 return "-rw-r--r--";
219 else
220 return "----------";
225 * User requests
228 #define REQ_INFO \
229 /* XXX: Keep the view request first and in sync with views[]. */ \
230 REQ_GROUP("View switching") \
231 REQ_(VIEW_MAIN, "Show main view"), \
232 REQ_(VIEW_DIFF, "Show diff view"), \
233 REQ_(VIEW_LOG, "Show log view"), \
234 REQ_(VIEW_TREE, "Show tree view"), \
235 REQ_(VIEW_BLOB, "Show blob view"), \
236 REQ_(VIEW_BLAME, "Show blame view"), \
237 REQ_(VIEW_BRANCH, "Show branch view"), \
238 REQ_(VIEW_HELP, "Show help page"), \
239 REQ_(VIEW_PAGER, "Show pager view"), \
240 REQ_(VIEW_STATUS, "Show status view"), \
241 REQ_(VIEW_STAGE, "Show stage view"), \
243 REQ_GROUP("View manipulation") \
244 REQ_(ENTER, "Enter current line and scroll"), \
245 REQ_(NEXT, "Move to next"), \
246 REQ_(PREVIOUS, "Move to previous"), \
247 REQ_(PARENT, "Move to parent"), \
248 REQ_(VIEW_NEXT, "Move focus to next view"), \
249 REQ_(REFRESH, "Reload and refresh"), \
250 REQ_(MAXIMIZE, "Maximize the current view"), \
251 REQ_(VIEW_CLOSE, "Close the current view"), \
252 REQ_(QUIT, "Close all views and quit"), \
254 REQ_GROUP("View specific requests") \
255 REQ_(STATUS_UPDATE, "Update file status"), \
256 REQ_(STATUS_REVERT, "Revert file changes"), \
257 REQ_(STATUS_MERGE, "Merge file using external tool"), \
258 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
259 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
260 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
262 REQ_GROUP("Cursor navigation") \
263 REQ_(MOVE_UP, "Move cursor one line up"), \
264 REQ_(MOVE_DOWN, "Move cursor one line down"), \
265 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
266 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
267 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
268 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
270 REQ_GROUP("Scrolling") \
271 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
272 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
273 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
274 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
275 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
276 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
277 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
279 REQ_GROUP("Searching") \
280 REQ_(SEARCH, "Search the view"), \
281 REQ_(SEARCH_BACK, "Search backwards in the view"), \
282 REQ_(FIND_NEXT, "Find next search match"), \
283 REQ_(FIND_PREV, "Find previous search match"), \
285 REQ_GROUP("Option manipulation") \
286 REQ_(OPTIONS, "Open option menu"), \
287 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
288 REQ_(TOGGLE_DATE, "Toggle date display"), \
289 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
290 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
291 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
292 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
293 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
294 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
296 REQ_GROUP("Misc") \
297 REQ_(PROMPT, "Bring up the prompt"), \
298 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
299 REQ_(SHOW_VERSION, "Show version information"), \
300 REQ_(STOP_LOADING, "Stop all loading views"), \
301 REQ_(EDIT, "Open in editor"), \
302 REQ_(NONE, "Do nothing")
305 /* User action requests. */
306 enum request {
307 #define REQ_GROUP(help)
308 #define REQ_(req, help) REQ_##req
310 /* Offset all requests to avoid conflicts with ncurses getch values. */
311 REQ_UNKNOWN = KEY_MAX + 1,
312 REQ_OFFSET,
313 REQ_INFO
315 #undef REQ_GROUP
316 #undef REQ_
319 struct request_info {
320 enum request request;
321 const char *name;
322 int namelen;
323 const char *help;
326 static const struct request_info req_info[] = {
327 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
328 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
329 REQ_INFO
330 #undef REQ_GROUP
331 #undef REQ_
334 static enum request
335 get_request(const char *name)
337 int namelen = strlen(name);
338 int i;
340 for (i = 0; i < ARRAY_SIZE(req_info); i++)
341 if (enum_equals(req_info[i], name, namelen))
342 return req_info[i].request;
344 return REQ_UNKNOWN;
349 * Options
352 /* Option and state variables. */
353 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
354 static enum date opt_date = DATE_DEFAULT;
355 static enum author opt_author = AUTHOR_FULL;
356 static bool opt_rev_graph = TRUE;
357 static bool opt_line_number = FALSE;
358 static bool opt_show_refs = TRUE;
359 static bool opt_untracked_dirs_content = TRUE;
360 static int opt_diff_context = 3;
361 static char opt_diff_context_arg[9] = "";
362 static int opt_num_interval = 5;
363 static double opt_hscroll = 0.50;
364 static double opt_scale_split_view = 2.0 / 3.0;
365 static int opt_tab_size = 8;
366 static int opt_author_cols = AUTHOR_COLS;
367 static char opt_path[SIZEOF_STR] = "";
368 static char opt_file[SIZEOF_STR] = "";
369 static char opt_ref[SIZEOF_REF] = "";
370 static unsigned long opt_goto_line = 0;
371 static char opt_head[SIZEOF_REF] = "";
372 static char opt_remote[SIZEOF_REF] = "";
373 static char opt_encoding[20] = "UTF-8";
374 static iconv_t opt_iconv_in = ICONV_NONE;
375 static iconv_t opt_iconv_out = ICONV_NONE;
376 static char opt_search[SIZEOF_STR] = "";
377 static char opt_cdup[SIZEOF_STR] = "";
378 static char opt_prefix[SIZEOF_STR] = "";
379 static char opt_git_dir[SIZEOF_STR] = "";
380 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
381 static char opt_editor[SIZEOF_STR] = "";
382 static FILE *opt_tty = NULL;
383 static const char **opt_diff_argv = NULL;
384 static const char **opt_rev_argv = NULL;
385 static const char **opt_file_argv = NULL;
386 static const char **opt_blame_argv = NULL;
388 #define is_initial_commit() (!get_ref_head())
389 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
391 static inline void
392 update_diff_context_arg(int diff_context)
394 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
395 string_ncopy(opt_diff_context_arg, "-U3", 3);
399 * Line-oriented content detection.
402 #define LINE_INFO \
403 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
404 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
405 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
406 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
407 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
408 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
409 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
410 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
411 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
412 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
413 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
414 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
415 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
416 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
417 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
418 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
419 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
420 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
421 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
422 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
423 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
424 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
425 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
426 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
427 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
428 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
429 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
430 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
431 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
432 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
433 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
434 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
435 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
436 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
437 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
438 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
439 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
440 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
441 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
442 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
443 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
444 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
445 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
446 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
447 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
448 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
449 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
450 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
451 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
452 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
453 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
454 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
455 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
456 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
457 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
458 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
459 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
460 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
461 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
462 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
463 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
464 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
465 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
466 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
467 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
468 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
469 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
470 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
471 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
472 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
473 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
475 enum line_type {
476 #define LINE(type, line, fg, bg, attr) \
477 LINE_##type
478 LINE_INFO,
479 LINE_NONE
480 #undef LINE
483 struct line_info {
484 const char *name; /* Option name. */
485 int namelen; /* Size of option name. */
486 const char *line; /* The start of line to match. */
487 int linelen; /* Size of string to match. */
488 int fg, bg, attr; /* Color and text attributes for the lines. */
491 static struct line_info line_info[] = {
492 #define LINE(type, line, fg, bg, attr) \
493 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
494 LINE_INFO
495 #undef LINE
498 static enum line_type
499 get_line_type(const char *line)
501 int linelen = strlen(line);
502 enum line_type type;
504 for (type = 0; type < ARRAY_SIZE(line_info); type++)
505 /* Case insensitive search matches Signed-off-by lines better. */
506 if (linelen >= line_info[type].linelen &&
507 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
508 return type;
510 return LINE_DEFAULT;
513 static enum line_type
514 get_line_type_from_ref(const struct ref *ref)
516 if (ref->head)
517 return LINE_MAIN_HEAD;
518 else if (ref->ltag)
519 return LINE_MAIN_LOCAL_TAG;
520 else if (ref->tag)
521 return LINE_MAIN_TAG;
522 else if (ref->tracked)
523 return LINE_MAIN_TRACKED;
524 else if (ref->remote)
525 return LINE_MAIN_REMOTE;
526 else if (ref->replace)
527 return LINE_MAIN_REPLACE;
529 return LINE_MAIN_REF;
532 static inline int
533 get_line_attr(enum line_type type)
535 assert(type < ARRAY_SIZE(line_info));
536 return COLOR_PAIR(type) | line_info[type].attr;
539 static struct line_info *
540 get_line_info(const char *name)
542 size_t namelen = strlen(name);
543 enum line_type type;
545 for (type = 0; type < ARRAY_SIZE(line_info); type++)
546 if (enum_equals(line_info[type], name, namelen))
547 return &line_info[type];
549 return NULL;
552 static void
553 init_colors(void)
555 int default_bg = line_info[LINE_DEFAULT].bg;
556 int default_fg = line_info[LINE_DEFAULT].fg;
557 enum line_type type;
559 start_color();
561 if (assume_default_colors(default_fg, default_bg) == ERR) {
562 default_bg = COLOR_BLACK;
563 default_fg = COLOR_WHITE;
566 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
567 struct line_info *info = &line_info[type];
568 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
569 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
571 init_pair(type, fg, bg);
575 struct line {
576 enum line_type type;
578 /* State flags */
579 unsigned int selected:1;
580 unsigned int dirty:1;
581 unsigned int cleareol:1;
582 unsigned int other:16;
584 void *data; /* User data */
589 * Keys
592 struct keybinding {
593 int alias;
594 enum request request;
597 static struct keybinding default_keybindings[] = {
598 /* View switching */
599 { 'm', REQ_VIEW_MAIN },
600 { 'd', REQ_VIEW_DIFF },
601 { 'l', REQ_VIEW_LOG },
602 { 't', REQ_VIEW_TREE },
603 { 'f', REQ_VIEW_BLOB },
604 { 'B', REQ_VIEW_BLAME },
605 { 'H', REQ_VIEW_BRANCH },
606 { 'p', REQ_VIEW_PAGER },
607 { 'h', REQ_VIEW_HELP },
608 { 'S', REQ_VIEW_STATUS },
609 { 'c', REQ_VIEW_STAGE },
611 /* View manipulation */
612 { 'q', REQ_VIEW_CLOSE },
613 { KEY_TAB, REQ_VIEW_NEXT },
614 { KEY_RETURN, REQ_ENTER },
615 { KEY_UP, REQ_PREVIOUS },
616 { KEY_CTL('P'), REQ_PREVIOUS },
617 { KEY_DOWN, REQ_NEXT },
618 { KEY_CTL('N'), REQ_NEXT },
619 { 'R', REQ_REFRESH },
620 { KEY_F(5), REQ_REFRESH },
621 { 'O', REQ_MAXIMIZE },
622 { ',', REQ_PARENT },
624 /* View specific */
625 { 'u', REQ_STATUS_UPDATE },
626 { '!', REQ_STATUS_REVERT },
627 { 'M', REQ_STATUS_MERGE },
628 { '@', REQ_STAGE_NEXT },
629 { '[', REQ_DIFF_CONTEXT_DOWN },
630 { ']', REQ_DIFF_CONTEXT_UP },
632 /* Cursor navigation */
633 { 'k', REQ_MOVE_UP },
634 { 'j', REQ_MOVE_DOWN },
635 { KEY_HOME, REQ_MOVE_FIRST_LINE },
636 { KEY_END, REQ_MOVE_LAST_LINE },
637 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
638 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
639 { ' ', REQ_MOVE_PAGE_DOWN },
640 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
641 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
642 { 'b', REQ_MOVE_PAGE_UP },
643 { '-', REQ_MOVE_PAGE_UP },
645 /* Scrolling */
646 { '|', REQ_SCROLL_FIRST_COL },
647 { KEY_LEFT, REQ_SCROLL_LEFT },
648 { KEY_RIGHT, REQ_SCROLL_RIGHT },
649 { KEY_IC, REQ_SCROLL_LINE_UP },
650 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
651 { KEY_DC, REQ_SCROLL_LINE_DOWN },
652 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
653 { 'w', REQ_SCROLL_PAGE_UP },
654 { 's', REQ_SCROLL_PAGE_DOWN },
656 /* Searching */
657 { '/', REQ_SEARCH },
658 { '?', REQ_SEARCH_BACK },
659 { 'n', REQ_FIND_NEXT },
660 { 'N', REQ_FIND_PREV },
662 /* Misc */
663 { 'Q', REQ_QUIT },
664 { 'z', REQ_STOP_LOADING },
665 { 'v', REQ_SHOW_VERSION },
666 { 'r', REQ_SCREEN_REDRAW },
667 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
668 { 'o', REQ_OPTIONS },
669 { '.', REQ_TOGGLE_LINENO },
670 { 'D', REQ_TOGGLE_DATE },
671 { 'A', REQ_TOGGLE_AUTHOR },
672 { 'g', REQ_TOGGLE_REV_GRAPH },
673 { '~', REQ_TOGGLE_GRAPHIC },
674 { 'F', REQ_TOGGLE_REFS },
675 { 'I', REQ_TOGGLE_SORT_ORDER },
676 { 'i', REQ_TOGGLE_SORT_FIELD },
677 { ':', REQ_PROMPT },
678 { 'e', REQ_EDIT },
681 #define KEYMAP_ENUM(_) \
682 _(KEYMAP, GENERIC), \
683 _(KEYMAP, MAIN), \
684 _(KEYMAP, DIFF), \
685 _(KEYMAP, LOG), \
686 _(KEYMAP, TREE), \
687 _(KEYMAP, BLOB), \
688 _(KEYMAP, BLAME), \
689 _(KEYMAP, BRANCH), \
690 _(KEYMAP, PAGER), \
691 _(KEYMAP, HELP), \
692 _(KEYMAP, STATUS), \
693 _(KEYMAP, STAGE)
695 DEFINE_ENUM(keymap, KEYMAP_ENUM);
697 #define set_keymap(map, name) map_enum(map, keymap_map, name)
699 struct keybinding_table {
700 struct keybinding *data;
701 size_t size;
704 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
706 static void
707 add_keybinding(enum keymap keymap, enum request request, int key)
709 struct keybinding_table *table = &keybindings[keymap];
710 size_t i;
712 for (i = 0; i < keybindings[keymap].size; i++) {
713 if (keybindings[keymap].data[i].alias == key) {
714 keybindings[keymap].data[i].request = request;
715 return;
719 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
720 if (!table->data)
721 die("Failed to allocate keybinding");
722 table->data[table->size].alias = key;
723 table->data[table->size++].request = request;
725 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
726 int i;
728 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
729 if (default_keybindings[i].alias == key)
730 default_keybindings[i].request = REQ_NONE;
734 /* Looks for a key binding first in the given map, then in the generic map, and
735 * lastly in the default keybindings. */
736 static enum request
737 get_keybinding(enum keymap keymap, int key)
739 size_t i;
741 for (i = 0; i < keybindings[keymap].size; i++)
742 if (keybindings[keymap].data[i].alias == key)
743 return keybindings[keymap].data[i].request;
745 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
746 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
747 return keybindings[KEYMAP_GENERIC].data[i].request;
749 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
750 if (default_keybindings[i].alias == key)
751 return default_keybindings[i].request;
753 return (enum request) key;
757 struct key {
758 const char *name;
759 int value;
762 static const struct key key_table[] = {
763 { "Enter", KEY_RETURN },
764 { "Space", ' ' },
765 { "Backspace", KEY_BACKSPACE },
766 { "Tab", KEY_TAB },
767 { "Escape", KEY_ESC },
768 { "Left", KEY_LEFT },
769 { "Right", KEY_RIGHT },
770 { "Up", KEY_UP },
771 { "Down", KEY_DOWN },
772 { "Insert", KEY_IC },
773 { "Delete", KEY_DC },
774 { "Hash", '#' },
775 { "Home", KEY_HOME },
776 { "End", KEY_END },
777 { "PageUp", KEY_PPAGE },
778 { "PageDown", KEY_NPAGE },
779 { "F1", KEY_F(1) },
780 { "F2", KEY_F(2) },
781 { "F3", KEY_F(3) },
782 { "F4", KEY_F(4) },
783 { "F5", KEY_F(5) },
784 { "F6", KEY_F(6) },
785 { "F7", KEY_F(7) },
786 { "F8", KEY_F(8) },
787 { "F9", KEY_F(9) },
788 { "F10", KEY_F(10) },
789 { "F11", KEY_F(11) },
790 { "F12", KEY_F(12) },
793 static int
794 get_key_value(const char *name)
796 int i;
798 for (i = 0; i < ARRAY_SIZE(key_table); i++)
799 if (!strcasecmp(key_table[i].name, name))
800 return key_table[i].value;
802 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
803 return (int)name[1] & 0x1f;
804 if (strlen(name) == 1 && isprint(*name))
805 return (int) *name;
806 return ERR;
809 static const char *
810 get_key_name(int key_value)
812 static char key_char[] = "'X'\0";
813 const char *seq = NULL;
814 int key;
816 for (key = 0; key < ARRAY_SIZE(key_table); key++)
817 if (key_table[key].value == key_value)
818 seq = key_table[key].name;
820 if (seq == NULL && key_value < 0x7f) {
821 char *s = key_char + 1;
823 if (key_value >= 0x20) {
824 *s++ = key_value;
825 } else {
826 *s++ = '^';
827 *s++ = 0x40 | (key_value & 0x1f);
829 *s++ = '\'';
830 *s++ = '\0';
831 seq = key_char;
834 return seq ? seq : "(no key)";
837 static bool
838 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
840 const char *sep = *pos > 0 ? ", " : "";
841 const char *keyname = get_key_name(keybinding->alias);
843 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
846 static bool
847 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
848 enum keymap keymap, bool all)
850 int i;
852 for (i = 0; i < keybindings[keymap].size; i++) {
853 if (keybindings[keymap].data[i].request == request) {
854 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
855 return FALSE;
856 if (!all)
857 break;
861 return TRUE;
864 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
866 static const char *
867 get_keys(enum keymap keymap, enum request request, bool all)
869 static char buf[BUFSIZ];
870 size_t pos = 0;
871 int i;
873 buf[pos] = 0;
875 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
876 return "Too many keybindings!";
877 if (pos > 0 && !all)
878 return buf;
880 if (keymap != KEYMAP_GENERIC) {
881 /* Only the generic keymap includes the default keybindings when
882 * listing all keys. */
883 if (all)
884 return buf;
886 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
887 return "Too many keybindings!";
888 if (pos)
889 return buf;
892 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
893 if (default_keybindings[i].request == request) {
894 if (!append_key(buf, &pos, &default_keybindings[i]))
895 return "Too many keybindings!";
896 if (!all)
897 return buf;
901 return buf;
904 struct run_request {
905 enum keymap keymap;
906 int key;
907 const char **argv;
910 static struct run_request *run_request;
911 static size_t run_requests;
913 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
915 static enum request
916 add_run_request(enum keymap keymap, int key, const char **argv)
918 struct run_request *req;
920 if (!realloc_run_requests(&run_request, run_requests, 1))
921 return REQ_NONE;
923 req = &run_request[run_requests];
924 req->keymap = keymap;
925 req->key = key;
926 req->argv = NULL;
928 if (!argv_copy(&req->argv, argv))
929 return REQ_NONE;
931 return REQ_NONE + ++run_requests;
934 static struct run_request *
935 get_run_request(enum request request)
937 if (request <= REQ_NONE)
938 return NULL;
939 return &run_request[request - REQ_NONE - 1];
942 static void
943 add_builtin_run_requests(void)
945 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
946 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
947 const char *commit[] = { "git", "commit", NULL };
948 const char *gc[] = { "git", "gc", NULL };
949 struct run_request reqs[] = {
950 { KEYMAP_MAIN, 'C', cherry_pick },
951 { KEYMAP_STATUS, 'C', commit },
952 { KEYMAP_BRANCH, 'C', checkout },
953 { KEYMAP_GENERIC, 'G', gc },
955 int i;
957 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
958 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
960 if (req != reqs[i].key)
961 continue;
962 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
963 if (req != REQ_NONE)
964 add_keybinding(reqs[i].keymap, req, reqs[i].key);
969 * User config file handling.
972 #define OPT_ERR_INFO \
973 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
974 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
975 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
976 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
977 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
978 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
979 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
980 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
981 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
982 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
983 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
984 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
985 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
986 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
987 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
988 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
989 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
991 enum option_code {
992 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
993 OPT_ERR_INFO
994 #undef OPT_ERR_
995 OPT_OK
998 static const char *option_errors[] = {
999 #define OPT_ERR_(name, msg) msg
1000 OPT_ERR_INFO
1001 #undef OPT_ERR_
1004 static const struct enum_map color_map[] = {
1005 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1006 COLOR_MAP(DEFAULT),
1007 COLOR_MAP(BLACK),
1008 COLOR_MAP(BLUE),
1009 COLOR_MAP(CYAN),
1010 COLOR_MAP(GREEN),
1011 COLOR_MAP(MAGENTA),
1012 COLOR_MAP(RED),
1013 COLOR_MAP(WHITE),
1014 COLOR_MAP(YELLOW),
1017 static const struct enum_map attr_map[] = {
1018 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1019 ATTR_MAP(NORMAL),
1020 ATTR_MAP(BLINK),
1021 ATTR_MAP(BOLD),
1022 ATTR_MAP(DIM),
1023 ATTR_MAP(REVERSE),
1024 ATTR_MAP(STANDOUT),
1025 ATTR_MAP(UNDERLINE),
1028 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1030 static enum option_code
1031 parse_step(double *opt, const char *arg)
1033 *opt = atoi(arg);
1034 if (!strchr(arg, '%'))
1035 return OPT_OK;
1037 /* "Shift down" so 100% and 1 does not conflict. */
1038 *opt = (*opt - 1) / 100;
1039 if (*opt >= 1.0) {
1040 *opt = 0.99;
1041 return OPT_ERR_INVALID_STEP_VALUE;
1043 if (*opt < 0.0) {
1044 *opt = 1;
1045 return OPT_ERR_INVALID_STEP_VALUE;
1047 return OPT_OK;
1050 static enum option_code
1051 parse_int(int *opt, const char *arg, int min, int max)
1053 int value = atoi(arg);
1055 if (min <= value && value <= max) {
1056 *opt = value;
1057 return OPT_OK;
1060 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1063 static bool
1064 set_color(int *color, const char *name)
1066 if (map_enum(color, color_map, name))
1067 return TRUE;
1068 if (!prefixcmp(name, "color"))
1069 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1070 return FALSE;
1073 /* Wants: object fgcolor bgcolor [attribute] */
1074 static enum option_code
1075 option_color_command(int argc, const char *argv[])
1077 struct line_info *info;
1079 if (argc < 3)
1080 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1082 info = get_line_info(argv[0]);
1083 if (!info) {
1084 static const struct enum_map obsolete[] = {
1085 ENUM_MAP("main-delim", LINE_DELIMITER),
1086 ENUM_MAP("main-date", LINE_DATE),
1087 ENUM_MAP("main-author", LINE_AUTHOR),
1089 int index;
1091 if (!map_enum(&index, obsolete, argv[0]))
1092 return OPT_ERR_UNKNOWN_COLOR_NAME;
1093 info = &line_info[index];
1096 if (!set_color(&info->fg, argv[1]) ||
1097 !set_color(&info->bg, argv[2]))
1098 return OPT_ERR_UNKNOWN_COLOR;
1100 info->attr = 0;
1101 while (argc-- > 3) {
1102 int attr;
1104 if (!set_attribute(&attr, argv[argc]))
1105 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1106 info->attr |= attr;
1109 return OPT_OK;
1112 static enum option_code
1113 parse_bool(bool *opt, const char *arg)
1115 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1116 ? TRUE : FALSE;
1117 return OPT_OK;
1120 static enum option_code
1121 parse_enum_do(unsigned int *opt, const char *arg,
1122 const struct enum_map *map, size_t map_size)
1124 bool is_true;
1126 assert(map_size > 1);
1128 if (map_enum_do(map, map_size, (int *) opt, arg))
1129 return OPT_OK;
1131 parse_bool(&is_true, arg);
1132 *opt = is_true ? map[1].value : map[0].value;
1133 return OPT_OK;
1136 #define parse_enum(opt, arg, map) \
1137 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1139 static enum option_code
1140 parse_string(char *opt, const char *arg, size_t optsize)
1142 int arglen = strlen(arg);
1144 switch (arg[0]) {
1145 case '\"':
1146 case '\'':
1147 if (arglen == 1 || arg[arglen - 1] != arg[0])
1148 return OPT_ERR_UNMATCHED_QUOTATION;
1149 arg += 1; arglen -= 2;
1150 default:
1151 string_ncopy_do(opt, optsize, arg, arglen);
1152 return OPT_OK;
1156 static enum option_code
1157 parse_args(const char ***args, const char *argv[])
1159 if (*args == NULL && !argv_copy(args, argv))
1160 return OPT_ERR_OUT_OF_MEMORY;
1161 return OPT_OK;
1164 /* Wants: name = value */
1165 static enum option_code
1166 option_set_command(int argc, const char *argv[])
1168 if (argc < 3)
1169 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1171 if (strcmp(argv[1], "="))
1172 return OPT_ERR_NO_VALUE_ASSIGNED;
1174 if (!strcmp(argv[0], "blame-options"))
1175 return parse_args(&opt_blame_argv, argv + 2);
1177 if (argc != 3)
1178 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1180 if (!strcmp(argv[0], "show-author"))
1181 return parse_enum(&opt_author, argv[2], author_map);
1183 if (!strcmp(argv[0], "show-date"))
1184 return parse_enum(&opt_date, argv[2], date_map);
1186 if (!strcmp(argv[0], "show-rev-graph"))
1187 return parse_bool(&opt_rev_graph, argv[2]);
1189 if (!strcmp(argv[0], "show-refs"))
1190 return parse_bool(&opt_show_refs, argv[2]);
1192 if (!strcmp(argv[0], "show-line-numbers"))
1193 return parse_bool(&opt_line_number, argv[2]);
1195 if (!strcmp(argv[0], "line-graphics"))
1196 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1198 if (!strcmp(argv[0], "line-number-interval"))
1199 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1201 if (!strcmp(argv[0], "author-width"))
1202 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1204 if (!strcmp(argv[0], "horizontal-scroll"))
1205 return parse_step(&opt_hscroll, argv[2]);
1207 if (!strcmp(argv[0], "split-view-height"))
1208 return parse_step(&opt_scale_split_view, argv[2]);
1210 if (!strcmp(argv[0], "tab-size"))
1211 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1213 if (!strcmp(argv[0], "diff-context")) {
1214 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1216 if (code == OPT_OK)
1217 update_diff_context_arg(opt_diff_context);
1218 return code;
1221 if (!strcmp(argv[0], "commit-encoding"))
1222 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1224 if (!strcmp(argv[0], "status-untracked-dirs"))
1225 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1227 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1230 /* Wants: mode request key */
1231 static enum option_code
1232 option_bind_command(int argc, const char *argv[])
1234 enum request request;
1235 int keymap = -1;
1236 int key;
1238 if (argc < 3)
1239 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1241 if (!set_keymap(&keymap, argv[0]))
1242 return OPT_ERR_UNKNOWN_KEY_MAP;
1244 key = get_key_value(argv[1]);
1245 if (key == ERR)
1246 return OPT_ERR_UNKNOWN_KEY;
1248 request = get_request(argv[2]);
1249 if (request == REQ_UNKNOWN) {
1250 static const struct enum_map obsolete[] = {
1251 ENUM_MAP("cherry-pick", REQ_NONE),
1252 ENUM_MAP("screen-resize", REQ_NONE),
1253 ENUM_MAP("tree-parent", REQ_PARENT),
1255 int alias;
1257 if (map_enum(&alias, obsolete, argv[2])) {
1258 if (alias != REQ_NONE)
1259 add_keybinding(keymap, alias, key);
1260 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1263 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1264 request = add_run_request(keymap, key, argv + 2);
1265 if (request == REQ_UNKNOWN)
1266 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1268 add_keybinding(keymap, request, key);
1270 return OPT_OK;
1273 static enum option_code
1274 set_option(const char *opt, char *value)
1276 const char *argv[SIZEOF_ARG];
1277 int argc = 0;
1279 if (!argv_from_string(argv, &argc, value))
1280 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1282 if (!strcmp(opt, "color"))
1283 return option_color_command(argc, argv);
1285 if (!strcmp(opt, "set"))
1286 return option_set_command(argc, argv);
1288 if (!strcmp(opt, "bind"))
1289 return option_bind_command(argc, argv);
1291 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1294 struct config_state {
1295 int lineno;
1296 bool errors;
1299 static int
1300 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1302 struct config_state *config = data;
1303 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1305 config->lineno++;
1307 /* Check for comment markers, since read_properties() will
1308 * only ensure opt and value are split at first " \t". */
1309 optlen = strcspn(opt, "#");
1310 if (optlen == 0)
1311 return OK;
1313 if (opt[optlen] == 0) {
1314 /* Look for comment endings in the value. */
1315 size_t len = strcspn(value, "#");
1317 if (len < valuelen) {
1318 valuelen = len;
1319 value[valuelen] = 0;
1322 status = set_option(opt, value);
1325 if (status != OPT_OK) {
1326 warn("Error on line %d, near '%.*s': %s",
1327 config->lineno, (int) optlen, opt, option_errors[status]);
1328 config->errors = TRUE;
1331 /* Always keep going if errors are encountered. */
1332 return OK;
1335 static void
1336 load_option_file(const char *path)
1338 struct config_state config = { 0, FALSE };
1339 struct io io;
1341 /* It's OK that the file doesn't exist. */
1342 if (!io_open(&io, "%s", path))
1343 return;
1345 if (io_load(&io, " \t", read_option, &config) == ERR ||
1346 config.errors == TRUE)
1347 warn("Errors while loading %s.", path);
1350 static int
1351 load_options(void)
1353 const char *home = getenv("HOME");
1354 const char *tigrc_user = getenv("TIGRC_USER");
1355 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1356 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1357 char buf[SIZEOF_STR];
1359 if (!tigrc_system)
1360 tigrc_system = SYSCONFDIR "/tigrc";
1361 load_option_file(tigrc_system);
1363 if (!tigrc_user) {
1364 if (!home || !string_format(buf, "%s/.tigrc", home))
1365 return ERR;
1366 tigrc_user = buf;
1368 load_option_file(tigrc_user);
1370 /* Add _after_ loading config files to avoid adding run requests
1371 * that conflict with keybindings. */
1372 add_builtin_run_requests();
1374 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1375 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1376 int argc = 0;
1378 if (!string_format(buf, "%s", tig_diff_opts) ||
1379 !argv_from_string(diff_opts, &argc, buf))
1380 die("TIG_DIFF_OPTS contains too many arguments");
1381 else if (!argv_copy(&opt_diff_argv, diff_opts))
1382 die("Failed to format TIG_DIFF_OPTS arguments");
1385 return OK;
1390 * The viewer
1393 struct view;
1394 struct view_ops;
1396 /* The display array of active views and the index of the current view. */
1397 static struct view *display[2];
1398 static WINDOW *display_win[2];
1399 static WINDOW *display_title[2];
1400 static unsigned int current_view;
1402 #define foreach_displayed_view(view, i) \
1403 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1405 #define displayed_views() (display[1] != NULL ? 2 : 1)
1407 /* Current head and commit ID */
1408 static char ref_blob[SIZEOF_REF] = "";
1409 static char ref_commit[SIZEOF_REF] = "HEAD";
1410 static char ref_head[SIZEOF_REF] = "HEAD";
1411 static char ref_branch[SIZEOF_REF] = "";
1413 enum view_type {
1414 VIEW_MAIN,
1415 VIEW_DIFF,
1416 VIEW_LOG,
1417 VIEW_TREE,
1418 VIEW_BLOB,
1419 VIEW_BLAME,
1420 VIEW_BRANCH,
1421 VIEW_HELP,
1422 VIEW_PAGER,
1423 VIEW_STATUS,
1424 VIEW_STAGE,
1427 struct view {
1428 enum view_type type; /* View type */
1429 const char *name; /* View name */
1430 const char *id; /* Points to either of ref_{head,commit,blob} */
1432 struct view_ops *ops; /* View operations */
1434 enum keymap keymap; /* What keymap does this view have */
1435 bool git_dir; /* Whether the view requires a git directory. */
1437 char ref[SIZEOF_REF]; /* Hovered commit reference */
1438 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1440 int height, width; /* The width and height of the main window */
1441 WINDOW *win; /* The main window */
1443 /* Navigation */
1444 unsigned long offset; /* Offset of the window top */
1445 unsigned long yoffset; /* Offset from the window side. */
1446 unsigned long lineno; /* Current line number */
1447 unsigned long p_offset; /* Previous offset of the window top */
1448 unsigned long p_yoffset;/* Previous offset from the window side */
1449 unsigned long p_lineno; /* Previous current line number */
1450 bool p_restore; /* Should the previous position be restored. */
1452 /* Searching */
1453 char grep[SIZEOF_STR]; /* Search string */
1454 regex_t *regex; /* Pre-compiled regexp */
1456 /* If non-NULL, points to the view that opened this view. If this view
1457 * is closed tig will switch back to the parent view. */
1458 struct view *parent;
1459 struct view *prev;
1461 /* Buffering */
1462 size_t lines; /* Total number of lines */
1463 struct line *line; /* Line index */
1464 unsigned int digits; /* Number of digits in the lines member. */
1466 /* Drawing */
1467 struct line *curline; /* Line currently being drawn. */
1468 enum line_type curtype; /* Attribute currently used for drawing. */
1469 unsigned long col; /* Column when drawing. */
1470 bool has_scrolled; /* View was scrolled. */
1472 /* Loading */
1473 const char **argv; /* Shell command arguments. */
1474 const char *dir; /* Directory from which to execute. */
1475 struct io io;
1476 struct io *pipe;
1477 time_t start_time;
1478 time_t update_secs;
1481 enum open_flags {
1482 OPEN_DEFAULT = 0, /* Use default view switching. */
1483 OPEN_SPLIT = 1, /* Split current view. */
1484 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1485 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1486 OPEN_PREPARED = 32, /* Open already prepared command. */
1487 OPEN_EXTRA = 64, /* Open extra data from command. */
1490 struct view_ops {
1491 /* What type of content being displayed. Used in the title bar. */
1492 const char *type;
1493 /* Open and reads in all view content. */
1494 bool (*open)(struct view *view, enum open_flags flags);
1495 /* Read one line; updates view->line. */
1496 bool (*read)(struct view *view, char *data);
1497 /* Draw one line; @lineno must be < view->height. */
1498 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1499 /* Depending on view handle a special requests. */
1500 enum request (*request)(struct view *view, enum request request, struct line *line);
1501 /* Search for regexp in a line. */
1502 bool (*grep)(struct view *view, struct line *line);
1503 /* Select line */
1504 void (*select)(struct view *view, struct line *line);
1507 static struct view_ops blame_ops;
1508 static struct view_ops blob_ops;
1509 static struct view_ops diff_ops;
1510 static struct view_ops help_ops;
1511 static struct view_ops log_ops;
1512 static struct view_ops main_ops;
1513 static struct view_ops pager_ops;
1514 static struct view_ops stage_ops;
1515 static struct view_ops status_ops;
1516 static struct view_ops tree_ops;
1517 static struct view_ops branch_ops;
1519 #define VIEW_STR(type, name, ref, ops, map, git) \
1520 { type, name, ref, ops, map, git }
1522 #define VIEW_(id, name, ops, git, ref) \
1523 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1525 static struct view views[] = {
1526 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1527 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1528 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1529 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1530 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1531 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1532 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1533 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1534 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1535 VIEW_(STATUS, "status", &status_ops, TRUE, "status"),
1536 VIEW_(STAGE, "stage", &stage_ops, TRUE, "stage"),
1539 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1541 #define foreach_view(view, i) \
1542 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1544 #define view_is_displayed(view) \
1545 (view == display[0] || view == display[1])
1547 static enum request
1548 view_request(struct view *view, enum request request)
1550 if (!view || !view->lines)
1551 return request;
1552 return view->ops->request(view, request, &view->line[view->lineno]);
1557 * View drawing.
1560 static inline void
1561 set_view_attr(struct view *view, enum line_type type)
1563 if (!view->curline->selected && view->curtype != type) {
1564 (void) wattrset(view->win, get_line_attr(type));
1565 wchgat(view->win, -1, 0, type, NULL);
1566 view->curtype = type;
1570 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1572 static bool
1573 draw_chars(struct view *view, enum line_type type, const char *string,
1574 int max_len, bool use_tilde)
1576 static char out_buffer[BUFSIZ * 2];
1577 int len = 0;
1578 int col = 0;
1579 int trimmed = FALSE;
1580 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1582 if (max_len <= 0)
1583 return VIEW_MAX_LEN(view) <= 0;
1585 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1587 set_view_attr(view, type);
1588 if (len > 0) {
1589 if (opt_iconv_out != ICONV_NONE) {
1590 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1591 size_t inlen = len + 1;
1593 char *outbuf = out_buffer;
1594 size_t outlen = sizeof(out_buffer);
1596 size_t ret;
1598 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1599 if (ret != (size_t) -1) {
1600 string = out_buffer;
1601 len = sizeof(out_buffer) - outlen;
1605 waddnstr(view->win, string, len);
1607 if (trimmed && use_tilde) {
1608 set_view_attr(view, LINE_DELIMITER);
1609 waddch(view->win, '~');
1610 col++;
1614 view->col += col;
1615 return VIEW_MAX_LEN(view) <= 0;
1618 static bool
1619 draw_space(struct view *view, enum line_type type, int max, int spaces)
1621 static char space[] = " ";
1623 spaces = MIN(max, spaces);
1625 while (spaces > 0) {
1626 int len = MIN(spaces, sizeof(space) - 1);
1628 if (draw_chars(view, type, space, len, FALSE))
1629 return TRUE;
1630 spaces -= len;
1633 return VIEW_MAX_LEN(view) <= 0;
1636 static bool
1637 draw_text(struct view *view, enum line_type type, const char *string)
1639 char text[SIZEOF_STR];
1641 do {
1642 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1644 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1645 return TRUE;
1646 string += pos;
1647 } while (*string);
1649 return VIEW_MAX_LEN(view) <= 0;
1652 static bool
1653 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1655 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1656 int max = VIEW_MAX_LEN(view);
1657 int i;
1659 if (max < size)
1660 size = max;
1662 set_view_attr(view, type);
1663 /* Using waddch() instead of waddnstr() ensures that
1664 * they'll be rendered correctly for the cursor line. */
1665 for (i = skip; i < size; i++)
1666 waddch(view->win, graphic[i]);
1668 view->col += size;
1669 if (separator) {
1670 if (size < max && skip <= size)
1671 waddch(view->win, ' ');
1672 view->col++;
1675 return VIEW_MAX_LEN(view) <= 0;
1678 static bool
1679 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1681 int max = MIN(VIEW_MAX_LEN(view), len);
1682 int col = view->col;
1684 if (!text)
1685 return draw_space(view, type, max, max);
1687 return draw_chars(view, type, text, max - 1, trim)
1688 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1691 static bool
1692 draw_date(struct view *view, struct time *time)
1694 const char *date = mkdate(time, opt_date);
1695 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1697 if (opt_date == DATE_NO)
1698 return FALSE;
1700 return draw_field(view, LINE_DATE, date, cols, FALSE);
1703 static bool
1704 draw_author(struct view *view, const char *author)
1706 bool trim = author_trim(opt_author_cols);
1707 const char *text = mkauthor(author, opt_author_cols, opt_author);
1709 if (opt_author == AUTHOR_NO)
1710 return FALSE;
1712 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1715 static bool
1716 draw_mode(struct view *view, mode_t mode)
1718 const char *str = mkmode(mode);
1720 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1723 static bool
1724 draw_lineno(struct view *view, unsigned int lineno)
1726 char number[10];
1727 int digits3 = view->digits < 3 ? 3 : view->digits;
1728 int max = MIN(VIEW_MAX_LEN(view), digits3);
1729 char *text = NULL;
1730 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1732 lineno += view->offset + 1;
1733 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1734 static char fmt[] = "%1ld";
1736 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1737 if (string_format(number, fmt, lineno))
1738 text = number;
1740 if (text)
1741 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1742 else
1743 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1744 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1747 static bool
1748 draw_refs(struct view *view, struct ref_list *refs)
1750 size_t i;
1752 if (!opt_show_refs || !refs)
1753 return FALSE;
1755 for (i = 0; i < refs->size; i++) {
1756 struct ref *ref = refs->refs[i];
1757 enum line_type type = get_line_type_from_ref(ref);
1759 if (draw_text(view, type, "[") ||
1760 draw_text(view, type, ref->name) ||
1761 draw_text(view, type, "]"))
1762 return TRUE;
1764 if (draw_text(view, LINE_DEFAULT, " "))
1765 return TRUE;
1768 return FALSE;
1771 static bool
1772 draw_view_line(struct view *view, unsigned int lineno)
1774 struct line *line;
1775 bool selected = (view->offset + lineno == view->lineno);
1777 assert(view_is_displayed(view));
1779 if (view->offset + lineno >= view->lines)
1780 return FALSE;
1782 line = &view->line[view->offset + lineno];
1784 wmove(view->win, lineno, 0);
1785 if (line->cleareol)
1786 wclrtoeol(view->win);
1787 view->col = 0;
1788 view->curline = line;
1789 view->curtype = LINE_NONE;
1790 line->selected = FALSE;
1791 line->dirty = line->cleareol = 0;
1793 if (selected) {
1794 set_view_attr(view, LINE_CURSOR);
1795 line->selected = TRUE;
1796 view->ops->select(view, line);
1799 return view->ops->draw(view, line, lineno);
1802 static void
1803 redraw_view_dirty(struct view *view)
1805 bool dirty = FALSE;
1806 int lineno;
1808 for (lineno = 0; lineno < view->height; lineno++) {
1809 if (view->offset + lineno >= view->lines)
1810 break;
1811 if (!view->line[view->offset + lineno].dirty)
1812 continue;
1813 dirty = TRUE;
1814 if (!draw_view_line(view, lineno))
1815 break;
1818 if (!dirty)
1819 return;
1820 wnoutrefresh(view->win);
1823 static void
1824 redraw_view_from(struct view *view, int lineno)
1826 assert(0 <= lineno && lineno < view->height);
1828 for (; lineno < view->height; lineno++) {
1829 if (!draw_view_line(view, lineno))
1830 break;
1833 wnoutrefresh(view->win);
1836 static void
1837 redraw_view(struct view *view)
1839 werase(view->win);
1840 redraw_view_from(view, 0);
1844 static void
1845 update_view_title(struct view *view)
1847 char buf[SIZEOF_STR];
1848 char state[SIZEOF_STR];
1849 size_t bufpos = 0, statelen = 0;
1850 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1852 assert(view_is_displayed(view));
1854 if (view->type != VIEW_STATUS && view->lines) {
1855 unsigned int view_lines = view->offset + view->height;
1856 unsigned int lines = view->lines
1857 ? MIN(view_lines, view->lines) * 100 / view->lines
1858 : 0;
1860 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1861 view->ops->type,
1862 view->lineno + 1,
1863 view->lines,
1864 lines);
1868 if (view->pipe) {
1869 time_t secs = time(NULL) - view->start_time;
1871 /* Three git seconds are a long time ... */
1872 if (secs > 2)
1873 string_format_from(state, &statelen, " loading %lds", secs);
1876 string_format_from(buf, &bufpos, "[%s]", view->name);
1877 if (*view->ref && bufpos < view->width) {
1878 size_t refsize = strlen(view->ref);
1879 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1881 if (minsize < view->width)
1882 refsize = view->width - minsize + 7;
1883 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1886 if (statelen && bufpos < view->width) {
1887 string_format_from(buf, &bufpos, "%s", state);
1890 if (view == display[current_view])
1891 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1892 else
1893 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1895 mvwaddnstr(window, 0, 0, buf, bufpos);
1896 wclrtoeol(window);
1897 wnoutrefresh(window);
1900 static int
1901 apply_step(double step, int value)
1903 if (step >= 1)
1904 return (int) step;
1905 value *= step + 0.01;
1906 return value ? value : 1;
1909 static void
1910 resize_display(void)
1912 int offset, i;
1913 struct view *base = display[0];
1914 struct view *view = display[1] ? display[1] : display[0];
1916 /* Setup window dimensions */
1918 getmaxyx(stdscr, base->height, base->width);
1920 /* Make room for the status window. */
1921 base->height -= 1;
1923 if (view != base) {
1924 /* Horizontal split. */
1925 view->width = base->width;
1926 view->height = apply_step(opt_scale_split_view, base->height);
1927 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1928 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1929 base->height -= view->height;
1931 /* Make room for the title bar. */
1932 view->height -= 1;
1935 /* Make room for the title bar. */
1936 base->height -= 1;
1938 offset = 0;
1940 foreach_displayed_view (view, i) {
1941 if (!display_win[i]) {
1942 display_win[i] = newwin(view->height, view->width, offset, 0);
1943 if (!display_win[i])
1944 die("Failed to create %s view", view->name);
1946 scrollok(display_win[i], FALSE);
1948 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1949 if (!display_title[i])
1950 die("Failed to create title window");
1952 } else {
1953 wresize(display_win[i], view->height, view->width);
1954 mvwin(display_win[i], offset, 0);
1955 mvwin(display_title[i], offset + view->height, 0);
1958 view->win = display_win[i];
1960 offset += view->height + 1;
1964 static void
1965 redraw_display(bool clear)
1967 struct view *view;
1968 int i;
1970 foreach_displayed_view (view, i) {
1971 if (clear)
1972 wclear(view->win);
1973 redraw_view(view);
1974 update_view_title(view);
1980 * Option management
1983 #define TOGGLE_MENU \
1984 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1985 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1986 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1987 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1988 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1989 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1991 static void
1992 toggle_option(enum request request)
1994 const struct {
1995 enum request request;
1996 const struct enum_map *map;
1997 size_t map_size;
1998 } data[] = {
1999 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2000 TOGGLE_MENU
2001 #undef TOGGLE_
2003 const struct menu_item menu[] = {
2004 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2005 TOGGLE_MENU
2006 #undef TOGGLE_
2007 { 0 }
2009 int i = 0;
2011 if (request == REQ_OPTIONS) {
2012 if (!prompt_menu("Toggle option", menu, &i))
2013 return;
2014 } else {
2015 while (i < ARRAY_SIZE(data) && data[i].request != request)
2016 i++;
2017 if (i >= ARRAY_SIZE(data))
2018 die("Invalid request (%d)", request);
2021 if (data[i].map != NULL) {
2022 unsigned int *opt = menu[i].data;
2024 *opt = (*opt + 1) % data[i].map_size;
2025 redraw_display(FALSE);
2026 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2028 } else {
2029 bool *option = menu[i].data;
2031 *option = !*option;
2032 redraw_display(FALSE);
2033 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2037 static void
2038 maximize_view(struct view *view, bool redraw)
2040 memset(display, 0, sizeof(display));
2041 current_view = 0;
2042 display[current_view] = view;
2043 resize_display();
2044 if (redraw) {
2045 redraw_display(FALSE);
2046 report("");
2052 * Navigation
2055 static bool
2056 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2058 if (lineno >= view->lines)
2059 lineno = view->lines > 0 ? view->lines - 1 : 0;
2061 if (offset > lineno || offset + view->height <= lineno) {
2062 unsigned long half = view->height / 2;
2064 if (lineno > half)
2065 offset = lineno - half;
2066 else
2067 offset = 0;
2070 if (offset != view->offset || lineno != view->lineno) {
2071 view->offset = offset;
2072 view->lineno = lineno;
2073 return TRUE;
2076 return FALSE;
2079 /* Scrolling backend */
2080 static void
2081 do_scroll_view(struct view *view, int lines)
2083 bool redraw_current_line = FALSE;
2085 /* The rendering expects the new offset. */
2086 view->offset += lines;
2088 assert(0 <= view->offset && view->offset < view->lines);
2089 assert(lines);
2091 /* Move current line into the view. */
2092 if (view->lineno < view->offset) {
2093 view->lineno = view->offset;
2094 redraw_current_line = TRUE;
2095 } else if (view->lineno >= view->offset + view->height) {
2096 view->lineno = view->offset + view->height - 1;
2097 redraw_current_line = TRUE;
2100 assert(view->offset <= view->lineno && view->lineno < view->lines);
2102 /* Redraw the whole screen if scrolling is pointless. */
2103 if (view->height < ABS(lines)) {
2104 redraw_view(view);
2106 } else {
2107 int line = lines > 0 ? view->height - lines : 0;
2108 int end = line + ABS(lines);
2110 scrollok(view->win, TRUE);
2111 wscrl(view->win, lines);
2112 scrollok(view->win, FALSE);
2114 while (line < end && draw_view_line(view, line))
2115 line++;
2117 if (redraw_current_line)
2118 draw_view_line(view, view->lineno - view->offset);
2119 wnoutrefresh(view->win);
2122 view->has_scrolled = TRUE;
2123 report("");
2126 /* Scroll frontend */
2127 static void
2128 scroll_view(struct view *view, enum request request)
2130 int lines = 1;
2132 assert(view_is_displayed(view));
2134 switch (request) {
2135 case REQ_SCROLL_FIRST_COL:
2136 view->yoffset = 0;
2137 redraw_view_from(view, 0);
2138 report("");
2139 return;
2140 case REQ_SCROLL_LEFT:
2141 if (view->yoffset == 0) {
2142 report("Cannot scroll beyond the first column");
2143 return;
2145 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2146 view->yoffset = 0;
2147 else
2148 view->yoffset -= apply_step(opt_hscroll, view->width);
2149 redraw_view_from(view, 0);
2150 report("");
2151 return;
2152 case REQ_SCROLL_RIGHT:
2153 view->yoffset += apply_step(opt_hscroll, view->width);
2154 redraw_view(view);
2155 report("");
2156 return;
2157 case REQ_SCROLL_PAGE_DOWN:
2158 lines = view->height;
2159 case REQ_SCROLL_LINE_DOWN:
2160 if (view->offset + lines > view->lines)
2161 lines = view->lines - view->offset;
2163 if (lines == 0 || view->offset + view->height >= view->lines) {
2164 report("Cannot scroll beyond the last line");
2165 return;
2167 break;
2169 case REQ_SCROLL_PAGE_UP:
2170 lines = view->height;
2171 case REQ_SCROLL_LINE_UP:
2172 if (lines > view->offset)
2173 lines = view->offset;
2175 if (lines == 0) {
2176 report("Cannot scroll beyond the first line");
2177 return;
2180 lines = -lines;
2181 break;
2183 default:
2184 die("request %d not handled in switch", request);
2187 do_scroll_view(view, lines);
2190 /* Cursor moving */
2191 static void
2192 move_view(struct view *view, enum request request)
2194 int scroll_steps = 0;
2195 int steps;
2197 switch (request) {
2198 case REQ_MOVE_FIRST_LINE:
2199 steps = -view->lineno;
2200 break;
2202 case REQ_MOVE_LAST_LINE:
2203 steps = view->lines - view->lineno - 1;
2204 break;
2206 case REQ_MOVE_PAGE_UP:
2207 steps = view->height > view->lineno
2208 ? -view->lineno : -view->height;
2209 break;
2211 case REQ_MOVE_PAGE_DOWN:
2212 steps = view->lineno + view->height >= view->lines
2213 ? view->lines - view->lineno - 1 : view->height;
2214 break;
2216 case REQ_MOVE_UP:
2217 steps = -1;
2218 break;
2220 case REQ_MOVE_DOWN:
2221 steps = 1;
2222 break;
2224 default:
2225 die("request %d not handled in switch", request);
2228 if (steps <= 0 && view->lineno == 0) {
2229 report("Cannot move beyond the first line");
2230 return;
2232 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2233 report("Cannot move beyond the last line");
2234 return;
2237 /* Move the current line */
2238 view->lineno += steps;
2239 assert(0 <= view->lineno && view->lineno < view->lines);
2241 /* Check whether the view needs to be scrolled */
2242 if (view->lineno < view->offset ||
2243 view->lineno >= view->offset + view->height) {
2244 scroll_steps = steps;
2245 if (steps < 0 && -steps > view->offset) {
2246 scroll_steps = -view->offset;
2248 } else if (steps > 0) {
2249 if (view->lineno == view->lines - 1 &&
2250 view->lines > view->height) {
2251 scroll_steps = view->lines - view->offset - 1;
2252 if (scroll_steps >= view->height)
2253 scroll_steps -= view->height - 1;
2258 if (!view_is_displayed(view)) {
2259 view->offset += scroll_steps;
2260 assert(0 <= view->offset && view->offset < view->lines);
2261 view->ops->select(view, &view->line[view->lineno]);
2262 return;
2265 /* Repaint the old "current" line if we be scrolling */
2266 if (ABS(steps) < view->height)
2267 draw_view_line(view, view->lineno - steps - view->offset);
2269 if (scroll_steps) {
2270 do_scroll_view(view, scroll_steps);
2271 return;
2274 /* Draw the current line */
2275 draw_view_line(view, view->lineno - view->offset);
2277 wnoutrefresh(view->win);
2278 report("");
2283 * Searching
2286 static void search_view(struct view *view, enum request request);
2288 static bool
2289 grep_text(struct view *view, const char *text[])
2291 regmatch_t pmatch;
2292 size_t i;
2294 for (i = 0; text[i]; i++)
2295 if (*text[i] &&
2296 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2297 return TRUE;
2298 return FALSE;
2301 static void
2302 select_view_line(struct view *view, unsigned long lineno)
2304 unsigned long old_lineno = view->lineno;
2305 unsigned long old_offset = view->offset;
2307 if (goto_view_line(view, view->offset, lineno)) {
2308 if (view_is_displayed(view)) {
2309 if (old_offset != view->offset) {
2310 redraw_view(view);
2311 } else {
2312 draw_view_line(view, old_lineno - view->offset);
2313 draw_view_line(view, view->lineno - view->offset);
2314 wnoutrefresh(view->win);
2316 } else {
2317 view->ops->select(view, &view->line[view->lineno]);
2322 static void
2323 find_next(struct view *view, enum request request)
2325 unsigned long lineno = view->lineno;
2326 int direction;
2328 if (!*view->grep) {
2329 if (!*opt_search)
2330 report("No previous search");
2331 else
2332 search_view(view, request);
2333 return;
2336 switch (request) {
2337 case REQ_SEARCH:
2338 case REQ_FIND_NEXT:
2339 direction = 1;
2340 break;
2342 case REQ_SEARCH_BACK:
2343 case REQ_FIND_PREV:
2344 direction = -1;
2345 break;
2347 default:
2348 return;
2351 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2352 lineno += direction;
2354 /* Note, lineno is unsigned long so will wrap around in which case it
2355 * will become bigger than view->lines. */
2356 for (; lineno < view->lines; lineno += direction) {
2357 if (view->ops->grep(view, &view->line[lineno])) {
2358 select_view_line(view, lineno);
2359 report("Line %ld matches '%s'", lineno + 1, view->grep);
2360 return;
2364 report("No match found for '%s'", view->grep);
2367 static void
2368 search_view(struct view *view, enum request request)
2370 int regex_err;
2372 if (view->regex) {
2373 regfree(view->regex);
2374 *view->grep = 0;
2375 } else {
2376 view->regex = calloc(1, sizeof(*view->regex));
2377 if (!view->regex)
2378 return;
2381 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2382 if (regex_err != 0) {
2383 char buf[SIZEOF_STR] = "unknown error";
2385 regerror(regex_err, view->regex, buf, sizeof(buf));
2386 report("Search failed: %s", buf);
2387 return;
2390 string_copy(view->grep, opt_search);
2392 find_next(view, request);
2396 * Incremental updating
2399 static void
2400 reset_view(struct view *view)
2402 int i;
2404 for (i = 0; i < view->lines; i++)
2405 free(view->line[i].data);
2406 free(view->line);
2408 view->p_offset = view->offset;
2409 view->p_yoffset = view->yoffset;
2410 view->p_lineno = view->lineno;
2412 view->line = NULL;
2413 view->offset = 0;
2414 view->yoffset = 0;
2415 view->lines = 0;
2416 view->lineno = 0;
2417 view->vid[0] = 0;
2418 view->update_secs = 0;
2421 static const char *
2422 format_arg(const char *name)
2424 static struct {
2425 const char *name;
2426 size_t namelen;
2427 const char *value;
2428 const char *value_if_empty;
2429 } vars[] = {
2430 #define FORMAT_VAR(name, value, value_if_empty) \
2431 { name, STRING_SIZE(name), value, value_if_empty }
2432 FORMAT_VAR("%(directory)", opt_path, "."),
2433 FORMAT_VAR("%(file)", opt_file, ""),
2434 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2435 FORMAT_VAR("%(head)", ref_head, ""),
2436 FORMAT_VAR("%(commit)", ref_commit, ""),
2437 FORMAT_VAR("%(blob)", ref_blob, ""),
2438 FORMAT_VAR("%(branch)", ref_branch, ""),
2440 int i;
2442 for (i = 0; i < ARRAY_SIZE(vars); i++)
2443 if (!strncmp(name, vars[i].name, vars[i].namelen))
2444 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2446 report("Unknown replacement: `%s`", name);
2447 return NULL;
2450 static bool
2451 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2453 char buf[SIZEOF_STR];
2454 int argc;
2456 argv_free(*dst_argv);
2458 for (argc = 0; src_argv[argc]; argc++) {
2459 const char *arg = src_argv[argc];
2460 size_t bufpos = 0;
2462 if (!strcmp(arg, "%(fileargs)")) {
2463 if (!argv_append_array(dst_argv, opt_file_argv))
2464 break;
2465 continue;
2467 } else if (!strcmp(arg, "%(diffargs)")) {
2468 if (!argv_append_array(dst_argv, opt_diff_argv))
2469 break;
2470 continue;
2472 } else if (!strcmp(arg, "%(blameargs)")) {
2473 if (!argv_append_array(dst_argv, opt_blame_argv))
2474 break;
2475 continue;
2477 } else if (!strcmp(arg, "%(revargs)") ||
2478 (first && !strcmp(arg, "%(commit)"))) {
2479 if (!argv_append_array(dst_argv, opt_rev_argv))
2480 break;
2481 continue;
2484 while (arg) {
2485 char *next = strstr(arg, "%(");
2486 int len = next - arg;
2487 const char *value;
2489 if (!next) {
2490 len = strlen(arg);
2491 value = "";
2493 } else {
2494 value = format_arg(next);
2496 if (!value) {
2497 return FALSE;
2501 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2502 return FALSE;
2504 arg = next ? strchr(next, ')') + 1 : NULL;
2507 if (!argv_append(dst_argv, buf))
2508 break;
2511 return src_argv[argc] == NULL;
2514 static bool
2515 restore_view_position(struct view *view)
2517 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2518 return FALSE;
2520 /* Changing the view position cancels the restoring. */
2521 /* FIXME: Changing back to the first line is not detected. */
2522 if (view->offset != 0 || view->lineno != 0) {
2523 view->p_restore = FALSE;
2524 return FALSE;
2527 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2528 view_is_displayed(view))
2529 werase(view->win);
2531 view->yoffset = view->p_yoffset;
2532 view->p_restore = FALSE;
2534 return TRUE;
2537 static void
2538 end_update(struct view *view, bool force)
2540 if (!view->pipe)
2541 return;
2542 while (!view->ops->read(view, NULL))
2543 if (!force)
2544 return;
2545 if (force)
2546 io_kill(view->pipe);
2547 io_done(view->pipe);
2548 view->pipe = NULL;
2551 static void
2552 setup_update(struct view *view, const char *vid)
2554 reset_view(view);
2555 string_copy_rev(view->vid, vid);
2556 view->pipe = &view->io;
2557 view->start_time = time(NULL);
2560 static bool
2561 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2563 bool extra = !!(flags & (OPEN_EXTRA));
2564 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2565 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2567 if (!reload && !strcmp(view->vid, view->id))
2568 return TRUE;
2570 if (view->pipe) {
2571 if (extra)
2572 io_done(view->pipe);
2573 else
2574 end_update(view, TRUE);
2577 if (!refresh && argv) {
2578 view->dir = dir;
2579 if (!format_argv(&view->argv, argv, !view->prev))
2580 return FALSE;
2582 /* Put the current ref_* value to the view title ref
2583 * member. This is needed by the blob view. Most other
2584 * views sets it automatically after loading because the
2585 * first line is a commit line. */
2586 string_copy_rev(view->ref, view->id);
2589 if (view->argv && view->argv[0] &&
2590 !io_run(&view->io, IO_RD, view->dir, view->argv))
2591 return FALSE;
2593 if (!extra)
2594 setup_update(view, view->id);
2596 return TRUE;
2599 static bool
2600 update_view(struct view *view)
2602 char out_buffer[BUFSIZ * 2];
2603 char *line;
2604 /* Clear the view and redraw everything since the tree sorting
2605 * might have rearranged things. */
2606 bool redraw = view->lines == 0;
2607 bool can_read = TRUE;
2609 if (!view->pipe)
2610 return TRUE;
2612 if (!io_can_read(view->pipe, FALSE)) {
2613 if (view->lines == 0 && view_is_displayed(view)) {
2614 time_t secs = time(NULL) - view->start_time;
2616 if (secs > 1 && secs > view->update_secs) {
2617 if (view->update_secs == 0)
2618 redraw_view(view);
2619 update_view_title(view);
2620 view->update_secs = secs;
2623 return TRUE;
2626 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2627 if (opt_iconv_in != ICONV_NONE) {
2628 ICONV_CONST char *inbuf = line;
2629 size_t inlen = strlen(line) + 1;
2631 char *outbuf = out_buffer;
2632 size_t outlen = sizeof(out_buffer);
2634 size_t ret;
2636 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2637 if (ret != (size_t) -1)
2638 line = out_buffer;
2641 if (!view->ops->read(view, line)) {
2642 report("Allocation failure");
2643 end_update(view, TRUE);
2644 return FALSE;
2649 unsigned long lines = view->lines;
2650 int digits;
2652 for (digits = 0; lines; digits++)
2653 lines /= 10;
2655 /* Keep the displayed view in sync with line number scaling. */
2656 if (digits != view->digits) {
2657 view->digits = digits;
2658 if (opt_line_number || view->type == VIEW_BLAME)
2659 redraw = TRUE;
2663 if (io_error(view->pipe)) {
2664 report("Failed to read: %s", io_strerror(view->pipe));
2665 end_update(view, TRUE);
2667 } else if (io_eof(view->pipe)) {
2668 if (view_is_displayed(view))
2669 report("");
2670 end_update(view, FALSE);
2673 if (restore_view_position(view))
2674 redraw = TRUE;
2676 if (!view_is_displayed(view))
2677 return TRUE;
2679 if (redraw)
2680 redraw_view_from(view, 0);
2681 else
2682 redraw_view_dirty(view);
2684 /* Update the title _after_ the redraw so that if the redraw picks up a
2685 * commit reference in view->ref it'll be available here. */
2686 update_view_title(view);
2687 return TRUE;
2690 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2692 static struct line *
2693 add_line_data(struct view *view, void *data, enum line_type type)
2695 struct line *line;
2697 if (!realloc_lines(&view->line, view->lines, 1))
2698 return NULL;
2700 line = &view->line[view->lines++];
2701 memset(line, 0, sizeof(*line));
2702 line->type = type;
2703 line->data = data;
2704 line->dirty = 1;
2706 return line;
2709 static struct line *
2710 add_line_text(struct view *view, const char *text, enum line_type type)
2712 char *data = text ? strdup(text) : NULL;
2714 return data ? add_line_data(view, data, type) : NULL;
2717 static struct line *
2718 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2720 char buf[SIZEOF_STR];
2721 va_list args;
2723 va_start(args, fmt);
2724 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2725 buf[0] = 0;
2726 va_end(args);
2728 return buf[0] ? add_line_text(view, buf, type) : NULL;
2732 * View opening
2735 static void
2736 load_view(struct view *view, enum open_flags flags)
2738 if (view->pipe)
2739 end_update(view, TRUE);
2740 if (!view->ops->open(view, flags)) {
2741 report("Failed to load %s view", view->name);
2742 return;
2744 restore_view_position(view);
2746 if (view->pipe && view->lines == 0) {
2747 /* Clear the old view and let the incremental updating refill
2748 * the screen. */
2749 werase(view->win);
2750 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2751 report("");
2752 } else if (view_is_displayed(view)) {
2753 redraw_view(view);
2754 report("");
2758 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2759 #define reload_view(view) load_view(view, OPEN_RELOAD)
2761 static void
2762 split_view(struct view *prev, struct view *view)
2764 display[1] = view;
2765 current_view = 1;
2766 view->parent = prev;
2767 resize_display();
2769 if (prev->lineno - prev->offset >= prev->height) {
2770 /* Take the title line into account. */
2771 int lines = prev->lineno - prev->offset - prev->height + 1;
2773 /* Scroll the view that was split if the current line is
2774 * outside the new limited view. */
2775 do_scroll_view(prev, lines);
2778 if (view != prev && view_is_displayed(prev)) {
2779 /* "Blur" the previous view. */
2780 update_view_title(prev);
2784 static void
2785 open_view(struct view *prev, enum request request, enum open_flags flags)
2787 bool split = !!(flags & OPEN_SPLIT);
2788 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2789 struct view *view = VIEW(request);
2790 int nviews = displayed_views();
2792 assert(flags ^ OPEN_REFRESH);
2794 if (view == prev && nviews == 1 && !reload) {
2795 report("Already in %s view", view->name);
2796 return;
2799 if (view->git_dir && !opt_git_dir[0]) {
2800 report("The %s view is disabled in pager view", view->name);
2801 return;
2804 if (split) {
2805 split_view(prev, view);
2806 } else {
2807 maximize_view(view, FALSE);
2810 /* No prev signals that this is the first loaded view. */
2811 if (prev && view != prev) {
2812 view->prev = prev;
2815 load_view(view, flags);
2818 static void
2819 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2821 enum request request = view - views + REQ_OFFSET + 1;
2823 if (view->pipe)
2824 end_update(view, TRUE);
2825 view->dir = dir;
2827 if (!argv_copy(&view->argv, argv)) {
2828 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2829 } else {
2830 open_view(prev, request, flags | OPEN_PREPARED);
2834 static void
2835 open_external_viewer(const char *argv[], const char *dir)
2837 def_prog_mode(); /* save current tty modes */
2838 endwin(); /* restore original tty modes */
2839 io_run_fg(argv, dir);
2840 fprintf(stderr, "Press Enter to continue");
2841 getc(opt_tty);
2842 reset_prog_mode();
2843 redraw_display(TRUE);
2846 static void
2847 open_mergetool(const char *file)
2849 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2851 open_external_viewer(mergetool_argv, opt_cdup);
2854 static void
2855 open_editor(const char *file)
2857 const char *editor_argv[] = { "vi", file, NULL };
2858 const char *editor;
2860 editor = getenv("GIT_EDITOR");
2861 if (!editor && *opt_editor)
2862 editor = opt_editor;
2863 if (!editor)
2864 editor = getenv("VISUAL");
2865 if (!editor)
2866 editor = getenv("EDITOR");
2867 if (!editor)
2868 editor = "vi";
2870 editor_argv[0] = editor;
2871 open_external_viewer(editor_argv, opt_cdup);
2874 static void
2875 open_run_request(enum request request)
2877 struct run_request *req = get_run_request(request);
2878 const char **argv = NULL;
2880 if (!req) {
2881 report("Unknown run request");
2882 return;
2885 if (format_argv(&argv, req->argv, FALSE))
2886 open_external_viewer(argv, NULL);
2887 if (argv)
2888 argv_free(argv);
2889 free(argv);
2893 * User request switch noodle
2896 static int
2897 view_driver(struct view *view, enum request request)
2899 int i;
2901 if (request == REQ_NONE)
2902 return TRUE;
2904 if (request > REQ_NONE) {
2905 open_run_request(request);
2906 view_request(view, REQ_REFRESH);
2907 return TRUE;
2910 request = view_request(view, request);
2911 if (request == REQ_NONE)
2912 return TRUE;
2914 switch (request) {
2915 case REQ_MOVE_UP:
2916 case REQ_MOVE_DOWN:
2917 case REQ_MOVE_PAGE_UP:
2918 case REQ_MOVE_PAGE_DOWN:
2919 case REQ_MOVE_FIRST_LINE:
2920 case REQ_MOVE_LAST_LINE:
2921 move_view(view, request);
2922 break;
2924 case REQ_SCROLL_FIRST_COL:
2925 case REQ_SCROLL_LEFT:
2926 case REQ_SCROLL_RIGHT:
2927 case REQ_SCROLL_LINE_DOWN:
2928 case REQ_SCROLL_LINE_UP:
2929 case REQ_SCROLL_PAGE_DOWN:
2930 case REQ_SCROLL_PAGE_UP:
2931 scroll_view(view, request);
2932 break;
2934 case REQ_VIEW_BLAME:
2935 if (!opt_file[0]) {
2936 report("No file chosen, press %s to open tree view",
2937 get_key(view->keymap, REQ_VIEW_TREE));
2938 break;
2940 open_view(view, request, OPEN_DEFAULT);
2941 break;
2943 case REQ_VIEW_BLOB:
2944 if (!ref_blob[0]) {
2945 report("No file chosen, press %s to open tree view",
2946 get_key(view->keymap, REQ_VIEW_TREE));
2947 break;
2949 open_view(view, request, OPEN_DEFAULT);
2950 break;
2952 case REQ_VIEW_PAGER:
2953 if (view == NULL) {
2954 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2955 die("Failed to open stdin");
2956 open_view(view, request, OPEN_PREPARED);
2957 break;
2960 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2961 report("No pager content, press %s to run command from prompt",
2962 get_key(view->keymap, REQ_PROMPT));
2963 break;
2965 open_view(view, request, OPEN_DEFAULT);
2966 break;
2968 case REQ_VIEW_STAGE:
2969 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2970 report("No stage content, press %s to open the status view and choose file",
2971 get_key(view->keymap, REQ_VIEW_STATUS));
2972 break;
2974 open_view(view, request, OPEN_DEFAULT);
2975 break;
2977 case REQ_VIEW_STATUS:
2978 if (opt_is_inside_work_tree == FALSE) {
2979 report("The status view requires a working tree");
2980 break;
2982 open_view(view, request, OPEN_DEFAULT);
2983 break;
2985 case REQ_VIEW_MAIN:
2986 case REQ_VIEW_DIFF:
2987 case REQ_VIEW_LOG:
2988 case REQ_VIEW_TREE:
2989 case REQ_VIEW_HELP:
2990 case REQ_VIEW_BRANCH:
2991 open_view(view, request, OPEN_DEFAULT);
2992 break;
2994 case REQ_NEXT:
2995 case REQ_PREVIOUS:
2996 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2998 if (view->parent) {
2999 int line;
3001 view = view->parent;
3002 line = view->lineno;
3003 move_view(view, request);
3004 if (view_is_displayed(view))
3005 update_view_title(view);
3006 if (line != view->lineno)
3007 view_request(view, REQ_ENTER);
3008 } else {
3009 move_view(view, request);
3011 break;
3013 case REQ_VIEW_NEXT:
3015 int nviews = displayed_views();
3016 int next_view = (current_view + 1) % nviews;
3018 if (next_view == current_view) {
3019 report("Only one view is displayed");
3020 break;
3023 current_view = next_view;
3024 /* Blur out the title of the previous view. */
3025 update_view_title(view);
3026 report("");
3027 break;
3029 case REQ_REFRESH:
3030 report("Refreshing is not yet supported for the %s view", view->name);
3031 break;
3033 case REQ_MAXIMIZE:
3034 if (displayed_views() == 2)
3035 maximize_view(view, TRUE);
3036 break;
3038 case REQ_OPTIONS:
3039 case REQ_TOGGLE_LINENO:
3040 case REQ_TOGGLE_DATE:
3041 case REQ_TOGGLE_AUTHOR:
3042 case REQ_TOGGLE_GRAPHIC:
3043 case REQ_TOGGLE_REV_GRAPH:
3044 case REQ_TOGGLE_REFS:
3045 toggle_option(request);
3046 break;
3048 case REQ_TOGGLE_SORT_FIELD:
3049 case REQ_TOGGLE_SORT_ORDER:
3050 report("Sorting is not yet supported for the %s view", view->name);
3051 break;
3053 case REQ_DIFF_CONTEXT_UP:
3054 case REQ_DIFF_CONTEXT_DOWN:
3055 report("Changing the diff context is not yet supported for the %s view", view->name);
3056 break;
3058 case REQ_SEARCH:
3059 case REQ_SEARCH_BACK:
3060 search_view(view, request);
3061 break;
3063 case REQ_FIND_NEXT:
3064 case REQ_FIND_PREV:
3065 find_next(view, request);
3066 break;
3068 case REQ_STOP_LOADING:
3069 foreach_view(view, i) {
3070 if (view->pipe)
3071 report("Stopped loading the %s view", view->name),
3072 end_update(view, TRUE);
3074 break;
3076 case REQ_SHOW_VERSION:
3077 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3078 return TRUE;
3080 case REQ_SCREEN_REDRAW:
3081 redraw_display(TRUE);
3082 break;
3084 case REQ_EDIT:
3085 report("Nothing to edit");
3086 break;
3088 case REQ_ENTER:
3089 report("Nothing to enter");
3090 break;
3092 case REQ_VIEW_CLOSE:
3093 /* XXX: Mark closed views by letting view->prev point to the
3094 * view itself. Parents to closed view should never be
3095 * followed. */
3096 if (view->prev && view->prev != view) {
3097 maximize_view(view->prev, TRUE);
3098 view->prev = view;
3099 break;
3101 /* Fall-through */
3102 case REQ_QUIT:
3103 return FALSE;
3105 default:
3106 report("Unknown key, press %s for help",
3107 get_key(view->keymap, REQ_VIEW_HELP));
3108 return TRUE;
3111 return TRUE;
3116 * View backend utilities
3119 enum sort_field {
3120 ORDERBY_NAME,
3121 ORDERBY_DATE,
3122 ORDERBY_AUTHOR,
3125 struct sort_state {
3126 const enum sort_field *fields;
3127 size_t size, current;
3128 bool reverse;
3131 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3132 #define get_sort_field(state) ((state).fields[(state).current])
3133 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3135 static void
3136 sort_view(struct view *view, enum request request, struct sort_state *state,
3137 int (*compare)(const void *, const void *))
3139 switch (request) {
3140 case REQ_TOGGLE_SORT_FIELD:
3141 state->current = (state->current + 1) % state->size;
3142 break;
3144 case REQ_TOGGLE_SORT_ORDER:
3145 state->reverse = !state->reverse;
3146 break;
3147 default:
3148 die("Not a sort request");
3151 qsort(view->line, view->lines, sizeof(*view->line), compare);
3152 redraw_view(view);
3155 static bool
3156 update_diff_context(enum request request)
3158 int diff_context = opt_diff_context;
3160 switch (request) {
3161 case REQ_DIFF_CONTEXT_UP:
3162 opt_diff_context += 1;
3163 update_diff_context_arg(opt_diff_context);
3164 break;
3166 case REQ_DIFF_CONTEXT_DOWN:
3167 if (opt_diff_context == 0) {
3168 report("Diff context cannot be less than zero");
3169 break;
3171 opt_diff_context -= 1;
3172 update_diff_context_arg(opt_diff_context);
3173 break;
3175 default:
3176 die("Not a diff context request");
3179 return diff_context != opt_diff_context;
3182 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3184 /* Small author cache to reduce memory consumption. It uses binary
3185 * search to lookup or find place to position new entries. No entries
3186 * are ever freed. */
3187 static const char *
3188 get_author(const char *name)
3190 static const char **authors;
3191 static size_t authors_size;
3192 int from = 0, to = authors_size - 1;
3194 while (from <= to) {
3195 size_t pos = (to + from) / 2;
3196 int cmp = strcmp(name, authors[pos]);
3198 if (!cmp)
3199 return authors[pos];
3201 if (cmp < 0)
3202 to = pos - 1;
3203 else
3204 from = pos + 1;
3207 if (!realloc_authors(&authors, authors_size, 1))
3208 return NULL;
3209 name = strdup(name);
3210 if (!name)
3211 return NULL;
3213 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3214 authors[from] = name;
3215 authors_size++;
3217 return name;
3220 static void
3221 parse_timesec(struct time *time, const char *sec)
3223 time->sec = (time_t) atol(sec);
3226 static void
3227 parse_timezone(struct time *time, const char *zone)
3229 long tz;
3231 tz = ('0' - zone[1]) * 60 * 60 * 10;
3232 tz += ('0' - zone[2]) * 60 * 60;
3233 tz += ('0' - zone[3]) * 60 * 10;
3234 tz += ('0' - zone[4]) * 60;
3236 if (zone[0] == '-')
3237 tz = -tz;
3239 time->tz = tz;
3240 time->sec -= tz;
3243 /* Parse author lines where the name may be empty:
3244 * author <email@address.tld> 1138474660 +0100
3246 static void
3247 parse_author_line(char *ident, const char **author, struct time *time)
3249 char *nameend = strchr(ident, '<');
3250 char *emailend = strchr(ident, '>');
3252 if (nameend && emailend)
3253 *nameend = *emailend = 0;
3254 ident = chomp_string(ident);
3255 if (!*ident) {
3256 if (nameend)
3257 ident = chomp_string(nameend + 1);
3258 if (!*ident)
3259 ident = "Unknown";
3262 *author = get_author(ident);
3264 /* Parse epoch and timezone */
3265 if (emailend && emailend[1] == ' ') {
3266 char *secs = emailend + 2;
3267 char *zone = strchr(secs, ' ');
3269 parse_timesec(time, secs);
3271 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3272 parse_timezone(time, zone + 1);
3276 static struct line *
3277 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3279 for (; view->line < line; line--)
3280 if (line->type == type)
3281 return line;
3283 return NULL;
3287 * Blame
3290 struct blame_commit {
3291 char id[SIZEOF_REV]; /* SHA1 ID. */
3292 char title[128]; /* First line of the commit message. */
3293 const char *author; /* Author of the commit. */
3294 struct time time; /* Date from the author ident. */
3295 char filename[128]; /* Name of file. */
3296 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3297 char parent_filename[128]; /* Parent/previous name of file. */
3300 struct blame_header {
3301 char id[SIZEOF_REV]; /* SHA1 ID. */
3302 size_t orig_lineno;
3303 size_t lineno;
3304 size_t group;
3307 static bool
3308 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3310 const char *pos = *posref;
3312 *posref = NULL;
3313 pos = strchr(pos + 1, ' ');
3314 if (!pos || !isdigit(pos[1]))
3315 return FALSE;
3316 *number = atoi(pos + 1);
3317 if (*number < min || *number > max)
3318 return FALSE;
3320 *posref = pos;
3321 return TRUE;
3324 static bool
3325 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3327 const char *pos = text + SIZEOF_REV - 2;
3329 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3330 return FALSE;
3332 string_ncopy(header->id, text, SIZEOF_REV);
3334 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3335 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3336 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3337 return FALSE;
3339 return TRUE;
3342 static bool
3343 match_blame_header(const char *name, char **line)
3345 size_t namelen = strlen(name);
3346 bool matched = !strncmp(name, *line, namelen);
3348 if (matched)
3349 *line += namelen;
3351 return matched;
3354 static bool
3355 parse_blame_info(struct blame_commit *commit, char *line)
3357 if (match_blame_header("author ", &line)) {
3358 commit->author = get_author(line);
3360 } else if (match_blame_header("author-time ", &line)) {
3361 parse_timesec(&commit->time, line);
3363 } else if (match_blame_header("author-tz ", &line)) {
3364 parse_timezone(&commit->time, line);
3366 } else if (match_blame_header("summary ", &line)) {
3367 string_ncopy(commit->title, line, strlen(line));
3369 } else if (match_blame_header("previous ", &line)) {
3370 if (strlen(line) <= SIZEOF_REV)
3371 return FALSE;
3372 string_copy_rev(commit->parent_id, line);
3373 line += SIZEOF_REV;
3374 string_ncopy(commit->parent_filename, line, strlen(line));
3376 } else if (match_blame_header("filename ", &line)) {
3377 string_ncopy(commit->filename, line, strlen(line));
3378 return TRUE;
3381 return FALSE;
3385 * Pager backend
3388 static bool
3389 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3391 if (opt_line_number && draw_lineno(view, lineno))
3392 return TRUE;
3394 draw_text(view, line->type, line->data);
3395 return TRUE;
3398 static bool
3399 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3401 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3402 char ref[SIZEOF_STR];
3404 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3405 return TRUE;
3407 /* This is the only fatal call, since it can "corrupt" the buffer. */
3408 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3409 return FALSE;
3411 return TRUE;
3414 static void
3415 add_pager_refs(struct view *view, struct line *line)
3417 char buf[SIZEOF_STR];
3418 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3419 struct ref_list *list;
3420 size_t bufpos = 0, i;
3421 const char *sep = "Refs: ";
3422 bool is_tag = FALSE;
3424 assert(line->type == LINE_COMMIT);
3426 list = get_ref_list(commit_id);
3427 if (!list) {
3428 if (view->type == VIEW_DIFF)
3429 goto try_add_describe_ref;
3430 return;
3433 for (i = 0; i < list->size; i++) {
3434 struct ref *ref = list->refs[i];
3435 const char *fmt = ref->tag ? "%s[%s]" :
3436 ref->remote ? "%s<%s>" : "%s%s";
3438 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3439 return;
3440 sep = ", ";
3441 if (ref->tag)
3442 is_tag = TRUE;
3445 if (!is_tag && view->type == VIEW_DIFF) {
3446 try_add_describe_ref:
3447 /* Add <tag>-g<commit_id> "fake" reference. */
3448 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3449 return;
3452 if (bufpos == 0)
3453 return;
3455 add_line_text(view, buf, LINE_PP_REFS);
3458 static bool
3459 pager_read(struct view *view, char *data)
3461 struct line *line;
3463 if (!data)
3464 return TRUE;
3466 line = add_line_text(view, data, get_line_type(data));
3467 if (!line)
3468 return FALSE;
3470 if (line->type == LINE_COMMIT &&
3471 (view->type == VIEW_DIFF ||
3472 view->type == VIEW_LOG))
3473 add_pager_refs(view, line);
3475 return TRUE;
3478 static enum request
3479 pager_request(struct view *view, enum request request, struct line *line)
3481 int split = 0;
3483 if (request != REQ_ENTER)
3484 return request;
3486 if (line->type == LINE_COMMIT &&
3487 (view->type == VIEW_LOG ||
3488 view->type == VIEW_PAGER)) {
3489 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3490 split = 1;
3493 /* Always scroll the view even if it was split. That way
3494 * you can use Enter to scroll through the log view and
3495 * split open each commit diff. */
3496 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3498 /* FIXME: A minor workaround. Scrolling the view will call report("")
3499 * but if we are scrolling a non-current view this won't properly
3500 * update the view title. */
3501 if (split)
3502 update_view_title(view);
3504 return REQ_NONE;
3507 static bool
3508 pager_grep(struct view *view, struct line *line)
3510 const char *text[] = { line->data, NULL };
3512 return grep_text(view, text);
3515 static void
3516 pager_select(struct view *view, struct line *line)
3518 if (line->type == LINE_COMMIT) {
3519 char *text = (char *)line->data + STRING_SIZE("commit ");
3521 if (view->type != VIEW_PAGER)
3522 string_copy_rev(view->ref, text);
3523 string_copy_rev(ref_commit, text);
3527 static bool
3528 pager_open(struct view *view, enum open_flags flags)
3530 return begin_update(view, NULL, NULL, flags);
3533 static struct view_ops pager_ops = {
3534 "line",
3535 pager_open,
3536 pager_read,
3537 pager_draw,
3538 pager_request,
3539 pager_grep,
3540 pager_select,
3543 static bool
3544 log_open(struct view *view, enum open_flags flags)
3546 static const char *log_argv[] = {
3547 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3550 return begin_update(view, NULL, log_argv, flags);
3553 static enum request
3554 log_request(struct view *view, enum request request, struct line *line)
3556 switch (request) {
3557 case REQ_REFRESH:
3558 load_refs();
3559 refresh_view(view);
3560 return REQ_NONE;
3561 default:
3562 return pager_request(view, request, line);
3566 static struct view_ops log_ops = {
3567 "line",
3568 log_open,
3569 pager_read,
3570 pager_draw,
3571 log_request,
3572 pager_grep,
3573 pager_select,
3576 static bool
3577 diff_open(struct view *view, enum open_flags flags)
3579 static const char *diff_argv[] = {
3580 "git", "show", "--pretty=fuller", "--no-color", "--root",
3581 "--patch-with-stat", "--find-copies-harder", "-C",
3582 opt_diff_context_arg, "%(diffargs)", "%(commit)", "--",
3583 "%(fileargs)", NULL
3586 return begin_update(view, NULL, diff_argv, flags);
3589 static bool
3590 diff_common_read(struct view *view, char *data, bool *reading_diff_stat)
3592 if (reading_diff_stat) {
3593 size_t len = strlen(data);
3594 bool has_pipe = strchr(data, '|') != NULL;
3595 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3597 if (has_pipe && has_histogram) {
3598 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3599 } else {
3600 *reading_diff_stat = FALSE;
3603 } else if (!strcmp(data, "---")) {
3604 *reading_diff_stat = TRUE;
3607 return pager_read(view, data);
3610 static enum request
3611 diff_common_enter(struct view *view, enum request request, struct line *line)
3613 if (line->type == LINE_DIFF_STAT) {
3614 int file_number = 0;
3616 do {
3617 file_number++;
3618 line--;
3619 } while (line >= view->line && line->type == LINE_DIFF_STAT);
3621 while (line < view->line + view->lines) {
3622 if (line->type == LINE_DIFF_HEADER) {
3623 if (file_number == 1) {
3624 break;
3626 file_number--;
3628 line++;
3632 select_view_line(view, line - view->line);
3633 report("");
3634 return REQ_NONE;
3636 } else {
3637 return pager_request(view, request, line);
3641 static void
3642 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3644 char *sep = strchr(*text, c);
3646 if (sep != NULL) {
3647 *sep = 0;
3648 draw_text(view, *type, *text);
3649 *sep = c;
3650 *text = sep;
3651 *type = next_type;
3655 static bool
3656 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3658 char *text = line->data;
3659 enum line_type type = line->type;
3661 if (opt_line_number && draw_lineno(view, lineno))
3662 return TRUE;
3664 if (type == LINE_DIFF_STAT) {
3665 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3666 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3667 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3670 draw_text(view, type, text);
3671 return TRUE;
3674 static bool
3675 diff_read(struct view *view, char *data)
3677 static bool reading_diff_stat = FALSE;
3679 if (!data) {
3680 /* Fall back to retry if no diff will be shown. */
3681 if (view->lines == 0 && opt_file_argv) {
3682 int pos = argv_size(view->argv)
3683 - argv_size(opt_file_argv) - 1;
3685 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3686 for (; view->argv[pos]; pos++) {
3687 free((void *) view->argv[pos]);
3688 view->argv[pos] = NULL;
3691 if (view->pipe)
3692 io_done(view->pipe);
3693 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3694 return FALSE;
3697 return TRUE;
3700 return diff_common_read(view, data, &reading_diff_stat);
3703 static bool
3704 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3705 struct blame_header *header, struct blame_commit *commit)
3707 char line_arg[SIZEOF_STR];
3708 const char *blame_argv[] = {
3709 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3711 struct io io;
3712 bool ok = FALSE;
3713 char *buf;
3715 if (!string_format(line_arg, "-L%d,+1", lineno))
3716 return FALSE;
3718 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3719 return FALSE;
3721 while ((buf = io_get(&io, '\n', TRUE))) {
3722 if (header) {
3723 if (!parse_blame_header(header, buf, 9999999))
3724 break;
3725 header = NULL;
3727 } else if (parse_blame_info(commit, buf)) {
3728 ok = TRUE;
3729 break;
3733 if (io_error(&io))
3734 ok = FALSE;
3736 io_done(&io);
3737 return ok;
3740 static enum request
3741 diff_trace_origin(struct view *view, struct line *line)
3743 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3744 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3745 const char *chunk_data;
3746 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3747 int lineno = 0;
3748 const char *file = NULL;
3749 char ref[SIZEOF_REF];
3750 struct blame_header header;
3751 struct blame_commit commit;
3753 if (!diff || !chunk || chunk == line) {
3754 report("The line to trace must be inside a diff chunk");
3755 return REQ_NONE;
3758 for (; diff < line && !file; diff++) {
3759 const char *data = diff->data;
3761 if (!prefixcmp(data, "--- a/")) {
3762 file = data + STRING_SIZE("--- a/");
3763 break;
3767 if (diff == line || !file) {
3768 report("Failed to read the file name");
3769 return REQ_NONE;
3772 chunk_data = chunk->data;
3774 if (prefixcmp(chunk_data, "@@ -") ||
3775 !(chunk_data = strchr(chunk_data, chunk_marker)) ||
3776 parse_int(&lineno, chunk_data + 1, 0, 9999999) != OPT_OK) {
3777 report("Failed to read the line number");
3778 return REQ_NONE;
3781 if (lineno == 0) {
3782 report("This is the origin of the line");
3783 return REQ_NONE;
3786 for (chunk += 1; chunk < line; chunk++) {
3787 if (chunk->type == LINE_DIFF_ADD) {
3788 lineno += chunk_marker == '+';
3789 } else if (chunk->type == LINE_DIFF_DEL) {
3790 lineno += chunk_marker == '-';
3791 } else {
3792 lineno++;
3796 if (chunk_marker == '+')
3797 string_copy(ref, view->vid);
3798 else
3799 string_format(ref, "%s^", view->vid);
3801 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
3802 report("Failed to read blame data");
3803 return REQ_NONE;
3806 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
3807 string_copy(opt_ref, header.id);
3808 opt_goto_line = header.orig_lineno - 1;
3810 return REQ_VIEW_BLAME;
3813 static enum request
3814 diff_request(struct view *view, enum request request, struct line *line)
3816 switch (request) {
3817 case REQ_VIEW_BLAME:
3818 return diff_trace_origin(view, line);
3820 case REQ_DIFF_CONTEXT_UP:
3821 case REQ_DIFF_CONTEXT_DOWN:
3822 if (!update_diff_context(request))
3823 return REQ_NONE;
3824 reload_view(view);
3825 return REQ_NONE;
3827 case REQ_ENTER:
3828 return diff_common_enter(view, request, line);
3830 default:
3831 return pager_request(view, request, line);
3835 static void
3836 diff_select(struct view *view, struct line *line)
3838 if (line->type == LINE_DIFF_STAT) {
3839 const char *key = get_key(KEYMAP_DIFF, REQ_ENTER);
3841 string_format(view->ref, "Press '%s' to jump to file diff", key);
3842 } else {
3843 string_ncopy(view->ref, view->id, strlen(view->id));
3844 return pager_select(view, line);
3848 static struct view_ops diff_ops = {
3849 "line",
3850 diff_open,
3851 diff_read,
3852 diff_common_draw,
3853 diff_request,
3854 pager_grep,
3855 diff_select,
3859 * Help backend
3862 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
3864 static bool
3865 help_open_keymap_title(struct view *view, enum keymap keymap)
3867 struct line *line;
3869 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3870 help_keymap_hidden[keymap] ? '+' : '-',
3871 enum_name(keymap_map[keymap]));
3872 if (line)
3873 line->other = keymap;
3875 return help_keymap_hidden[keymap];
3878 static void
3879 help_open_keymap(struct view *view, enum keymap keymap)
3881 const char *group = NULL;
3882 char buf[SIZEOF_STR];
3883 size_t bufpos;
3884 bool add_title = TRUE;
3885 int i;
3887 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3888 const char *key = NULL;
3890 if (req_info[i].request == REQ_NONE)
3891 continue;
3893 if (!req_info[i].request) {
3894 group = req_info[i].help;
3895 continue;
3898 key = get_keys(keymap, req_info[i].request, TRUE);
3899 if (!key || !*key)
3900 continue;
3902 if (add_title && help_open_keymap_title(view, keymap))
3903 return;
3904 add_title = FALSE;
3906 if (group) {
3907 add_line_text(view, group, LINE_HELP_GROUP);
3908 group = NULL;
3911 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3912 enum_name(req_info[i]), req_info[i].help);
3915 group = "External commands:";
3917 for (i = 0; i < run_requests; i++) {
3918 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3919 const char *key;
3920 int argc;
3922 if (!req || req->keymap != keymap)
3923 continue;
3925 key = get_key_name(req->key);
3926 if (!*key)
3927 key = "(no key defined)";
3929 if (add_title && help_open_keymap_title(view, keymap))
3930 return;
3931 if (group) {
3932 add_line_text(view, group, LINE_HELP_GROUP);
3933 group = NULL;
3936 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3937 if (!string_format_from(buf, &bufpos, "%s%s",
3938 argc ? " " : "", req->argv[argc]))
3939 return;
3941 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3945 static bool
3946 help_open(struct view *view, enum open_flags flags)
3948 enum keymap keymap;
3950 reset_view(view);
3951 view->p_restore = TRUE;
3952 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3953 add_line_text(view, "", LINE_DEFAULT);
3955 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
3956 help_open_keymap(view, keymap);
3958 return TRUE;
3961 static enum request
3962 help_request(struct view *view, enum request request, struct line *line)
3964 switch (request) {
3965 case REQ_ENTER:
3966 if (line->type == LINE_HELP_KEYMAP) {
3967 help_keymap_hidden[line->other] =
3968 !help_keymap_hidden[line->other];
3969 refresh_view(view);
3972 return REQ_NONE;
3973 default:
3974 return pager_request(view, request, line);
3978 static struct view_ops help_ops = {
3979 "line",
3980 help_open,
3981 NULL,
3982 pager_draw,
3983 help_request,
3984 pager_grep,
3985 pager_select,
3990 * Tree backend
3993 struct tree_stack_entry {
3994 struct tree_stack_entry *prev; /* Entry below this in the stack */
3995 unsigned long lineno; /* Line number to restore */
3996 char *name; /* Position of name in opt_path */
3999 /* The top of the path stack. */
4000 static struct tree_stack_entry *tree_stack = NULL;
4001 unsigned long tree_lineno = 0;
4003 static void
4004 pop_tree_stack_entry(void)
4006 struct tree_stack_entry *entry = tree_stack;
4008 tree_lineno = entry->lineno;
4009 entry->name[0] = 0;
4010 tree_stack = entry->prev;
4011 free(entry);
4014 static void
4015 push_tree_stack_entry(const char *name, unsigned long lineno)
4017 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4018 size_t pathlen = strlen(opt_path);
4020 if (!entry)
4021 return;
4023 entry->prev = tree_stack;
4024 entry->name = opt_path + pathlen;
4025 tree_stack = entry;
4027 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4028 pop_tree_stack_entry();
4029 return;
4032 /* Move the current line to the first tree entry. */
4033 tree_lineno = 1;
4034 entry->lineno = lineno;
4037 /* Parse output from git-ls-tree(1):
4039 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4042 #define SIZEOF_TREE_ATTR \
4043 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4045 #define SIZEOF_TREE_MODE \
4046 STRING_SIZE("100644 ")
4048 #define TREE_ID_OFFSET \
4049 STRING_SIZE("100644 blob ")
4051 struct tree_entry {
4052 char id[SIZEOF_REV];
4053 mode_t mode;
4054 struct time time; /* Date from the author ident. */
4055 const char *author; /* Author of the commit. */
4056 char name[1];
4059 static const char *
4060 tree_path(const struct line *line)
4062 return ((struct tree_entry *) line->data)->name;
4065 static int
4066 tree_compare_entry(const struct line *line1, const struct line *line2)
4068 if (line1->type != line2->type)
4069 return line1->type == LINE_TREE_DIR ? -1 : 1;
4070 return strcmp(tree_path(line1), tree_path(line2));
4073 static const enum sort_field tree_sort_fields[] = {
4074 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4076 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4078 static int
4079 tree_compare(const void *l1, const void *l2)
4081 const struct line *line1 = (const struct line *) l1;
4082 const struct line *line2 = (const struct line *) l2;
4083 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4084 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4086 if (line1->type == LINE_TREE_HEAD)
4087 return -1;
4088 if (line2->type == LINE_TREE_HEAD)
4089 return 1;
4091 switch (get_sort_field(tree_sort_state)) {
4092 case ORDERBY_DATE:
4093 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4095 case ORDERBY_AUTHOR:
4096 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
4098 case ORDERBY_NAME:
4099 default:
4100 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4105 static struct line *
4106 tree_entry(struct view *view, enum line_type type, const char *path,
4107 const char *mode, const char *id)
4109 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4110 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4112 if (!entry || !line) {
4113 free(entry);
4114 return NULL;
4117 strncpy(entry->name, path, strlen(path));
4118 if (mode)
4119 entry->mode = strtoul(mode, NULL, 8);
4120 if (id)
4121 string_copy_rev(entry->id, id);
4123 return line;
4126 static bool
4127 tree_read_date(struct view *view, char *text, bool *read_date)
4129 static const char *author_name;
4130 static struct time author_time;
4132 if (!text && *read_date) {
4133 *read_date = FALSE;
4134 return TRUE;
4136 } else if (!text) {
4137 /* Find next entry to process */
4138 const char *log_file[] = {
4139 "git", "log", "--no-color", "--pretty=raw",
4140 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4143 if (!view->lines) {
4144 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4145 report("Tree is empty");
4146 return TRUE;
4149 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4150 report("Failed to load tree data");
4151 return TRUE;
4154 *read_date = TRUE;
4155 return FALSE;
4157 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4158 parse_author_line(text + STRING_SIZE("author "),
4159 &author_name, &author_time);
4161 } else if (*text == ':') {
4162 char *pos;
4163 size_t annotated = 1;
4164 size_t i;
4166 pos = strchr(text, '\t');
4167 if (!pos)
4168 return TRUE;
4169 text = pos + 1;
4170 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4171 text += strlen(opt_path);
4172 pos = strchr(text, '/');
4173 if (pos)
4174 *pos = 0;
4176 for (i = 1; i < view->lines; i++) {
4177 struct line *line = &view->line[i];
4178 struct tree_entry *entry = line->data;
4180 annotated += !!entry->author;
4181 if (entry->author || strcmp(entry->name, text))
4182 continue;
4184 entry->author = author_name;
4185 entry->time = author_time;
4186 line->dirty = 1;
4187 break;
4190 if (annotated == view->lines)
4191 io_kill(view->pipe);
4193 return TRUE;
4196 static bool
4197 tree_read(struct view *view, char *text)
4199 static bool read_date = FALSE;
4200 struct tree_entry *data;
4201 struct line *entry, *line;
4202 enum line_type type;
4203 size_t textlen = text ? strlen(text) : 0;
4204 char *path = text + SIZEOF_TREE_ATTR;
4206 if (read_date || !text)
4207 return tree_read_date(view, text, &read_date);
4209 if (textlen <= SIZEOF_TREE_ATTR)
4210 return FALSE;
4211 if (view->lines == 0 &&
4212 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4213 return FALSE;
4215 /* Strip the path part ... */
4216 if (*opt_path) {
4217 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4218 size_t striplen = strlen(opt_path);
4220 if (pathlen > striplen)
4221 memmove(path, path + striplen,
4222 pathlen - striplen + 1);
4224 /* Insert "link" to parent directory. */
4225 if (view->lines == 1 &&
4226 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4227 return FALSE;
4230 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4231 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4232 if (!entry)
4233 return FALSE;
4234 data = entry->data;
4236 /* Skip "Directory ..." and ".." line. */
4237 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4238 if (tree_compare_entry(line, entry) <= 0)
4239 continue;
4241 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4243 line->data = data;
4244 line->type = type;
4245 for (; line <= entry; line++)
4246 line->dirty = line->cleareol = 1;
4247 return TRUE;
4250 if (tree_lineno > view->lineno) {
4251 view->lineno = tree_lineno;
4252 tree_lineno = 0;
4255 return TRUE;
4258 static bool
4259 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4261 struct tree_entry *entry = line->data;
4263 if (line->type == LINE_TREE_HEAD) {
4264 if (draw_text(view, line->type, "Directory path /"))
4265 return TRUE;
4266 } else {
4267 if (draw_mode(view, entry->mode))
4268 return TRUE;
4270 if (draw_author(view, entry->author))
4271 return TRUE;
4273 if (draw_date(view, &entry->time))
4274 return TRUE;
4277 draw_text(view, line->type, entry->name);
4278 return TRUE;
4281 static void
4282 open_blob_editor(const char *id)
4284 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4285 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4286 int fd = mkstemp(file);
4288 if (fd == -1)
4289 report("Failed to create temporary file");
4290 else if (!io_run_append(blob_argv, fd))
4291 report("Failed to save blob data to file");
4292 else
4293 open_editor(file);
4294 if (fd != -1)
4295 unlink(file);
4298 static enum request
4299 tree_request(struct view *view, enum request request, struct line *line)
4301 enum open_flags flags;
4302 struct tree_entry *entry = line->data;
4304 switch (request) {
4305 case REQ_VIEW_BLAME:
4306 if (line->type != LINE_TREE_FILE) {
4307 report("Blame only supported for files");
4308 return REQ_NONE;
4311 string_copy(opt_ref, view->vid);
4312 return request;
4314 case REQ_EDIT:
4315 if (line->type != LINE_TREE_FILE) {
4316 report("Edit only supported for files");
4317 } else if (!is_head_commit(view->vid)) {
4318 open_blob_editor(entry->id);
4319 } else {
4320 open_editor(opt_file);
4322 return REQ_NONE;
4324 case REQ_TOGGLE_SORT_FIELD:
4325 case REQ_TOGGLE_SORT_ORDER:
4326 sort_view(view, request, &tree_sort_state, tree_compare);
4327 return REQ_NONE;
4329 case REQ_PARENT:
4330 if (!*opt_path) {
4331 /* quit view if at top of tree */
4332 return REQ_VIEW_CLOSE;
4334 /* fake 'cd ..' */
4335 line = &view->line[1];
4336 break;
4338 case REQ_ENTER:
4339 break;
4341 default:
4342 return request;
4345 /* Cleanup the stack if the tree view is at a different tree. */
4346 while (!*opt_path && tree_stack)
4347 pop_tree_stack_entry();
4349 switch (line->type) {
4350 case LINE_TREE_DIR:
4351 /* Depending on whether it is a subdirectory or parent link
4352 * mangle the path buffer. */
4353 if (line == &view->line[1] && *opt_path) {
4354 pop_tree_stack_entry();
4356 } else {
4357 const char *basename = tree_path(line);
4359 push_tree_stack_entry(basename, view->lineno);
4362 /* Trees and subtrees share the same ID, so they are not not
4363 * unique like blobs. */
4364 flags = OPEN_RELOAD;
4365 request = REQ_VIEW_TREE;
4366 break;
4368 case LINE_TREE_FILE:
4369 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4370 request = REQ_VIEW_BLOB;
4371 break;
4373 default:
4374 return REQ_NONE;
4377 open_view(view, request, flags);
4378 if (request == REQ_VIEW_TREE)
4379 view->lineno = tree_lineno;
4381 return REQ_NONE;
4384 static bool
4385 tree_grep(struct view *view, struct line *line)
4387 struct tree_entry *entry = line->data;
4388 const char *text[] = {
4389 entry->name,
4390 mkauthor(entry->author, opt_author_cols, opt_author),
4391 mkdate(&entry->time, opt_date),
4392 NULL
4395 return grep_text(view, text);
4398 static void
4399 tree_select(struct view *view, struct line *line)
4401 struct tree_entry *entry = line->data;
4403 if (line->type == LINE_TREE_FILE) {
4404 string_copy_rev(ref_blob, entry->id);
4405 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4407 } else if (line->type != LINE_TREE_DIR) {
4408 return;
4411 string_copy_rev(view->ref, entry->id);
4414 static bool
4415 tree_open(struct view *view, enum open_flags flags)
4417 static const char *tree_argv[] = {
4418 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4421 if (view->lines == 0 && opt_prefix[0]) {
4422 char *pos = opt_prefix;
4424 while (pos && *pos) {
4425 char *end = strchr(pos, '/');
4427 if (end)
4428 *end = 0;
4429 push_tree_stack_entry(pos, 0);
4430 pos = end;
4431 if (end) {
4432 *end = '/';
4433 pos++;
4437 } else if (strcmp(view->vid, view->id)) {
4438 opt_path[0] = 0;
4441 return begin_update(view, opt_cdup, tree_argv, flags);
4444 static struct view_ops tree_ops = {
4445 "file",
4446 tree_open,
4447 tree_read,
4448 tree_draw,
4449 tree_request,
4450 tree_grep,
4451 tree_select,
4454 static bool
4455 blob_open(struct view *view, enum open_flags flags)
4457 static const char *blob_argv[] = {
4458 "git", "cat-file", "blob", "%(blob)", NULL
4461 return begin_update(view, NULL, blob_argv, flags);
4464 static bool
4465 blob_read(struct view *view, char *line)
4467 if (!line)
4468 return TRUE;
4469 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4472 static enum request
4473 blob_request(struct view *view, enum request request, struct line *line)
4475 switch (request) {
4476 case REQ_EDIT:
4477 open_blob_editor(view->vid);
4478 return REQ_NONE;
4479 default:
4480 return pager_request(view, request, line);
4484 static struct view_ops blob_ops = {
4485 "line",
4486 blob_open,
4487 blob_read,
4488 pager_draw,
4489 blob_request,
4490 pager_grep,
4491 pager_select,
4495 * Blame backend
4497 * Loading the blame view is a two phase job:
4499 * 1. File content is read either using opt_file from the
4500 * filesystem or using git-cat-file.
4501 * 2. Then blame information is incrementally added by
4502 * reading output from git-blame.
4505 struct blame {
4506 struct blame_commit *commit;
4507 unsigned long lineno;
4508 char text[1];
4511 static bool
4512 blame_open(struct view *view, enum open_flags flags)
4514 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4515 char path[SIZEOF_STR];
4516 size_t i;
4518 if (!view->prev && *opt_prefix) {
4519 string_copy(path, opt_file);
4520 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4521 return FALSE;
4524 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4525 const char *blame_cat_file_argv[] = {
4526 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4529 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4530 return FALSE;
4533 /* First pass: remove multiple references to the same commit. */
4534 for (i = 0; i < view->lines; i++) {
4535 struct blame *blame = view->line[i].data;
4537 if (blame->commit && blame->commit->id[0])
4538 blame->commit->id[0] = 0;
4539 else
4540 blame->commit = NULL;
4543 /* Second pass: free existing references. */
4544 for (i = 0; i < view->lines; i++) {
4545 struct blame *blame = view->line[i].data;
4547 if (blame->commit)
4548 free(blame->commit);
4551 string_format(view->vid, "%s", opt_file);
4552 string_format(view->ref, "%s ...", opt_file);
4554 return TRUE;
4557 static struct blame_commit *
4558 get_blame_commit(struct view *view, const char *id)
4560 size_t i;
4562 for (i = 0; i < view->lines; i++) {
4563 struct blame *blame = view->line[i].data;
4565 if (!blame->commit)
4566 continue;
4568 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4569 return blame->commit;
4573 struct blame_commit *commit = calloc(1, sizeof(*commit));
4575 if (commit)
4576 string_ncopy(commit->id, id, SIZEOF_REV);
4577 return commit;
4581 static struct blame_commit *
4582 read_blame_commit(struct view *view, const char *text, int *blamed)
4584 struct blame_header header;
4585 struct blame_commit *commit;
4586 struct blame *blame;
4588 if (!parse_blame_header(&header, text, view->lines))
4589 return NULL;
4591 commit = get_blame_commit(view, text);
4592 if (!commit)
4593 return NULL;
4595 *blamed += header.group;
4596 while (header.group--) {
4597 struct line *line = &view->line[header.lineno + header.group - 1];
4599 blame = line->data;
4600 blame->commit = commit;
4601 blame->lineno = header.orig_lineno + header.group - 1;
4602 line->dirty = 1;
4605 return commit;
4608 static bool
4609 blame_read_file(struct view *view, const char *line, bool *read_file)
4611 if (!line) {
4612 const char *blame_argv[] = {
4613 "git", "blame", "%(blameargs)", "--incremental",
4614 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4617 if (view->lines == 0 && !view->prev)
4618 die("No blame exist for %s", view->vid);
4620 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4621 report("Failed to load blame data");
4622 return TRUE;
4625 if (opt_goto_line > 0) {
4626 select_view_line(view, opt_goto_line);
4627 opt_goto_line = 0;
4630 *read_file = FALSE;
4631 return FALSE;
4633 } else {
4634 size_t linelen = strlen(line);
4635 struct blame *blame = malloc(sizeof(*blame) + linelen);
4637 if (!blame)
4638 return FALSE;
4640 blame->commit = NULL;
4641 strncpy(blame->text, line, linelen);
4642 blame->text[linelen] = 0;
4643 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4647 static bool
4648 blame_read(struct view *view, char *line)
4650 static struct blame_commit *commit = NULL;
4651 static int blamed = 0;
4652 static bool read_file = TRUE;
4654 if (read_file)
4655 return blame_read_file(view, line, &read_file);
4657 if (!line) {
4658 /* Reset all! */
4659 commit = NULL;
4660 blamed = 0;
4661 read_file = TRUE;
4662 string_format(view->ref, "%s", view->vid);
4663 if (view_is_displayed(view)) {
4664 update_view_title(view);
4665 redraw_view_from(view, 0);
4667 return TRUE;
4670 if (!commit) {
4671 commit = read_blame_commit(view, line, &blamed);
4672 string_format(view->ref, "%s %2d%%", view->vid,
4673 view->lines ? blamed * 100 / view->lines : 0);
4675 } else if (parse_blame_info(commit, line)) {
4676 commit = NULL;
4679 return TRUE;
4682 static bool
4683 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4685 struct blame *blame = line->data;
4686 struct time *time = NULL;
4687 const char *id = NULL, *author = NULL;
4688 enum line_type id_type = LINE_BLAME_ID;
4689 static const enum line_type blame_colors[] = {
4690 LINE_PALETTE_0,
4691 LINE_PALETTE_1,
4692 LINE_PALETTE_2,
4693 LINE_PALETTE_3,
4694 LINE_PALETTE_4,
4695 LINE_PALETTE_5,
4696 LINE_PALETTE_6,
4699 #define BLAME_COLOR(i) \
4700 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4702 if (blame->commit && *blame->commit->filename) {
4703 id = blame->commit->id;
4704 author = blame->commit->author;
4705 time = &blame->commit->time;
4706 id_type = BLAME_COLOR((long) blame->commit);
4709 if (draw_date(view, time))
4710 return TRUE;
4712 if (draw_author(view, author))
4713 return TRUE;
4715 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4716 return TRUE;
4718 if (draw_lineno(view, lineno))
4719 return TRUE;
4721 draw_text(view, LINE_DEFAULT, blame->text);
4722 return TRUE;
4725 static bool
4726 check_blame_commit(struct blame *blame, bool check_null_id)
4728 if (!blame->commit)
4729 report("Commit data not loaded yet");
4730 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4731 report("No commit exist for the selected line");
4732 else
4733 return TRUE;
4734 return FALSE;
4737 static void
4738 setup_blame_parent_line(struct view *view, struct blame *blame)
4740 char from[SIZEOF_REF + SIZEOF_STR];
4741 char to[SIZEOF_REF + SIZEOF_STR];
4742 const char *diff_tree_argv[] = {
4743 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4744 "-U0", from, to, "--", NULL
4746 struct io io;
4747 int parent_lineno = -1;
4748 int blamed_lineno = -1;
4749 char *line;
4751 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4752 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4753 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4754 return;
4756 while ((line = io_get(&io, '\n', TRUE))) {
4757 if (*line == '@') {
4758 char *pos = strchr(line, '+');
4760 parent_lineno = atoi(line + 4);
4761 if (pos)
4762 blamed_lineno = atoi(pos + 1);
4764 } else if (*line == '+' && parent_lineno != -1) {
4765 if (blame->lineno == blamed_lineno - 1 &&
4766 !strcmp(blame->text, line + 1)) {
4767 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4768 break;
4770 blamed_lineno++;
4774 io_done(&io);
4777 static enum request
4778 blame_request(struct view *view, enum request request, struct line *line)
4780 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4781 struct blame *blame = line->data;
4783 switch (request) {
4784 case REQ_VIEW_BLAME:
4785 if (check_blame_commit(blame, TRUE)) {
4786 string_copy(opt_ref, blame->commit->id);
4787 string_copy(opt_file, blame->commit->filename);
4788 if (blame->lineno)
4789 view->lineno = blame->lineno;
4790 reload_view(view);
4792 break;
4794 case REQ_PARENT:
4795 if (!check_blame_commit(blame, TRUE))
4796 break;
4797 if (!*blame->commit->parent_id) {
4798 report("The selected commit has no parents");
4799 } else {
4800 string_copy_rev(opt_ref, blame->commit->parent_id);
4801 string_copy(opt_file, blame->commit->parent_filename);
4802 setup_blame_parent_line(view, blame);
4803 opt_goto_line = blame->lineno;
4804 reload_view(view);
4806 break;
4808 case REQ_ENTER:
4809 if (!check_blame_commit(blame, FALSE))
4810 break;
4812 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4813 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4814 break;
4816 if (!strcmp(blame->commit->id, NULL_ID)) {
4817 struct view *diff = VIEW(REQ_VIEW_DIFF);
4818 const char *diff_index_argv[] = {
4819 "git", "diff-index", "--root", "--patch-with-stat",
4820 "-C", "-M", opt_diff_context_arg,
4821 "HEAD", "--", view->vid, NULL
4824 if (!*blame->commit->parent_id) {
4825 diff_index_argv[1] = "diff";
4826 diff_index_argv[2] = "--no-color";
4827 diff_index_argv[7] = "--";
4828 diff_index_argv[8] = "/dev/null";
4831 open_argv(view, diff, diff_index_argv, NULL, flags);
4832 if (diff->pipe)
4833 string_copy_rev(diff->ref, NULL_ID);
4834 } else {
4835 open_view(view, REQ_VIEW_DIFF, flags);
4837 break;
4839 default:
4840 return request;
4843 return REQ_NONE;
4846 static bool
4847 blame_grep(struct view *view, struct line *line)
4849 struct blame *blame = line->data;
4850 struct blame_commit *commit = blame->commit;
4851 const char *text[] = {
4852 blame->text,
4853 commit ? commit->title : "",
4854 commit ? commit->id : "",
4855 commit && opt_author ? commit->author : "",
4856 commit ? mkdate(&commit->time, opt_date) : "",
4857 NULL
4860 return grep_text(view, text);
4863 static void
4864 blame_select(struct view *view, struct line *line)
4866 struct blame *blame = line->data;
4867 struct blame_commit *commit = blame->commit;
4869 if (!commit)
4870 return;
4872 if (!strcmp(commit->id, NULL_ID))
4873 string_ncopy(ref_commit, "HEAD", 4);
4874 else
4875 string_copy_rev(ref_commit, commit->id);
4878 static struct view_ops blame_ops = {
4879 "line",
4880 blame_open,
4881 blame_read,
4882 blame_draw,
4883 blame_request,
4884 blame_grep,
4885 blame_select,
4889 * Branch backend
4892 struct branch {
4893 const char *author; /* Author of the last commit. */
4894 struct time time; /* Date of the last activity. */
4895 const struct ref *ref; /* Name and commit ID information. */
4898 static const struct ref branch_all;
4900 static const enum sort_field branch_sort_fields[] = {
4901 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4903 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4905 static int
4906 branch_compare(const void *l1, const void *l2)
4908 const struct branch *branch1 = ((const struct line *) l1)->data;
4909 const struct branch *branch2 = ((const struct line *) l2)->data;
4911 if (branch1->ref == &branch_all)
4912 return -1;
4913 else if (branch2->ref == &branch_all)
4914 return 1;
4916 switch (get_sort_field(branch_sort_state)) {
4917 case ORDERBY_DATE:
4918 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4920 case ORDERBY_AUTHOR:
4921 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4923 case ORDERBY_NAME:
4924 default:
4925 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4929 static bool
4930 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4932 struct branch *branch = line->data;
4933 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
4935 if (draw_date(view, &branch->time))
4936 return TRUE;
4938 if (draw_author(view, branch->author))
4939 return TRUE;
4941 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4942 return TRUE;
4945 static enum request
4946 branch_request(struct view *view, enum request request, struct line *line)
4948 struct branch *branch = line->data;
4950 switch (request) {
4951 case REQ_REFRESH:
4952 load_refs();
4953 refresh_view(view);
4954 return REQ_NONE;
4956 case REQ_TOGGLE_SORT_FIELD:
4957 case REQ_TOGGLE_SORT_ORDER:
4958 sort_view(view, request, &branch_sort_state, branch_compare);
4959 return REQ_NONE;
4961 case REQ_ENTER:
4963 const struct ref *ref = branch->ref;
4964 const char *all_branches_argv[] = {
4965 "git", "log", "--no-color", "--pretty=raw", "--parents",
4966 "--topo-order",
4967 ref == &branch_all ? "--all" : ref->name, NULL
4969 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4971 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4972 return REQ_NONE;
4974 default:
4975 return request;
4979 static bool
4980 branch_read(struct view *view, char *line)
4982 static char id[SIZEOF_REV];
4983 struct branch *reference;
4984 size_t i;
4986 if (!line)
4987 return TRUE;
4989 switch (get_line_type(line)) {
4990 case LINE_COMMIT:
4991 string_copy_rev(id, line + STRING_SIZE("commit "));
4992 return TRUE;
4994 case LINE_AUTHOR:
4995 for (i = 0, reference = NULL; i < view->lines; i++) {
4996 struct branch *branch = view->line[i].data;
4998 if (strcmp(branch->ref->id, id))
4999 continue;
5001 view->line[i].dirty = TRUE;
5002 if (reference) {
5003 branch->author = reference->author;
5004 branch->time = reference->time;
5005 continue;
5008 parse_author_line(line + STRING_SIZE("author "),
5009 &branch->author, &branch->time);
5010 reference = branch;
5012 return TRUE;
5014 default:
5015 return TRUE;
5020 static bool
5021 branch_open_visitor(void *data, const struct ref *ref)
5023 struct view *view = data;
5024 struct branch *branch;
5026 if (ref->tag || ref->ltag)
5027 return TRUE;
5029 branch = calloc(1, sizeof(*branch));
5030 if (!branch)
5031 return FALSE;
5033 branch->ref = ref;
5034 return !!add_line_data(view, branch, LINE_DEFAULT);
5037 static bool
5038 branch_open(struct view *view, enum open_flags flags)
5040 const char *branch_log[] = {
5041 "git", "log", "--no-color", "--pretty=raw",
5042 "--simplify-by-decoration", "--all", NULL
5045 if (!begin_update(view, NULL, branch_log, flags)) {
5046 report("Failed to load branch data");
5047 return TRUE;
5050 branch_open_visitor(view, &branch_all);
5051 foreach_ref(branch_open_visitor, view);
5052 view->p_restore = TRUE;
5054 return TRUE;
5057 static bool
5058 branch_grep(struct view *view, struct line *line)
5060 struct branch *branch = line->data;
5061 const char *text[] = {
5062 branch->ref->name,
5063 mkauthor(branch->author, opt_author_cols, opt_author),
5064 NULL
5067 return grep_text(view, text);
5070 static void
5071 branch_select(struct view *view, struct line *line)
5073 struct branch *branch = line->data;
5075 string_copy_rev(view->ref, branch->ref->id);
5076 string_copy_rev(ref_commit, branch->ref->id);
5077 string_copy_rev(ref_head, branch->ref->id);
5078 string_copy_rev(ref_branch, branch->ref->name);
5081 static struct view_ops branch_ops = {
5082 "branch",
5083 branch_open,
5084 branch_read,
5085 branch_draw,
5086 branch_request,
5087 branch_grep,
5088 branch_select,
5092 * Status backend
5095 struct status {
5096 char status;
5097 struct {
5098 mode_t mode;
5099 char rev[SIZEOF_REV];
5100 char name[SIZEOF_STR];
5101 } old;
5102 struct {
5103 mode_t mode;
5104 char rev[SIZEOF_REV];
5105 char name[SIZEOF_STR];
5106 } new;
5109 static char status_onbranch[SIZEOF_STR];
5110 static struct status stage_status;
5111 static enum line_type stage_line_type;
5112 static size_t stage_chunks;
5113 static int *stage_chunk;
5115 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5117 /* This should work even for the "On branch" line. */
5118 static inline bool
5119 status_has_none(struct view *view, struct line *line)
5121 return line < view->line + view->lines && !line[1].data;
5124 /* Get fields from the diff line:
5125 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5127 static inline bool
5128 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5130 const char *old_mode = buf + 1;
5131 const char *new_mode = buf + 8;
5132 const char *old_rev = buf + 15;
5133 const char *new_rev = buf + 56;
5134 const char *status = buf + 97;
5136 if (bufsize < 98 ||
5137 old_mode[-1] != ':' ||
5138 new_mode[-1] != ' ' ||
5139 old_rev[-1] != ' ' ||
5140 new_rev[-1] != ' ' ||
5141 status[-1] != ' ')
5142 return FALSE;
5144 file->status = *status;
5146 string_copy_rev(file->old.rev, old_rev);
5147 string_copy_rev(file->new.rev, new_rev);
5149 file->old.mode = strtoul(old_mode, NULL, 8);
5150 file->new.mode = strtoul(new_mode, NULL, 8);
5152 file->old.name[0] = file->new.name[0] = 0;
5154 return TRUE;
5157 static bool
5158 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5160 struct status *unmerged = NULL;
5161 char *buf;
5162 struct io io;
5164 if (!io_run(&io, IO_RD, opt_cdup, argv))
5165 return FALSE;
5167 add_line_data(view, NULL, type);
5169 while ((buf = io_get(&io, 0, TRUE))) {
5170 struct status *file = unmerged;
5172 if (!file) {
5173 file = calloc(1, sizeof(*file));
5174 if (!file || !add_line_data(view, file, type))
5175 goto error_out;
5178 /* Parse diff info part. */
5179 if (status) {
5180 file->status = status;
5181 if (status == 'A')
5182 string_copy(file->old.rev, NULL_ID);
5184 } else if (!file->status || file == unmerged) {
5185 if (!status_get_diff(file, buf, strlen(buf)))
5186 goto error_out;
5188 buf = io_get(&io, 0, TRUE);
5189 if (!buf)
5190 break;
5192 /* Collapse all modified entries that follow an
5193 * associated unmerged entry. */
5194 if (unmerged == file) {
5195 unmerged->status = 'U';
5196 unmerged = NULL;
5197 } else if (file->status == 'U') {
5198 unmerged = file;
5202 /* Grab the old name for rename/copy. */
5203 if (!*file->old.name &&
5204 (file->status == 'R' || file->status == 'C')) {
5205 string_ncopy(file->old.name, buf, strlen(buf));
5207 buf = io_get(&io, 0, TRUE);
5208 if (!buf)
5209 break;
5212 /* git-ls-files just delivers a NUL separated list of
5213 * file names similar to the second half of the
5214 * git-diff-* output. */
5215 string_ncopy(file->new.name, buf, strlen(buf));
5216 if (!*file->old.name)
5217 string_copy(file->old.name, file->new.name);
5218 file = NULL;
5221 if (io_error(&io)) {
5222 error_out:
5223 io_done(&io);
5224 return FALSE;
5227 if (!view->line[view->lines - 1].data)
5228 add_line_data(view, NULL, LINE_STAT_NONE);
5230 io_done(&io);
5231 return TRUE;
5234 /* Don't show unmerged entries in the staged section. */
5235 static const char *status_diff_index_argv[] = {
5236 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5237 "--cached", "-M", "HEAD", NULL
5240 static const char *status_diff_files_argv[] = {
5241 "git", "diff-files", "-z", NULL
5244 static const char *status_list_other_argv[] = {
5245 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5248 static const char *status_list_no_head_argv[] = {
5249 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5252 static const char *update_index_argv[] = {
5253 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5256 /* Restore the previous line number to stay in the context or select a
5257 * line with something that can be updated. */
5258 static void
5259 status_restore(struct view *view)
5261 if (view->p_lineno >= view->lines)
5262 view->p_lineno = view->lines - 1;
5263 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5264 view->p_lineno++;
5265 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5266 view->p_lineno--;
5268 /* If the above fails, always skip the "On branch" line. */
5269 if (view->p_lineno < view->lines)
5270 view->lineno = view->p_lineno;
5271 else
5272 view->lineno = 1;
5274 if (view->lineno < view->offset)
5275 view->offset = view->lineno;
5276 else if (view->offset + view->height <= view->lineno)
5277 view->offset = view->lineno - view->height + 1;
5279 view->p_restore = FALSE;
5282 static void
5283 status_update_onbranch(void)
5285 static const char *paths[][2] = {
5286 { "rebase-apply/rebasing", "Rebasing" },
5287 { "rebase-apply/applying", "Applying mailbox" },
5288 { "rebase-apply/", "Rebasing mailbox" },
5289 { "rebase-merge/interactive", "Interactive rebase" },
5290 { "rebase-merge/", "Rebase merge" },
5291 { "MERGE_HEAD", "Merging" },
5292 { "BISECT_LOG", "Bisecting" },
5293 { "HEAD", "On branch" },
5295 char buf[SIZEOF_STR];
5296 struct stat stat;
5297 int i;
5299 if (is_initial_commit()) {
5300 string_copy(status_onbranch, "Initial commit");
5301 return;
5304 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5305 char *head = opt_head;
5307 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5308 lstat(buf, &stat) < 0)
5309 continue;
5311 if (!*opt_head) {
5312 struct io io;
5314 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5315 io_read_buf(&io, buf, sizeof(buf))) {
5316 head = buf;
5317 if (!prefixcmp(head, "refs/heads/"))
5318 head += STRING_SIZE("refs/heads/");
5322 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5323 string_copy(status_onbranch, opt_head);
5324 return;
5327 string_copy(status_onbranch, "Not currently on any branch");
5330 /* First parse staged info using git-diff-index(1), then parse unstaged
5331 * info using git-diff-files(1), and finally untracked files using
5332 * git-ls-files(1). */
5333 static bool
5334 status_open(struct view *view, enum open_flags flags)
5336 reset_view(view);
5338 add_line_data(view, NULL, LINE_STAT_HEAD);
5339 status_update_onbranch();
5341 io_run_bg(update_index_argv);
5343 if (is_initial_commit()) {
5344 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5345 return FALSE;
5346 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5347 return FALSE;
5350 if (!opt_untracked_dirs_content)
5351 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5353 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5354 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5355 return FALSE;
5357 /* Restore the exact position or use the specialized restore
5358 * mode? */
5359 if (!view->p_restore)
5360 status_restore(view);
5361 return TRUE;
5364 static bool
5365 status_draw(struct view *view, struct line *line, unsigned int lineno)
5367 struct status *status = line->data;
5368 enum line_type type;
5369 const char *text;
5371 if (!status) {
5372 switch (line->type) {
5373 case LINE_STAT_STAGED:
5374 type = LINE_STAT_SECTION;
5375 text = "Changes to be committed:";
5376 break;
5378 case LINE_STAT_UNSTAGED:
5379 type = LINE_STAT_SECTION;
5380 text = "Changed but not updated:";
5381 break;
5383 case LINE_STAT_UNTRACKED:
5384 type = LINE_STAT_SECTION;
5385 text = "Untracked files:";
5386 break;
5388 case LINE_STAT_NONE:
5389 type = LINE_DEFAULT;
5390 text = " (no files)";
5391 break;
5393 case LINE_STAT_HEAD:
5394 type = LINE_STAT_HEAD;
5395 text = status_onbranch;
5396 break;
5398 default:
5399 return FALSE;
5401 } else {
5402 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5404 buf[0] = status->status;
5405 if (draw_text(view, line->type, buf))
5406 return TRUE;
5407 type = LINE_DEFAULT;
5408 text = status->new.name;
5411 draw_text(view, type, text);
5412 return TRUE;
5415 static enum request
5416 status_enter(struct view *view, struct line *line)
5418 struct status *status = line->data;
5419 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5421 if (line->type == LINE_STAT_NONE ||
5422 (!status && line[1].type == LINE_STAT_NONE)) {
5423 report("No file to diff");
5424 return REQ_NONE;
5427 switch (line->type) {
5428 case LINE_STAT_STAGED:
5429 case LINE_STAT_UNSTAGED:
5430 break;
5432 case LINE_STAT_UNTRACKED:
5433 if (!status) {
5434 report("No file to show");
5435 return REQ_NONE;
5438 if (!suffixcmp(status->new.name, -1, "/")) {
5439 report("Cannot display a directory");
5440 return REQ_NONE;
5442 break;
5444 case LINE_STAT_HEAD:
5445 return REQ_NONE;
5447 default:
5448 die("line type %d not handled in switch", line->type);
5451 if (status) {
5452 stage_status = *status;
5453 } else {
5454 memset(&stage_status, 0, sizeof(stage_status));
5457 stage_line_type = line->type;
5458 stage_chunks = 0;
5460 open_view(view, REQ_VIEW_STAGE, flags);
5461 return REQ_NONE;
5464 static bool
5465 status_exists(struct view *view, struct status *status, enum line_type type)
5467 unsigned long lineno;
5469 for (lineno = 0; lineno < view->lines; lineno++) {
5470 struct line *line = &view->line[lineno];
5471 struct status *pos = line->data;
5473 if (line->type != type)
5474 continue;
5475 if (!pos && (!status || !status->status) && line[1].data) {
5476 select_view_line(view, lineno);
5477 return TRUE;
5479 if (pos && !strcmp(status->new.name, pos->new.name)) {
5480 select_view_line(view, lineno);
5481 return TRUE;
5485 return FALSE;
5489 static bool
5490 status_update_prepare(struct io *io, enum line_type type)
5492 const char *staged_argv[] = {
5493 "git", "update-index", "-z", "--index-info", NULL
5495 const char *others_argv[] = {
5496 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5499 switch (type) {
5500 case LINE_STAT_STAGED:
5501 return io_run(io, IO_WR, opt_cdup, staged_argv);
5503 case LINE_STAT_UNSTAGED:
5504 case LINE_STAT_UNTRACKED:
5505 return io_run(io, IO_WR, opt_cdup, others_argv);
5507 default:
5508 die("line type %d not handled in switch", type);
5509 return FALSE;
5513 static bool
5514 status_update_write(struct io *io, struct status *status, enum line_type type)
5516 char buf[SIZEOF_STR];
5517 size_t bufsize = 0;
5519 switch (type) {
5520 case LINE_STAT_STAGED:
5521 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5522 status->old.mode,
5523 status->old.rev,
5524 status->old.name, 0))
5525 return FALSE;
5526 break;
5528 case LINE_STAT_UNSTAGED:
5529 case LINE_STAT_UNTRACKED:
5530 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5531 return FALSE;
5532 break;
5534 default:
5535 die("line type %d not handled in switch", type);
5538 return io_write(io, buf, bufsize);
5541 static bool
5542 status_update_file(struct status *status, enum line_type type)
5544 struct io io;
5545 bool result;
5547 if (!status_update_prepare(&io, type))
5548 return FALSE;
5550 result = status_update_write(&io, status, type);
5551 return io_done(&io) && result;
5554 static bool
5555 status_update_files(struct view *view, struct line *line)
5557 char buf[sizeof(view->ref)];
5558 struct io io;
5559 bool result = TRUE;
5560 struct line *pos = view->line + view->lines;
5561 int files = 0;
5562 int file, done;
5563 int cursor_y = -1, cursor_x = -1;
5565 if (!status_update_prepare(&io, line->type))
5566 return FALSE;
5568 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5569 files++;
5571 string_copy(buf, view->ref);
5572 getsyx(cursor_y, cursor_x);
5573 for (file = 0, done = 5; result && file < files; line++, file++) {
5574 int almost_done = file * 100 / files;
5576 if (almost_done > done) {
5577 done = almost_done;
5578 string_format(view->ref, "updating file %u of %u (%d%% done)",
5579 file, files, done);
5580 update_view_title(view);
5581 setsyx(cursor_y, cursor_x);
5582 doupdate();
5584 result = status_update_write(&io, line->data, line->type);
5586 string_copy(view->ref, buf);
5588 return io_done(&io) && result;
5591 static bool
5592 status_update(struct view *view)
5594 struct line *line = &view->line[view->lineno];
5596 assert(view->lines);
5598 if (!line->data) {
5599 /* This should work even for the "On branch" line. */
5600 if (line < view->line + view->lines && !line[1].data) {
5601 report("Nothing to update");
5602 return FALSE;
5605 if (!status_update_files(view, line + 1)) {
5606 report("Failed to update file status");
5607 return FALSE;
5610 } else if (!status_update_file(line->data, line->type)) {
5611 report("Failed to update file status");
5612 return FALSE;
5615 return TRUE;
5618 static bool
5619 status_revert(struct status *status, enum line_type type, bool has_none)
5621 if (!status || type != LINE_STAT_UNSTAGED) {
5622 if (type == LINE_STAT_STAGED) {
5623 report("Cannot revert changes to staged files");
5624 } else if (type == LINE_STAT_UNTRACKED) {
5625 report("Cannot revert changes to untracked files");
5626 } else if (has_none) {
5627 report("Nothing to revert");
5628 } else {
5629 report("Cannot revert changes to multiple files");
5632 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5633 char mode[10] = "100644";
5634 const char *reset_argv[] = {
5635 "git", "update-index", "--cacheinfo", mode,
5636 status->old.rev, status->old.name, NULL
5638 const char *checkout_argv[] = {
5639 "git", "checkout", "--", status->old.name, NULL
5642 if (status->status == 'U') {
5643 string_format(mode, "%5o", status->old.mode);
5645 if (status->old.mode == 0 && status->new.mode == 0) {
5646 reset_argv[2] = "--force-remove";
5647 reset_argv[3] = status->old.name;
5648 reset_argv[4] = NULL;
5651 if (!io_run_fg(reset_argv, opt_cdup))
5652 return FALSE;
5653 if (status->old.mode == 0 && status->new.mode == 0)
5654 return TRUE;
5657 return io_run_fg(checkout_argv, opt_cdup);
5660 return FALSE;
5663 static enum request
5664 status_request(struct view *view, enum request request, struct line *line)
5666 struct status *status = line->data;
5668 switch (request) {
5669 case REQ_STATUS_UPDATE:
5670 if (!status_update(view))
5671 return REQ_NONE;
5672 break;
5674 case REQ_STATUS_REVERT:
5675 if (!status_revert(status, line->type, status_has_none(view, line)))
5676 return REQ_NONE;
5677 break;
5679 case REQ_STATUS_MERGE:
5680 if (!status || status->status != 'U') {
5681 report("Merging only possible for files with unmerged status ('U').");
5682 return REQ_NONE;
5684 open_mergetool(status->new.name);
5685 break;
5687 case REQ_EDIT:
5688 if (!status)
5689 return request;
5690 if (status->status == 'D') {
5691 report("File has been deleted.");
5692 return REQ_NONE;
5695 open_editor(status->new.name);
5696 break;
5698 case REQ_VIEW_BLAME:
5699 if (status)
5700 opt_ref[0] = 0;
5701 return request;
5703 case REQ_ENTER:
5704 /* After returning the status view has been split to
5705 * show the stage view. No further reloading is
5706 * necessary. */
5707 return status_enter(view, line);
5709 case REQ_REFRESH:
5710 /* Simply reload the view. */
5711 break;
5713 default:
5714 return request;
5717 refresh_view(view);
5719 return REQ_NONE;
5722 static void
5723 status_select(struct view *view, struct line *line)
5725 struct status *status = line->data;
5726 char file[SIZEOF_STR] = "all files";
5727 const char *text;
5728 const char *key;
5730 if (status && !string_format(file, "'%s'", status->new.name))
5731 return;
5733 if (!status && line[1].type == LINE_STAT_NONE)
5734 line++;
5736 switch (line->type) {
5737 case LINE_STAT_STAGED:
5738 text = "Press %s to unstage %s for commit";
5739 break;
5741 case LINE_STAT_UNSTAGED:
5742 text = "Press %s to stage %s for commit";
5743 break;
5745 case LINE_STAT_UNTRACKED:
5746 text = "Press %s to stage %s for addition";
5747 break;
5749 case LINE_STAT_HEAD:
5750 case LINE_STAT_NONE:
5751 text = "Nothing to update";
5752 break;
5754 default:
5755 die("line type %d not handled in switch", line->type);
5758 if (status && status->status == 'U') {
5759 text = "Press %s to resolve conflict in %s";
5760 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5762 } else {
5763 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5766 string_format(view->ref, text, key, file);
5767 if (status)
5768 string_copy(opt_file, status->new.name);
5771 static bool
5772 status_grep(struct view *view, struct line *line)
5774 struct status *status = line->data;
5776 if (status) {
5777 const char buf[2] = { status->status, 0 };
5778 const char *text[] = { status->new.name, buf, NULL };
5780 return grep_text(view, text);
5783 return FALSE;
5786 static struct view_ops status_ops = {
5787 "file",
5788 status_open,
5789 NULL,
5790 status_draw,
5791 status_request,
5792 status_grep,
5793 status_select,
5797 static bool
5798 stage_diff_write(struct io *io, struct line *line, struct line *end)
5800 while (line < end) {
5801 if (!io_write(io, line->data, strlen(line->data)) ||
5802 !io_write(io, "\n", 1))
5803 return FALSE;
5804 line++;
5805 if (line->type == LINE_DIFF_CHUNK ||
5806 line->type == LINE_DIFF_HEADER)
5807 break;
5810 return TRUE;
5813 static bool
5814 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5816 const char *apply_argv[SIZEOF_ARG] = {
5817 "git", "apply", "--whitespace=nowarn", NULL
5819 struct line *diff_hdr;
5820 struct io io;
5821 int argc = 3;
5823 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
5824 if (!diff_hdr)
5825 return FALSE;
5827 if (!revert)
5828 apply_argv[argc++] = "--cached";
5829 if (revert || stage_line_type == LINE_STAT_STAGED)
5830 apply_argv[argc++] = "-R";
5831 apply_argv[argc++] = "-";
5832 apply_argv[argc++] = NULL;
5833 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5834 return FALSE;
5836 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5837 !stage_diff_write(&io, chunk, view->line + view->lines))
5838 chunk = NULL;
5840 io_done(&io);
5841 io_run_bg(update_index_argv);
5843 return chunk ? TRUE : FALSE;
5846 static bool
5847 stage_update(struct view *view, struct line *line)
5849 struct line *chunk = NULL;
5851 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5852 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
5854 if (chunk) {
5855 if (!stage_apply_chunk(view, chunk, FALSE)) {
5856 report("Failed to apply chunk");
5857 return FALSE;
5860 } else if (!stage_status.status) {
5861 view = view->parent;
5863 for (line = view->line; line < view->line + view->lines; line++)
5864 if (line->type == stage_line_type)
5865 break;
5867 if (!status_update_files(view, line + 1)) {
5868 report("Failed to update files");
5869 return FALSE;
5872 } else if (!status_update_file(&stage_status, stage_line_type)) {
5873 report("Failed to update file");
5874 return FALSE;
5877 return TRUE;
5880 static bool
5881 stage_revert(struct view *view, struct line *line)
5883 struct line *chunk = NULL;
5885 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5886 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
5888 if (chunk) {
5889 if (!prompt_yesno("Are you sure you want to revert changes?"))
5890 return FALSE;
5892 if (!stage_apply_chunk(view, chunk, TRUE)) {
5893 report("Failed to revert chunk");
5894 return FALSE;
5896 return TRUE;
5898 } else {
5899 return status_revert(stage_status.status ? &stage_status : NULL,
5900 stage_line_type, FALSE);
5905 static void
5906 stage_next(struct view *view, struct line *line)
5908 int i;
5910 if (!stage_chunks) {
5911 for (line = view->line; line < view->line + view->lines; line++) {
5912 if (line->type != LINE_DIFF_CHUNK)
5913 continue;
5915 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5916 report("Allocation failure");
5917 return;
5920 stage_chunk[stage_chunks++] = line - view->line;
5924 for (i = 0; i < stage_chunks; i++) {
5925 if (stage_chunk[i] > view->lineno) {
5926 do_scroll_view(view, stage_chunk[i] - view->lineno);
5927 report("Chunk %d of %d", i + 1, stage_chunks);
5928 return;
5932 report("No next chunk found");
5935 static enum request
5936 stage_request(struct view *view, enum request request, struct line *line)
5938 switch (request) {
5939 case REQ_STATUS_UPDATE:
5940 if (!stage_update(view, line))
5941 return REQ_NONE;
5942 break;
5944 case REQ_STATUS_REVERT:
5945 if (!stage_revert(view, line))
5946 return REQ_NONE;
5947 break;
5949 case REQ_STAGE_NEXT:
5950 if (stage_line_type == LINE_STAT_UNTRACKED) {
5951 report("File is untracked; press %s to add",
5952 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5953 return REQ_NONE;
5955 stage_next(view, line);
5956 return REQ_NONE;
5958 case REQ_EDIT:
5959 if (!stage_status.new.name[0])
5960 return request;
5961 if (stage_status.status == 'D') {
5962 report("File has been deleted.");
5963 return REQ_NONE;
5966 open_editor(stage_status.new.name);
5967 break;
5969 case REQ_REFRESH:
5970 /* Reload everything ... */
5971 break;
5973 case REQ_VIEW_BLAME:
5974 if (stage_status.new.name[0]) {
5975 string_copy(opt_file, stage_status.new.name);
5976 opt_ref[0] = 0;
5978 return request;
5980 case REQ_ENTER:
5981 return diff_common_enter(view, request, line);
5983 case REQ_DIFF_CONTEXT_UP:
5984 case REQ_DIFF_CONTEXT_DOWN:
5985 if (!update_diff_context(request))
5986 return REQ_NONE;
5987 break;
5989 default:
5990 return request;
5993 refresh_view(view->parent);
5995 /* Check whether the staged entry still exists, and close the
5996 * stage view if it doesn't. */
5997 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
5998 status_restore(view->parent);
5999 return REQ_VIEW_CLOSE;
6002 refresh_view(view);
6004 return REQ_NONE;
6007 static bool
6008 stage_open(struct view *view, enum open_flags flags)
6010 static const char *no_head_diff_argv[] = {
6011 "git", "diff", "--no-color", "--patch-with-stat",
6012 opt_diff_context_arg,
6013 "--", "/dev/null", stage_status.new.name, NULL
6015 static const char *index_show_argv[] = {
6016 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6017 "--cached", opt_diff_context_arg, "HEAD", "--",
6018 stage_status.old.name, stage_status.new.name, NULL
6020 static const char *files_show_argv[] = {
6021 "git", "diff-files", "--root", "--patch-with-stat",
6022 "-C", "-M", opt_diff_context_arg, "--",
6023 stage_status.old.name, stage_status.new.name, NULL
6025 /* Diffs for unmerged entries are empty when passing the new
6026 * path, so leave out the new path. */
6027 static const char *files_unmerged_argv[] = {
6028 "git", "diff-files", "--root", "--patch-with-stat",
6029 "-C", "-M", opt_diff_context_arg, "--",
6030 stage_status.old.name, NULL
6032 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6033 const char **argv = NULL;
6034 const char *info;
6036 switch (stage_line_type) {
6037 case LINE_STAT_STAGED:
6038 if (is_initial_commit()) {
6039 argv = no_head_diff_argv;
6040 } else {
6041 argv = index_show_argv;
6043 if (stage_status.status)
6044 info = "Staged changes to %s";
6045 else
6046 info = "Staged changes";
6047 break;
6049 case LINE_STAT_UNSTAGED:
6050 if (stage_status.status != 'U')
6051 argv = files_show_argv;
6052 else
6053 argv = files_unmerged_argv;
6054 if (stage_status.status)
6055 info = "Unstaged changes to %s";
6056 else
6057 info = "Unstaged changes";
6058 break;
6060 case LINE_STAT_UNTRACKED:
6061 info = "Untracked file %s";
6062 argv = file_argv;
6063 break;
6065 case LINE_STAT_HEAD:
6066 default:
6067 die("line type %d not handled in switch", stage_line_type);
6070 string_format(view->ref, info, stage_status.new.name);
6071 view->vid[0] = 0;
6072 view->dir = opt_cdup;
6073 return argv_copy(&view->argv, argv)
6074 && begin_update(view, NULL, NULL, flags);
6077 static bool
6078 stage_read(struct view *view, char *data)
6080 static bool reading_diff_stat = FALSE;
6082 if (data && diff_common_read(view, data, &reading_diff_stat))
6083 return TRUE;
6085 return pager_read(view, data);
6088 static struct view_ops stage_ops = {
6089 "line",
6090 stage_open,
6091 stage_read,
6092 diff_common_draw,
6093 stage_request,
6094 pager_grep,
6095 pager_select,
6100 * Revision graph
6103 static const enum line_type graph_colors[] = {
6104 LINE_PALETTE_0,
6105 LINE_PALETTE_1,
6106 LINE_PALETTE_2,
6107 LINE_PALETTE_3,
6108 LINE_PALETTE_4,
6109 LINE_PALETTE_5,
6110 LINE_PALETTE_6,
6113 static enum line_type get_graph_color(struct graph_symbol *symbol)
6115 if (symbol->commit)
6116 return LINE_GRAPH_COMMIT;
6117 assert(symbol->color < ARRAY_SIZE(graph_colors));
6118 return graph_colors[symbol->color];
6121 static bool
6122 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6124 const char *chars = graph_symbol_to_utf8(symbol);
6126 return draw_text(view, color, chars + !!first);
6129 static bool
6130 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6132 const char *chars = graph_symbol_to_ascii(symbol);
6134 return draw_text(view, color, chars + !!first);
6137 static bool
6138 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6140 const chtype *chars = graph_symbol_to_chtype(symbol);
6142 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6145 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6147 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6149 static const draw_graph_fn fns[] = {
6150 draw_graph_ascii,
6151 draw_graph_chtype,
6152 draw_graph_utf8
6154 draw_graph_fn fn = fns[opt_line_graphics];
6155 int i;
6157 for (i = 0; i < canvas->size; i++) {
6158 struct graph_symbol *symbol = &canvas->symbols[i];
6159 enum line_type color = get_graph_color(symbol);
6161 if (fn(view, symbol, color, i == 0))
6162 return TRUE;
6165 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6169 * Main view backend
6172 struct commit {
6173 char id[SIZEOF_REV]; /* SHA1 ID. */
6174 char title[128]; /* First line of the commit message. */
6175 const char *author; /* Author of the commit. */
6176 struct time time; /* Date from the author ident. */
6177 struct ref_list *refs; /* Repository references. */
6178 struct graph_canvas graph; /* Ancestry chain graphics. */
6181 static bool
6182 main_open(struct view *view, enum open_flags flags)
6184 static const char *main_argv[] = {
6185 "git", "log", "--no-color", "--pretty=raw", "--parents",
6186 "--topo-order", "%(diffargs)", "%(revargs)",
6187 "--", "%(fileargs)", NULL
6190 return begin_update(view, NULL, main_argv, flags);
6193 static bool
6194 main_draw(struct view *view, struct line *line, unsigned int lineno)
6196 struct commit *commit = line->data;
6198 if (!commit->author)
6199 return FALSE;
6201 if (opt_line_number && draw_lineno(view, lineno))
6202 return TRUE;
6204 if (draw_date(view, &commit->time))
6205 return TRUE;
6207 if (draw_author(view, commit->author))
6208 return TRUE;
6210 if (opt_rev_graph && draw_graph(view, &commit->graph))
6211 return TRUE;
6213 if (draw_refs(view, commit->refs))
6214 return TRUE;
6216 draw_text(view, LINE_DEFAULT, commit->title);
6217 return TRUE;
6220 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6221 static bool
6222 main_read(struct view *view, char *line)
6224 static struct graph graph;
6225 enum line_type type;
6226 struct commit *commit;
6228 if (!line) {
6229 if (!view->lines && !view->prev)
6230 die("No revisions match the given arguments.");
6231 if (view->lines > 0) {
6232 commit = view->line[view->lines - 1].data;
6233 view->line[view->lines - 1].dirty = 1;
6234 if (!commit->author) {
6235 view->lines--;
6236 free(commit);
6240 done_graph(&graph);
6241 return TRUE;
6244 type = get_line_type(line);
6245 if (type == LINE_COMMIT) {
6246 bool is_boundary;
6248 commit = calloc(1, sizeof(struct commit));
6249 if (!commit)
6250 return FALSE;
6252 line += STRING_SIZE("commit ");
6253 is_boundary = *line == '-';
6254 if (is_boundary)
6255 line++;
6257 string_copy_rev(commit->id, line);
6258 commit->refs = get_ref_list(commit->id);
6259 add_line_data(view, commit, LINE_MAIN_COMMIT);
6260 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
6261 return TRUE;
6264 if (!view->lines)
6265 return TRUE;
6266 commit = view->line[view->lines - 1].data;
6268 switch (type) {
6269 case LINE_PARENT:
6270 if (!graph.has_parents)
6271 graph_add_parent(&graph, line + STRING_SIZE("parent "));
6272 break;
6274 case LINE_AUTHOR:
6275 parse_author_line(line + STRING_SIZE("author "),
6276 &commit->author, &commit->time);
6277 graph_render_parents(&graph);
6278 break;
6280 default:
6281 /* Fill in the commit title if it has not already been set. */
6282 if (commit->title[0])
6283 break;
6285 /* Require titles to start with a non-space character at the
6286 * offset used by git log. */
6287 if (strncmp(line, " ", 4))
6288 break;
6289 line += 4;
6290 /* Well, if the title starts with a whitespace character,
6291 * try to be forgiving. Otherwise we end up with no title. */
6292 while (isspace(*line))
6293 line++;
6294 if (*line == '\0')
6295 break;
6296 /* FIXME: More graceful handling of titles; append "..." to
6297 * shortened titles, etc. */
6299 string_expand(commit->title, sizeof(commit->title), line, 1);
6300 view->line[view->lines - 1].dirty = 1;
6303 return TRUE;
6306 static enum request
6307 main_request(struct view *view, enum request request, struct line *line)
6309 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6311 switch (request) {
6312 case REQ_ENTER:
6313 if (view_is_displayed(view) && display[0] != view)
6314 maximize_view(view, TRUE);
6315 open_view(view, REQ_VIEW_DIFF, flags);
6316 break;
6317 case REQ_REFRESH:
6318 load_refs();
6319 refresh_view(view);
6320 break;
6321 default:
6322 return request;
6325 return REQ_NONE;
6328 static bool
6329 grep_refs(struct ref_list *list, regex_t *regex)
6331 regmatch_t pmatch;
6332 size_t i;
6334 if (!opt_show_refs || !list)
6335 return FALSE;
6337 for (i = 0; i < list->size; i++) {
6338 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6339 return TRUE;
6342 return FALSE;
6345 static bool
6346 main_grep(struct view *view, struct line *line)
6348 struct commit *commit = line->data;
6349 const char *text[] = {
6350 commit->title,
6351 mkauthor(commit->author, opt_author_cols, opt_author),
6352 mkdate(&commit->time, opt_date),
6353 NULL
6356 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6359 static void
6360 main_select(struct view *view, struct line *line)
6362 struct commit *commit = line->data;
6364 string_copy_rev(view->ref, commit->id);
6365 string_copy_rev(ref_commit, view->ref);
6368 static struct view_ops main_ops = {
6369 "commit",
6370 main_open,
6371 main_read,
6372 main_draw,
6373 main_request,
6374 main_grep,
6375 main_select,
6380 * Status management
6383 /* Whether or not the curses interface has been initialized. */
6384 static bool cursed = FALSE;
6386 /* Terminal hacks and workarounds. */
6387 static bool use_scroll_redrawwin;
6388 static bool use_scroll_status_wclear;
6390 /* The status window is used for polling keystrokes. */
6391 static WINDOW *status_win;
6393 /* Reading from the prompt? */
6394 static bool input_mode = FALSE;
6396 static bool status_empty = FALSE;
6398 /* Update status and title window. */
6399 static void
6400 report(const char *msg, ...)
6402 struct view *view = display[current_view];
6404 if (input_mode)
6405 return;
6407 if (!view) {
6408 char buf[SIZEOF_STR];
6409 va_list args;
6411 va_start(args, msg);
6412 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6413 buf[sizeof(buf) - 1] = 0;
6414 buf[sizeof(buf) - 2] = '.';
6415 buf[sizeof(buf) - 3] = '.';
6416 buf[sizeof(buf) - 4] = '.';
6418 va_end(args);
6419 die("%s", buf);
6422 if (!status_empty || *msg) {
6423 va_list args;
6425 va_start(args, msg);
6427 wmove(status_win, 0, 0);
6428 if (view->has_scrolled && use_scroll_status_wclear)
6429 wclear(status_win);
6430 if (*msg) {
6431 vwprintw(status_win, msg, args);
6432 status_empty = FALSE;
6433 } else {
6434 status_empty = TRUE;
6436 wclrtoeol(status_win);
6437 wnoutrefresh(status_win);
6439 va_end(args);
6442 update_view_title(view);
6445 static void
6446 init_display(void)
6448 const char *term;
6449 int x, y;
6451 /* Initialize the curses library */
6452 if (isatty(STDIN_FILENO)) {
6453 cursed = !!initscr();
6454 opt_tty = stdin;
6455 } else {
6456 /* Leave stdin and stdout alone when acting as a pager. */
6457 opt_tty = fopen("/dev/tty", "r+");
6458 if (!opt_tty)
6459 die("Failed to open /dev/tty");
6460 cursed = !!newterm(NULL, opt_tty, opt_tty);
6463 if (!cursed)
6464 die("Failed to initialize curses");
6466 nonl(); /* Disable conversion and detect newlines from input. */
6467 cbreak(); /* Take input chars one at a time, no wait for \n */
6468 noecho(); /* Don't echo input */
6469 leaveok(stdscr, FALSE);
6471 if (has_colors())
6472 init_colors();
6474 getmaxyx(stdscr, y, x);
6475 status_win = newwin(1, x, y - 1, 0);
6476 if (!status_win)
6477 die("Failed to create status window");
6479 /* Enable keyboard mapping */
6480 keypad(status_win, TRUE);
6481 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6483 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6484 set_tabsize(opt_tab_size);
6485 #else
6486 TABSIZE = opt_tab_size;
6487 #endif
6489 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6490 if (term && !strcmp(term, "gnome-terminal")) {
6491 /* In the gnome-terminal-emulator, the message from
6492 * scrolling up one line when impossible followed by
6493 * scrolling down one line causes corruption of the
6494 * status line. This is fixed by calling wclear. */
6495 use_scroll_status_wclear = TRUE;
6496 use_scroll_redrawwin = FALSE;
6498 } else if (term && !strcmp(term, "xrvt-xpm")) {
6499 /* No problems with full optimizations in xrvt-(unicode)
6500 * and aterm. */
6501 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6503 } else {
6504 /* When scrolling in (u)xterm the last line in the
6505 * scrolling direction will update slowly. */
6506 use_scroll_redrawwin = TRUE;
6507 use_scroll_status_wclear = FALSE;
6511 static int
6512 get_input(int prompt_position)
6514 struct view *view;
6515 int i, key, cursor_y, cursor_x;
6517 if (prompt_position)
6518 input_mode = TRUE;
6520 while (TRUE) {
6521 bool loading = FALSE;
6523 foreach_view (view, i) {
6524 update_view(view);
6525 if (view_is_displayed(view) && view->has_scrolled &&
6526 use_scroll_redrawwin)
6527 redrawwin(view->win);
6528 view->has_scrolled = FALSE;
6529 if (view->pipe)
6530 loading = TRUE;
6533 /* Update the cursor position. */
6534 if (prompt_position) {
6535 getbegyx(status_win, cursor_y, cursor_x);
6536 cursor_x = prompt_position;
6537 } else {
6538 view = display[current_view];
6539 getbegyx(view->win, cursor_y, cursor_x);
6540 cursor_x = view->width - 1;
6541 cursor_y += view->lineno - view->offset;
6543 setsyx(cursor_y, cursor_x);
6545 /* Refresh, accept single keystroke of input */
6546 doupdate();
6547 nodelay(status_win, loading);
6548 key = wgetch(status_win);
6550 /* wgetch() with nodelay() enabled returns ERR when
6551 * there's no input. */
6552 if (key == ERR) {
6554 } else if (key == KEY_RESIZE) {
6555 int height, width;
6557 getmaxyx(stdscr, height, width);
6559 wresize(status_win, 1, width);
6560 mvwin(status_win, height - 1, 0);
6561 wnoutrefresh(status_win);
6562 resize_display();
6563 redraw_display(TRUE);
6565 } else {
6566 input_mode = FALSE;
6567 if (key == erasechar())
6568 key = KEY_BACKSPACE;
6569 return key;
6574 static char *
6575 prompt_input(const char *prompt, input_handler handler, void *data)
6577 enum input_status status = INPUT_OK;
6578 static char buf[SIZEOF_STR];
6579 size_t pos = 0;
6581 buf[pos] = 0;
6583 while (status == INPUT_OK || status == INPUT_SKIP) {
6584 int key;
6586 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6587 wclrtoeol(status_win);
6589 key = get_input(pos + 1);
6590 switch (key) {
6591 case KEY_RETURN:
6592 case KEY_ENTER:
6593 case '\n':
6594 status = pos ? INPUT_STOP : INPUT_CANCEL;
6595 break;
6597 case KEY_BACKSPACE:
6598 if (pos > 0)
6599 buf[--pos] = 0;
6600 else
6601 status = INPUT_CANCEL;
6602 break;
6604 case KEY_ESC:
6605 status = INPUT_CANCEL;
6606 break;
6608 default:
6609 if (pos >= sizeof(buf)) {
6610 report("Input string too long");
6611 return NULL;
6614 status = handler(data, buf, key);
6615 if (status == INPUT_OK)
6616 buf[pos++] = (char) key;
6620 /* Clear the status window */
6621 status_empty = FALSE;
6622 report("");
6624 if (status == INPUT_CANCEL)
6625 return NULL;
6627 buf[pos++] = 0;
6629 return buf;
6632 static enum input_status
6633 prompt_yesno_handler(void *data, char *buf, int c)
6635 if (c == 'y' || c == 'Y')
6636 return INPUT_STOP;
6637 if (c == 'n' || c == 'N')
6638 return INPUT_CANCEL;
6639 return INPUT_SKIP;
6642 static bool
6643 prompt_yesno(const char *prompt)
6645 char prompt2[SIZEOF_STR];
6647 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6648 return FALSE;
6650 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6653 static enum input_status
6654 read_prompt_handler(void *data, char *buf, int c)
6656 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6659 static char *
6660 read_prompt(const char *prompt)
6662 return prompt_input(prompt, read_prompt_handler, NULL);
6665 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6667 enum input_status status = INPUT_OK;
6668 int size = 0;
6670 while (items[size].text)
6671 size++;
6673 while (status == INPUT_OK) {
6674 const struct menu_item *item = &items[*selected];
6675 int key;
6676 int i;
6678 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6679 prompt, *selected + 1, size);
6680 if (item->hotkey)
6681 wprintw(status_win, "[%c] ", (char) item->hotkey);
6682 wprintw(status_win, "%s", item->text);
6683 wclrtoeol(status_win);
6685 key = get_input(COLS - 1);
6686 switch (key) {
6687 case KEY_RETURN:
6688 case KEY_ENTER:
6689 case '\n':
6690 status = INPUT_STOP;
6691 break;
6693 case KEY_LEFT:
6694 case KEY_UP:
6695 *selected = *selected - 1;
6696 if (*selected < 0)
6697 *selected = size - 1;
6698 break;
6700 case KEY_RIGHT:
6701 case KEY_DOWN:
6702 *selected = (*selected + 1) % size;
6703 break;
6705 case KEY_ESC:
6706 status = INPUT_CANCEL;
6707 break;
6709 default:
6710 for (i = 0; items[i].text; i++)
6711 if (items[i].hotkey == key) {
6712 *selected = i;
6713 status = INPUT_STOP;
6714 break;
6719 /* Clear the status window */
6720 status_empty = FALSE;
6721 report("");
6723 return status != INPUT_CANCEL;
6727 * Repository properties
6730 static struct ref **refs = NULL;
6731 static size_t refs_size = 0;
6732 static struct ref *refs_head = NULL;
6734 static struct ref_list **ref_lists = NULL;
6735 static size_t ref_lists_size = 0;
6737 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6738 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6739 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6741 static int
6742 compare_refs(const void *ref1_, const void *ref2_)
6744 const struct ref *ref1 = *(const struct ref **)ref1_;
6745 const struct ref *ref2 = *(const struct ref **)ref2_;
6747 if (ref1->tag != ref2->tag)
6748 return ref2->tag - ref1->tag;
6749 if (ref1->ltag != ref2->ltag)
6750 return ref2->ltag - ref2->ltag;
6751 if (ref1->head != ref2->head)
6752 return ref2->head - ref1->head;
6753 if (ref1->tracked != ref2->tracked)
6754 return ref2->tracked - ref1->tracked;
6755 if (ref1->replace != ref2->replace)
6756 return ref2->replace - ref1->replace;
6757 /* Order remotes last. */
6758 if (ref1->remote != ref2->remote)
6759 return ref1->remote - ref2->remote;
6760 return strcmp(ref1->name, ref2->name);
6763 static void
6764 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6766 size_t i;
6768 for (i = 0; i < refs_size; i++)
6769 if (!visitor(data, refs[i]))
6770 break;
6773 static struct ref *
6774 get_ref_head()
6776 return refs_head;
6779 static struct ref_list *
6780 get_ref_list(const char *id)
6782 struct ref_list *list;
6783 size_t i;
6785 for (i = 0; i < ref_lists_size; i++)
6786 if (!strcmp(id, ref_lists[i]->id))
6787 return ref_lists[i];
6789 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6790 return NULL;
6791 list = calloc(1, sizeof(*list));
6792 if (!list)
6793 return NULL;
6795 for (i = 0; i < refs_size; i++) {
6796 if (!strcmp(id, refs[i]->id) &&
6797 realloc_refs_list(&list->refs, list->size, 1))
6798 list->refs[list->size++] = refs[i];
6801 if (!list->refs) {
6802 free(list);
6803 return NULL;
6806 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6807 ref_lists[ref_lists_size++] = list;
6808 return list;
6811 static int
6812 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6814 struct ref *ref = NULL;
6815 bool tag = FALSE;
6816 bool ltag = FALSE;
6817 bool remote = FALSE;
6818 bool replace = FALSE;
6819 bool tracked = FALSE;
6820 bool head = FALSE;
6821 int from = 0, to = refs_size - 1;
6823 if (!prefixcmp(name, "refs/tags/")) {
6824 if (!suffixcmp(name, namelen, "^{}")) {
6825 namelen -= 3;
6826 name[namelen] = 0;
6827 } else {
6828 ltag = TRUE;
6831 tag = TRUE;
6832 namelen -= STRING_SIZE("refs/tags/");
6833 name += STRING_SIZE("refs/tags/");
6835 } else if (!prefixcmp(name, "refs/remotes/")) {
6836 remote = TRUE;
6837 namelen -= STRING_SIZE("refs/remotes/");
6838 name += STRING_SIZE("refs/remotes/");
6839 tracked = !strcmp(opt_remote, name);
6841 } else if (!prefixcmp(name, "refs/replace/")) {
6842 replace = TRUE;
6843 id = name + strlen("refs/replace/");
6844 idlen = namelen - strlen("refs/replace/");
6845 name = "replaced";
6846 namelen = strlen(name);
6848 } else if (!prefixcmp(name, "refs/heads/")) {
6849 namelen -= STRING_SIZE("refs/heads/");
6850 name += STRING_SIZE("refs/heads/");
6851 if (!strncmp(opt_head, name, namelen))
6852 return OK;
6854 } else if (!strcmp(name, "HEAD")) {
6855 head = TRUE;
6856 if (*opt_head) {
6857 namelen = strlen(opt_head);
6858 name = opt_head;
6862 /* If we are reloading or it's an annotated tag, replace the
6863 * previous SHA1 with the resolved commit id; relies on the fact
6864 * git-ls-remote lists the commit id of an annotated tag right
6865 * before the commit id it points to. */
6866 while ((from <= to) && !replace) {
6867 size_t pos = (to + from) / 2;
6868 int cmp = strcmp(name, refs[pos]->name);
6870 if (!cmp) {
6871 ref = refs[pos];
6872 break;
6875 if (cmp < 0)
6876 to = pos - 1;
6877 else
6878 from = pos + 1;
6881 if (!ref) {
6882 if (!realloc_refs(&refs, refs_size, 1))
6883 return ERR;
6884 ref = calloc(1, sizeof(*ref) + namelen);
6885 if (!ref)
6886 return ERR;
6887 memmove(refs + from + 1, refs + from,
6888 (refs_size - from) * sizeof(*refs));
6889 refs[from] = ref;
6890 strncpy(ref->name, name, namelen);
6891 refs_size++;
6894 ref->head = head;
6895 ref->tag = tag;
6896 ref->ltag = ltag;
6897 ref->remote = remote;
6898 ref->replace = replace;
6899 ref->tracked = tracked;
6900 string_copy_rev(ref->id, id);
6902 if (head)
6903 refs_head = ref;
6904 return OK;
6907 static int
6908 load_refs(void)
6910 const char *head_argv[] = {
6911 "git", "symbolic-ref", "HEAD", NULL
6913 static const char *ls_remote_argv[SIZEOF_ARG] = {
6914 "git", "ls-remote", opt_git_dir, NULL
6916 static bool init = FALSE;
6917 size_t i;
6919 if (!init) {
6920 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6921 die("TIG_LS_REMOTE contains too many arguments");
6922 init = TRUE;
6925 if (!*opt_git_dir)
6926 return OK;
6928 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6929 !prefixcmp(opt_head, "refs/heads/")) {
6930 char *offset = opt_head + STRING_SIZE("refs/heads/");
6932 memmove(opt_head, offset, strlen(offset) + 1);
6935 refs_head = NULL;
6936 for (i = 0; i < refs_size; i++)
6937 refs[i]->id[0] = 0;
6939 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6940 return ERR;
6942 /* Update the ref lists to reflect changes. */
6943 for (i = 0; i < ref_lists_size; i++) {
6944 struct ref_list *list = ref_lists[i];
6945 size_t old, new;
6947 for (old = new = 0; old < list->size; old++)
6948 if (!strcmp(list->id, list->refs[old]->id))
6949 list->refs[new++] = list->refs[old];
6950 list->size = new;
6953 qsort(refs, refs_size, sizeof(*refs), compare_refs);
6955 return OK;
6958 static void
6959 set_remote_branch(const char *name, const char *value, size_t valuelen)
6961 if (!strcmp(name, ".remote")) {
6962 string_ncopy(opt_remote, value, valuelen);
6964 } else if (*opt_remote && !strcmp(name, ".merge")) {
6965 size_t from = strlen(opt_remote);
6967 if (!prefixcmp(value, "refs/heads/"))
6968 value += STRING_SIZE("refs/heads/");
6970 if (!string_format_from(opt_remote, &from, "/%s", value))
6971 opt_remote[0] = 0;
6975 static void
6976 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6978 const char *argv[SIZEOF_ARG] = { name, "=" };
6979 int argc = 1 + (cmd == option_set_command);
6980 enum option_code error;
6982 if (!argv_from_string(argv, &argc, value))
6983 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6984 else
6985 error = cmd(argc, argv);
6987 if (error != OPT_OK)
6988 warn("Option 'tig.%s': %s", name, option_errors[error]);
6991 static bool
6992 set_environment_variable(const char *name, const char *value)
6994 size_t len = strlen(name) + 1 + strlen(value) + 1;
6995 char *env = malloc(len);
6997 if (env &&
6998 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6999 putenv(env) == 0)
7000 return TRUE;
7001 free(env);
7002 return FALSE;
7005 static void
7006 set_work_tree(const char *value)
7008 char cwd[SIZEOF_STR];
7010 if (!getcwd(cwd, sizeof(cwd)))
7011 die("Failed to get cwd path: %s", strerror(errno));
7012 if (chdir(opt_git_dir) < 0)
7013 die("Failed to chdir(%s): %s", strerror(errno));
7014 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7015 die("Failed to get git path: %s", strerror(errno));
7016 if (chdir(cwd) < 0)
7017 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7018 if (chdir(value) < 0)
7019 die("Failed to chdir(%s): %s", value, strerror(errno));
7020 if (!getcwd(cwd, sizeof(cwd)))
7021 die("Failed to get cwd path: %s", strerror(errno));
7022 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7023 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7024 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7025 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7026 opt_is_inside_work_tree = TRUE;
7029 static int
7030 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7032 if (!strcmp(name, "i18n.commitencoding"))
7033 string_ncopy(opt_encoding, value, valuelen);
7035 else if (!strcmp(name, "core.editor"))
7036 string_ncopy(opt_editor, value, valuelen);
7038 else if (!strcmp(name, "core.worktree"))
7039 set_work_tree(value);
7041 else if (!prefixcmp(name, "tig.color."))
7042 set_repo_config_option(name + 10, value, option_color_command);
7044 else if (!prefixcmp(name, "tig.bind."))
7045 set_repo_config_option(name + 9, value, option_bind_command);
7047 else if (!prefixcmp(name, "tig."))
7048 set_repo_config_option(name + 4, value, option_set_command);
7050 else if (*opt_head && !prefixcmp(name, "branch.") &&
7051 !strncmp(name + 7, opt_head, strlen(opt_head)))
7052 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7054 return OK;
7057 static int
7058 load_git_config(void)
7060 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7062 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7065 static int
7066 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7068 if (!opt_git_dir[0]) {
7069 string_ncopy(opt_git_dir, name, namelen);
7071 } else if (opt_is_inside_work_tree == -1) {
7072 /* This can be 3 different values depending on the
7073 * version of git being used. If git-rev-parse does not
7074 * understand --is-inside-work-tree it will simply echo
7075 * the option else either "true" or "false" is printed.
7076 * Default to true for the unknown case. */
7077 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7079 } else if (*name == '.') {
7080 string_ncopy(opt_cdup, name, namelen);
7082 } else {
7083 string_ncopy(opt_prefix, name, namelen);
7086 return OK;
7089 static int
7090 load_repo_info(void)
7092 const char *rev_parse_argv[] = {
7093 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7094 "--show-cdup", "--show-prefix", NULL
7097 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7102 * Main
7105 static const char usage[] =
7106 "tig " TIG_VERSION " (" __DATE__ ")\n"
7107 "\n"
7108 "Usage: tig [options] [revs] [--] [paths]\n"
7109 " or: tig show [options] [revs] [--] [paths]\n"
7110 " or: tig blame [options] [rev] [--] path\n"
7111 " or: tig status\n"
7112 " or: tig < [git command output]\n"
7113 "\n"
7114 "Options:\n"
7115 " -v, --version Show version and exit\n"
7116 " -h, --help Show help message and exit";
7118 static void __NORETURN
7119 quit(int sig)
7121 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7122 if (cursed)
7123 endwin();
7124 exit(0);
7127 static void __NORETURN
7128 die(const char *err, ...)
7130 va_list args;
7132 endwin();
7134 va_start(args, err);
7135 fputs("tig: ", stderr);
7136 vfprintf(stderr, err, args);
7137 fputs("\n", stderr);
7138 va_end(args);
7140 exit(1);
7143 static void
7144 warn(const char *msg, ...)
7146 va_list args;
7148 va_start(args, msg);
7149 fputs("tig warning: ", stderr);
7150 vfprintf(stderr, msg, args);
7151 fputs("\n", stderr);
7152 va_end(args);
7155 static int
7156 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7158 const char ***filter_args = data;
7160 return argv_append(filter_args, name) ? OK : ERR;
7163 static void
7164 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7166 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7167 const char **all_argv = NULL;
7169 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7170 !argv_append_array(&all_argv, argv) ||
7171 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7172 die("Failed to split arguments");
7173 argv_free(all_argv);
7174 free(all_argv);
7177 static void
7178 filter_options(const char *argv[])
7180 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7181 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7182 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7185 static enum request
7186 parse_options(int argc, const char *argv[])
7188 enum request request = REQ_VIEW_MAIN;
7189 const char *subcommand;
7190 bool seen_dashdash = FALSE;
7191 const char **filter_argv = NULL;
7192 int i;
7194 if (!isatty(STDIN_FILENO))
7195 return REQ_VIEW_PAGER;
7197 if (argc <= 1)
7198 return REQ_VIEW_MAIN;
7200 subcommand = argv[1];
7201 if (!strcmp(subcommand, "status")) {
7202 if (argc > 2)
7203 warn("ignoring arguments after `%s'", subcommand);
7204 return REQ_VIEW_STATUS;
7206 } else if (!strcmp(subcommand, "blame")) {
7207 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
7208 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
7209 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
7211 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7212 die("invalid number of options to blame\n\n%s", usage);
7214 if (opt_rev_argv) {
7215 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7218 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7219 return REQ_VIEW_BLAME;
7221 } else if (!strcmp(subcommand, "show")) {
7222 request = REQ_VIEW_DIFF;
7224 } else {
7225 subcommand = NULL;
7228 for (i = 1 + !!subcommand; i < argc; i++) {
7229 const char *opt = argv[i];
7231 if (seen_dashdash) {
7232 argv_append(&opt_file_argv, opt);
7233 continue;
7235 } else if (!strcmp(opt, "--")) {
7236 seen_dashdash = TRUE;
7237 continue;
7239 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7240 printf("tig version %s\n", TIG_VERSION);
7241 quit(0);
7243 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7244 printf("%s\n", usage);
7245 quit(0);
7247 } else if (!strcmp(opt, "--all")) {
7248 argv_append(&opt_rev_argv, opt);
7249 continue;
7252 if (!argv_append(&filter_argv, opt))
7253 die("command too long");
7256 if (filter_argv)
7257 filter_options(filter_argv);
7259 return request;
7263 main(int argc, const char *argv[])
7265 const char *codeset = "UTF-8";
7266 enum request request = parse_options(argc, argv);
7267 struct view *view;
7269 signal(SIGINT, quit);
7270 signal(SIGPIPE, SIG_IGN);
7272 if (setlocale(LC_ALL, "")) {
7273 codeset = nl_langinfo(CODESET);
7276 if (load_repo_info() == ERR)
7277 die("Failed to load repo info.");
7279 if (load_options() == ERR)
7280 die("Failed to load user config.");
7282 if (load_git_config() == ERR)
7283 die("Failed to load repo config.");
7285 /* Require a git repository unless when running in pager mode. */
7286 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7287 die("Not a git repository");
7289 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
7290 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
7291 if (opt_iconv_in == ICONV_NONE)
7292 die("Failed to initialize character set conversion");
7295 if (codeset && strcmp(codeset, "UTF-8")) {
7296 opt_iconv_out = iconv_open(codeset, "UTF-8");
7297 if (opt_iconv_out == ICONV_NONE)
7298 die("Failed to initialize character set conversion");
7301 if (load_refs() == ERR)
7302 die("Failed to load refs.");
7304 init_display();
7306 while (view_driver(display[current_view], request)) {
7307 int key = get_input(0);
7309 view = display[current_view];
7310 request = get_keybinding(view->keymap, key);
7312 /* Some low-level request handling. This keeps access to
7313 * status_win restricted. */
7314 switch (request) {
7315 case REQ_NONE:
7316 report("Unknown key, press %s for help",
7317 get_key(view->keymap, REQ_VIEW_HELP));
7318 break;
7319 case REQ_PROMPT:
7321 char *cmd = read_prompt(":");
7323 if (cmd && isdigit(*cmd)) {
7324 int lineno = view->lineno + 1;
7326 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7327 select_view_line(view, lineno - 1);
7328 report("");
7329 } else {
7330 report("Unable to parse '%s' as a line number", cmd);
7333 } else if (cmd) {
7334 struct view *next = VIEW(REQ_VIEW_PAGER);
7335 const char *argv[SIZEOF_ARG] = { "git" };
7336 int argc = 1;
7338 /* When running random commands, initially show the
7339 * command in the title. However, it maybe later be
7340 * overwritten if a commit line is selected. */
7341 string_ncopy(next->ref, cmd, strlen(cmd));
7343 if (!argv_from_string(argv, &argc, cmd)) {
7344 report("Too many arguments");
7345 } else if (!format_argv(&next->argv, argv, FALSE)) {
7346 report("Argument formatting failed");
7347 } else {
7348 next->dir = NULL;
7349 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7353 request = REQ_NONE;
7354 break;
7356 case REQ_SEARCH:
7357 case REQ_SEARCH_BACK:
7359 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7360 char *search = read_prompt(prompt);
7362 if (search)
7363 string_ncopy(opt_search, search, strlen(search));
7364 else if (*opt_search)
7365 request = request == REQ_SEARCH ?
7366 REQ_FIND_NEXT :
7367 REQ_FIND_PREV;
7368 else
7369 request = REQ_NONE;
7370 break;
7372 default:
7373 break;
7377 quit(0);
7379 return 0;