Code

Unify enum map declarations through a common utility
[tig.git] / tig.c
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2  *
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.
7  *
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.
12  */
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 tracked:1; /* Is it the remote for the current HEAD? */
30         char name[1];           /* Ref name; tag or head names are shortened. */
31 };
33 struct ref_list {
34         char id[SIZEOF_REV];    /* Commit SHA1 ID */
35         size_t size;            /* Number of refs. */
36         struct ref **refs;      /* References for this ID. */
37 };
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45         INPUT_OK,
46         INPUT_SKIP,
47         INPUT_STOP,
48         INPUT_CANCEL
49 };
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57         int hotkey;
58         const char *text;
59         void *data;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 #define GRAPHIC_ENUM(_) \
65         _(GRAPHIC, ASCII), \
66         _(GRAPHIC, DEFAULT), \
67         _(GRAPHIC, UTF_8)
69 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
71 #define DATE_ENUM(_) \
72         _(DATE, NO), \
73         _(DATE, DEFAULT), \
74         _(DATE, LOCAL), \
75         _(DATE, RELATIVE), \
76         _(DATE, SHORT)
78 DEFINE_ENUM(date, DATE_ENUM);
80 struct time {
81         time_t sec;
82         int tz;
83 };
85 static inline int timecmp(const struct time *t1, const struct time *t2)
86 {
87         return t1->sec - t2->sec;
88 }
90 static const char *
91 mkdate(const struct time *time, enum date date)
92 {
93         static char buf[DATE_COLS + 1];
94         static const struct enum_map reldate[] = {
95                 { "second", 1,                  60 * 2 },
96                 { "minute", 60,                 60 * 60 * 2 },
97                 { "hour",   60 * 60,            60 * 60 * 24 * 2 },
98                 { "day",    60 * 60 * 24,       60 * 60 * 24 * 7 * 2 },
99                 { "week",   60 * 60 * 24 * 7,   60 * 60 * 24 * 7 * 5 },
100                 { "month",  60 * 60 * 24 * 30,  60 * 60 * 24 * 30 * 12 },
101         };
102         struct tm tm;
104         if (!date || !time || !time->sec)
105                 return "";
107         if (date == DATE_RELATIVE) {
108                 struct timeval now;
109                 time_t date = time->sec + time->tz;
110                 time_t seconds;
111                 int i;
113                 gettimeofday(&now, NULL);
114                 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
115                 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
116                         if (seconds >= reldate[i].value)
117                                 continue;
119                         seconds /= reldate[i].namelen;
120                         if (!string_format(buf, "%ld %s%s %s",
121                                            seconds, reldate[i].name,
122                                            seconds > 1 ? "s" : "",
123                                            now.tv_sec >= date ? "ago" : "ahead"))
124                                 break;
125                         return buf;
126                 }
127         }
129         if (date == DATE_LOCAL) {
130                 time_t date = time->sec + time->tz;
131                 localtime_r(&date, &tm);
132         }
133         else {
134                 gmtime_r(&time->sec, &tm);
135         }
136         return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
140 #define AUTHOR_ENUM(_) \
141         _(AUTHOR, NO), \
142         _(AUTHOR, FULL), \
143         _(AUTHOR, ABBREVIATED)
145 DEFINE_ENUM(author, AUTHOR_ENUM);
147 static const char *
148 get_author_initials(const char *author)
150         static char initials[AUTHOR_COLS * 6 + 1];
151         size_t pos = 0;
152         const char *end = strchr(author, '\0');
154 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
156         memset(initials, 0, sizeof(initials));
157         while (author < end) {
158                 unsigned char bytes;
159                 size_t i;
161                 while (is_initial_sep(*author))
162                         author++;
164                 bytes = utf8_char_length(author, end);
165                 if (bytes < sizeof(initials) - 1 - pos) {
166                         while (bytes--) {
167                                 initials[pos++] = *author++;
168                         }
169                 }
171                 for (i = pos; author < end && !is_initial_sep(*author); author++) {
172                         if (i < sizeof(initials) - 1)
173                                 initials[i++] = *author;
174                 }
176                 initials[i++] = 0;
177         }
179         return initials;
182 #define author_trim(cols) (cols == 0 || cols > 5)
184 static const char *
185 mkauthor(const char *text, int cols, enum author author)
187         bool trim = author_trim(cols);
188         bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
190         if (!author)
191                 return "";
192         if (abbreviate && text)
193                 return get_author_initials(text);
194         return text;
197 static const char *
198 mkmode(mode_t mode)
200         if (S_ISDIR(mode))
201                 return "drwxr-xr-x";
202         else if (S_ISLNK(mode))
203                 return "lrwxrwxrwx";
204         else if (S_ISGITLINK(mode))
205                 return "m---------";
206         else if (S_ISREG(mode) && mode & S_IXUSR)
207                 return "-rwxr-xr-x";
208         else if (S_ISREG(mode))
209                 return "-rw-r--r--";
210         else
211                 return "----------";
215 /*
216  * User requests
217  */
219 #define REQ_INFO \
220         /* XXX: Keep the view request first and in sync with views[]. */ \
221         REQ_GROUP("View switching") \
222         REQ_(VIEW_MAIN,         "Show main view"), \
223         REQ_(VIEW_DIFF,         "Show diff view"), \
224         REQ_(VIEW_LOG,          "Show log view"), \
225         REQ_(VIEW_TREE,         "Show tree view"), \
226         REQ_(VIEW_BLOB,         "Show blob view"), \
227         REQ_(VIEW_BLAME,        "Show blame view"), \
228         REQ_(VIEW_BRANCH,       "Show branch view"), \
229         REQ_(VIEW_HELP,         "Show help page"), \
230         REQ_(VIEW_PAGER,        "Show pager view"), \
231         REQ_(VIEW_STATUS,       "Show status view"), \
232         REQ_(VIEW_STAGE,        "Show stage view"), \
233         \
234         REQ_GROUP("View manipulation") \
235         REQ_(ENTER,             "Enter current line and scroll"), \
236         REQ_(NEXT,              "Move to next"), \
237         REQ_(PREVIOUS,          "Move to previous"), \
238         REQ_(PARENT,            "Move to parent"), \
239         REQ_(VIEW_NEXT,         "Move focus to next view"), \
240         REQ_(REFRESH,           "Reload and refresh"), \
241         REQ_(MAXIMIZE,          "Maximize the current view"), \
242         REQ_(VIEW_CLOSE,        "Close the current view"), \
243         REQ_(QUIT,              "Close all views and quit"), \
244         \
245         REQ_GROUP("View specific requests") \
246         REQ_(STATUS_UPDATE,     "Update file status"), \
247         REQ_(STATUS_REVERT,     "Revert file changes"), \
248         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
249         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
250         \
251         REQ_GROUP("Cursor navigation") \
252         REQ_(MOVE_UP,           "Move cursor one line up"), \
253         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
254         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
255         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
256         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
257         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
258         \
259         REQ_GROUP("Scrolling") \
260         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
261         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
262         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
263         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
264         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
265         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
266         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
267         \
268         REQ_GROUP("Searching") \
269         REQ_(SEARCH,            "Search the view"), \
270         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
271         REQ_(FIND_NEXT,         "Find next search match"), \
272         REQ_(FIND_PREV,         "Find previous search match"), \
273         \
274         REQ_GROUP("Option manipulation") \
275         REQ_(OPTIONS,           "Open option menu"), \
276         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
277         REQ_(TOGGLE_DATE,       "Toggle date display"), \
278         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
279         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
280         REQ_(TOGGLE_GRAPHIC,    "Toggle (line) graphics mode"), \
281         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
282         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
283         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
284         \
285         REQ_GROUP("Misc") \
286         REQ_(PROMPT,            "Bring up the prompt"), \
287         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
288         REQ_(SHOW_VERSION,      "Show version information"), \
289         REQ_(STOP_LOADING,      "Stop all loading views"), \
290         REQ_(EDIT,              "Open in editor"), \
291         REQ_(NONE,              "Do nothing")
294 /* User action requests. */
295 enum request {
296 #define REQ_GROUP(help)
297 #define REQ_(req, help) REQ_##req
299         /* Offset all requests to avoid conflicts with ncurses getch values. */
300         REQ_UNKNOWN = KEY_MAX + 1,
301         REQ_OFFSET,
302         REQ_INFO
304 #undef  REQ_GROUP
305 #undef  REQ_
306 };
308 struct request_info {
309         enum request request;
310         const char *name;
311         int namelen;
312         const char *help;
313 };
315 static const struct request_info req_info[] = {
316 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
317 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
318         REQ_INFO
319 #undef  REQ_GROUP
320 #undef  REQ_
321 };
323 static enum request
324 get_request(const char *name)
326         int namelen = strlen(name);
327         int i;
329         for (i = 0; i < ARRAY_SIZE(req_info); i++)
330                 if (enum_equals(req_info[i], name, namelen))
331                         return req_info[i].request;
333         return REQ_UNKNOWN;
337 /*
338  * Options
339  */
341 /* Option and state variables. */
342 static enum graphic opt_line_graphics   = GRAPHIC_DEFAULT;
343 static enum date opt_date               = DATE_DEFAULT;
344 static enum author opt_author           = AUTHOR_FULL;
345 static bool opt_rev_graph               = TRUE;
346 static bool opt_line_number             = FALSE;
347 static bool opt_show_refs               = TRUE;
348 static bool opt_untracked_dirs_content  = TRUE;
349 static int opt_num_interval             = 5;
350 static double opt_hscroll               = 0.50;
351 static double opt_scale_split_view      = 2.0 / 3.0;
352 static int opt_tab_size                 = 8;
353 static int opt_author_cols              = AUTHOR_COLS;
354 static char opt_path[SIZEOF_STR]        = "";
355 static char opt_file[SIZEOF_STR]        = "";
356 static char opt_ref[SIZEOF_REF]         = "";
357 static char opt_head[SIZEOF_REF]        = "";
358 static char opt_remote[SIZEOF_REF]      = "";
359 static char opt_encoding[20]            = "UTF-8";
360 static iconv_t opt_iconv_in             = ICONV_NONE;
361 static iconv_t opt_iconv_out            = ICONV_NONE;
362 static char opt_search[SIZEOF_STR]      = "";
363 static char opt_cdup[SIZEOF_STR]        = "";
364 static char opt_prefix[SIZEOF_STR]      = "";
365 static char opt_git_dir[SIZEOF_STR]     = "";
366 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
367 static char opt_editor[SIZEOF_STR]      = "";
368 static FILE *opt_tty                    = NULL;
369 static const char **opt_diff_argv       = NULL;
370 static const char **opt_rev_argv        = NULL;
371 static const char **opt_file_argv       = NULL;
372 static const char **opt_blame_argv      = NULL;
374 #define is_initial_commit()     (!get_ref_head())
375 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
378 /*
379  * Line-oriented content detection.
380  */
382 #define LINE_INFO \
383 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
384 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
385 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
386 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
387 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
388 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
389 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
390 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
391 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
392 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
393 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
394 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
395 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
396 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
397 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
398 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
399 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
400 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
401 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
402 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
403 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
404 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
405 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
406 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
407 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
408 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
409 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
410 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
411 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
412 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
413 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
414 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
415 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
416 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
417 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
418 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
419 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
420 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
421 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
422 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
423 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
424 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
425 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
426 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
427 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
428 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
429 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
430 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
431 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
432 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
433 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
434 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
435 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
436 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
437 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
438 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
439 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
440 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
441 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
442 LINE(GRAPH_LINE_0, "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
443 LINE(GRAPH_LINE_1, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
444 LINE(GRAPH_LINE_2, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
445 LINE(GRAPH_LINE_3, "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
446 LINE(GRAPH_LINE_4, "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
447 LINE(GRAPH_LINE_5, "",                  COLOR_WHITE,    COLOR_DEFAULT,  0), \
448 LINE(GRAPH_LINE_6, "",                  COLOR_RED,      COLOR_DEFAULT,  0), \
449 LINE(GRAPH_COMMIT, "",                  COLOR_BLUE,     COLOR_DEFAULT,  0)
451 enum line_type {
452 #define LINE(type, line, fg, bg, attr) \
453         LINE_##type
454         LINE_INFO,
455         LINE_NONE
456 #undef  LINE
457 };
459 struct line_info {
460         const char *name;       /* Option name. */
461         int namelen;            /* Size of option name. */
462         const char *line;       /* The start of line to match. */
463         int linelen;            /* Size of string to match. */
464         int fg, bg, attr;       /* Color and text attributes for the lines. */
465 };
467 static struct line_info line_info[] = {
468 #define LINE(type, line, fg, bg, attr) \
469         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
470         LINE_INFO
471 #undef  LINE
472 };
474 static enum line_type
475 get_line_type(const char *line)
477         int linelen = strlen(line);
478         enum line_type type;
480         for (type = 0; type < ARRAY_SIZE(line_info); type++)
481                 /* Case insensitive search matches Signed-off-by lines better. */
482                 if (linelen >= line_info[type].linelen &&
483                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
484                         return type;
486         return LINE_DEFAULT;
489 static inline int
490 get_line_attr(enum line_type type)
492         assert(type < ARRAY_SIZE(line_info));
493         return COLOR_PAIR(type) | line_info[type].attr;
496 static struct line_info *
497 get_line_info(const char *name)
499         size_t namelen = strlen(name);
500         enum line_type type;
502         for (type = 0; type < ARRAY_SIZE(line_info); type++)
503                 if (enum_equals(line_info[type], name, namelen))
504                         return &line_info[type];
506         return NULL;
509 static void
510 init_colors(void)
512         int default_bg = line_info[LINE_DEFAULT].bg;
513         int default_fg = line_info[LINE_DEFAULT].fg;
514         enum line_type type;
516         start_color();
518         if (assume_default_colors(default_fg, default_bg) == ERR) {
519                 default_bg = COLOR_BLACK;
520                 default_fg = COLOR_WHITE;
521         }
523         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
524                 struct line_info *info = &line_info[type];
525                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
526                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
528                 init_pair(type, fg, bg);
529         }
532 struct line {
533         enum line_type type;
535         /* State flags */
536         unsigned int selected:1;
537         unsigned int dirty:1;
538         unsigned int cleareol:1;
539         unsigned int other:16;
541         void *data;             /* User data */
542 };
545 /*
546  * Keys
547  */
549 struct keybinding {
550         int alias;
551         enum request request;
552 };
554 static struct keybinding default_keybindings[] = {
555         /* View switching */
556         { 'm',          REQ_VIEW_MAIN },
557         { 'd',          REQ_VIEW_DIFF },
558         { 'l',          REQ_VIEW_LOG },
559         { 't',          REQ_VIEW_TREE },
560         { 'f',          REQ_VIEW_BLOB },
561         { 'B',          REQ_VIEW_BLAME },
562         { 'H',          REQ_VIEW_BRANCH },
563         { 'p',          REQ_VIEW_PAGER },
564         { 'h',          REQ_VIEW_HELP },
565         { 'S',          REQ_VIEW_STATUS },
566         { 'c',          REQ_VIEW_STAGE },
568         /* View manipulation */
569         { 'q',          REQ_VIEW_CLOSE },
570         { KEY_TAB,      REQ_VIEW_NEXT },
571         { KEY_RETURN,   REQ_ENTER },
572         { KEY_UP,       REQ_PREVIOUS },
573         { KEY_CTL('P'), REQ_PREVIOUS },
574         { KEY_DOWN,     REQ_NEXT },
575         { KEY_CTL('N'), REQ_NEXT },
576         { 'R',          REQ_REFRESH },
577         { KEY_F(5),     REQ_REFRESH },
578         { 'O',          REQ_MAXIMIZE },
580         /* Cursor navigation */
581         { 'k',          REQ_MOVE_UP },
582         { 'j',          REQ_MOVE_DOWN },
583         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
584         { KEY_END,      REQ_MOVE_LAST_LINE },
585         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
586         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
587         { ' ',          REQ_MOVE_PAGE_DOWN },
588         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
589         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
590         { 'b',          REQ_MOVE_PAGE_UP },
591         { '-',          REQ_MOVE_PAGE_UP },
593         /* Scrolling */
594         { '|',          REQ_SCROLL_FIRST_COL },
595         { KEY_LEFT,     REQ_SCROLL_LEFT },
596         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
597         { KEY_IC,       REQ_SCROLL_LINE_UP },
598         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
599         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
600         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
601         { 'w',          REQ_SCROLL_PAGE_UP },
602         { 's',          REQ_SCROLL_PAGE_DOWN },
604         /* Searching */
605         { '/',          REQ_SEARCH },
606         { '?',          REQ_SEARCH_BACK },
607         { 'n',          REQ_FIND_NEXT },
608         { 'N',          REQ_FIND_PREV },
610         /* Misc */
611         { 'Q',          REQ_QUIT },
612         { 'z',          REQ_STOP_LOADING },
613         { 'v',          REQ_SHOW_VERSION },
614         { 'r',          REQ_SCREEN_REDRAW },
615         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
616         { 'o',          REQ_OPTIONS },
617         { '.',          REQ_TOGGLE_LINENO },
618         { 'D',          REQ_TOGGLE_DATE },
619         { 'A',          REQ_TOGGLE_AUTHOR },
620         { 'g',          REQ_TOGGLE_REV_GRAPH },
621         { '~',          REQ_TOGGLE_GRAPHIC },
622         { 'F',          REQ_TOGGLE_REFS },
623         { 'I',          REQ_TOGGLE_SORT_ORDER },
624         { 'i',          REQ_TOGGLE_SORT_FIELD },
625         { ':',          REQ_PROMPT },
626         { 'u',          REQ_STATUS_UPDATE },
627         { '!',          REQ_STATUS_REVERT },
628         { 'M',          REQ_STATUS_MERGE },
629         { '@',          REQ_STAGE_NEXT },
630         { ',',          REQ_PARENT },
631         { 'e',          REQ_EDIT },
632 };
634 #define KEYMAP_ENUM(_) \
635         _(KEYMAP, GENERIC), \
636         _(KEYMAP, MAIN), \
637         _(KEYMAP, DIFF), \
638         _(KEYMAP, LOG), \
639         _(KEYMAP, TREE), \
640         _(KEYMAP, BLOB), \
641         _(KEYMAP, BLAME), \
642         _(KEYMAP, BRANCH), \
643         _(KEYMAP, PAGER), \
644         _(KEYMAP, HELP), \
645         _(KEYMAP, STATUS), \
646         _(KEYMAP, STAGE)
648 DEFINE_ENUM(keymap, KEYMAP_ENUM);
650 #define set_keymap(map, name) map_enum(map, keymap_map, name)
652 struct keybinding_table {
653         struct keybinding *data;
654         size_t size;
655 };
657 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
659 static void
660 add_keybinding(enum keymap keymap, enum request request, int key)
662         struct keybinding_table *table = &keybindings[keymap];
663         size_t i;
665         for (i = 0; i < keybindings[keymap].size; i++) {
666                 if (keybindings[keymap].data[i].alias == key) {
667                         keybindings[keymap].data[i].request = request;
668                         return;
669                 }
670         }
672         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
673         if (!table->data)
674                 die("Failed to allocate keybinding");
675         table->data[table->size].alias = key;
676         table->data[table->size++].request = request;
678         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
679                 int i;
681                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
682                         if (default_keybindings[i].alias == key)
683                                 default_keybindings[i].request = REQ_NONE;
684         }
687 /* Looks for a key binding first in the given map, then in the generic map, and
688  * lastly in the default keybindings. */
689 static enum request
690 get_keybinding(enum keymap keymap, int key)
692         size_t i;
694         for (i = 0; i < keybindings[keymap].size; i++)
695                 if (keybindings[keymap].data[i].alias == key)
696                         return keybindings[keymap].data[i].request;
698         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
699                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
700                         return keybindings[KEYMAP_GENERIC].data[i].request;
702         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
703                 if (default_keybindings[i].alias == key)
704                         return default_keybindings[i].request;
706         return (enum request) key;
710 struct key {
711         const char *name;
712         int value;
713 };
715 static const struct key key_table[] = {
716         { "Enter",      KEY_RETURN },
717         { "Space",      ' ' },
718         { "Backspace",  KEY_BACKSPACE },
719         { "Tab",        KEY_TAB },
720         { "Escape",     KEY_ESC },
721         { "Left",       KEY_LEFT },
722         { "Right",      KEY_RIGHT },
723         { "Up",         KEY_UP },
724         { "Down",       KEY_DOWN },
725         { "Insert",     KEY_IC },
726         { "Delete",     KEY_DC },
727         { "Hash",       '#' },
728         { "Home",       KEY_HOME },
729         { "End",        KEY_END },
730         { "PageUp",     KEY_PPAGE },
731         { "PageDown",   KEY_NPAGE },
732         { "F1",         KEY_F(1) },
733         { "F2",         KEY_F(2) },
734         { "F3",         KEY_F(3) },
735         { "F4",         KEY_F(4) },
736         { "F5",         KEY_F(5) },
737         { "F6",         KEY_F(6) },
738         { "F7",         KEY_F(7) },
739         { "F8",         KEY_F(8) },
740         { "F9",         KEY_F(9) },
741         { "F10",        KEY_F(10) },
742         { "F11",        KEY_F(11) },
743         { "F12",        KEY_F(12) },
744 };
746 static int
747 get_key_value(const char *name)
749         int i;
751         for (i = 0; i < ARRAY_SIZE(key_table); i++)
752                 if (!strcasecmp(key_table[i].name, name))
753                         return key_table[i].value;
755         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
756                 return (int)name[1] & 0x1f;
757         if (strlen(name) == 1 && isprint(*name))
758                 return (int) *name;
759         return ERR;
762 static const char *
763 get_key_name(int key_value)
765         static char key_char[] = "'X'\0";
766         const char *seq = NULL;
767         int key;
769         for (key = 0; key < ARRAY_SIZE(key_table); key++)
770                 if (key_table[key].value == key_value)
771                         seq = key_table[key].name;
773         if (seq == NULL && key_value < 0x7f) {
774                 char *s = key_char + 1;
776                 if (key_value >= 0x20) {
777                         *s++ = key_value;
778                 } else {
779                         *s++ = '^';
780                         *s++ = 0x40 | (key_value & 0x1f);
781                 }
782                 *s++ = '\'';
783                 *s++ = '\0';
784                 seq = key_char;
785         }
787         return seq ? seq : "(no key)";
790 static bool
791 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
793         const char *sep = *pos > 0 ? ", " : "";
794         const char *keyname = get_key_name(keybinding->alias);
796         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
799 static bool
800 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
801                            enum keymap keymap, bool all)
803         int i;
805         for (i = 0; i < keybindings[keymap].size; i++) {
806                 if (keybindings[keymap].data[i].request == request) {
807                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
808                                 return FALSE;
809                         if (!all)
810                                 break;
811                 }
812         }
814         return TRUE;
817 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
819 static const char *
820 get_keys(enum keymap keymap, enum request request, bool all)
822         static char buf[BUFSIZ];
823         size_t pos = 0;
824         int i;
826         buf[pos] = 0;
828         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
829                 return "Too many keybindings!";
830         if (pos > 0 && !all)
831                 return buf;
833         if (keymap != KEYMAP_GENERIC) {
834                 /* Only the generic keymap includes the default keybindings when
835                  * listing all keys. */
836                 if (all)
837                         return buf;
839                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
840                         return "Too many keybindings!";
841                 if (pos)
842                         return buf;
843         }
845         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
846                 if (default_keybindings[i].request == request) {
847                         if (!append_key(buf, &pos, &default_keybindings[i]))
848                                 return "Too many keybindings!";
849                         if (!all)
850                                 return buf;
851                 }
852         }
854         return buf;
857 struct run_request {
858         enum keymap keymap;
859         int key;
860         const char **argv;
861 };
863 static struct run_request *run_request;
864 static size_t run_requests;
866 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
868 static enum request
869 add_run_request(enum keymap keymap, int key, const char **argv)
871         struct run_request *req;
873         if (!realloc_run_requests(&run_request, run_requests, 1))
874                 return REQ_NONE;
876         req = &run_request[run_requests];
877         req->keymap = keymap;
878         req->key = key;
879         req->argv = NULL;
881         if (!argv_copy(&req->argv, argv))
882                 return REQ_NONE;
884         return REQ_NONE + ++run_requests;
887 static struct run_request *
888 get_run_request(enum request request)
890         if (request <= REQ_NONE)
891                 return NULL;
892         return &run_request[request - REQ_NONE - 1];
895 static void
896 add_builtin_run_requests(void)
898         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
899         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
900         const char *commit[] = { "git", "commit", NULL };
901         const char *gc[] = { "git", "gc", NULL };
902         struct run_request reqs[] = {
903                 { KEYMAP_MAIN,    'C', cherry_pick },
904                 { KEYMAP_STATUS,  'C', commit },
905                 { KEYMAP_BRANCH,  'C', checkout },
906                 { KEYMAP_GENERIC, 'G', gc },
907         };
908         int i;
910         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
911                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
913                 if (req != reqs[i].key)
914                         continue;
915                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
916                 if (req != REQ_NONE)
917                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
918         }
921 /*
922  * User config file handling.
923  */
925 #define OPT_ERR_INFO \
926         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
927         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
928         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
929         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
930         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
931         OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
932         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
933         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
934         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
935         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
936         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
937         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
938         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
939         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
940         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
941         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
942         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
944 enum option_code {
945 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
946         OPT_ERR_INFO
947 #undef  OPT_ERR_
948         OPT_OK
949 };
951 static const char *option_errors[] = {
952 #define OPT_ERR_(name, msg) msg
953         OPT_ERR_INFO
954 #undef  OPT_ERR_
955 };
957 static const struct enum_map color_map[] = {
958 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
959         COLOR_MAP(DEFAULT),
960         COLOR_MAP(BLACK),
961         COLOR_MAP(BLUE),
962         COLOR_MAP(CYAN),
963         COLOR_MAP(GREEN),
964         COLOR_MAP(MAGENTA),
965         COLOR_MAP(RED),
966         COLOR_MAP(WHITE),
967         COLOR_MAP(YELLOW),
968 };
970 static const struct enum_map attr_map[] = {
971 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
972         ATTR_MAP(NORMAL),
973         ATTR_MAP(BLINK),
974         ATTR_MAP(BOLD),
975         ATTR_MAP(DIM),
976         ATTR_MAP(REVERSE),
977         ATTR_MAP(STANDOUT),
978         ATTR_MAP(UNDERLINE),
979 };
981 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
983 static enum option_code
984 parse_step(double *opt, const char *arg)
986         *opt = atoi(arg);
987         if (!strchr(arg, '%'))
988                 return OPT_OK;
990         /* "Shift down" so 100% and 1 does not conflict. */
991         *opt = (*opt - 1) / 100;
992         if (*opt >= 1.0) {
993                 *opt = 0.99;
994                 return OPT_ERR_INVALID_STEP_VALUE;
995         }
996         if (*opt < 0.0) {
997                 *opt = 1;
998                 return OPT_ERR_INVALID_STEP_VALUE;
999         }
1000         return OPT_OK;
1003 static enum option_code
1004 parse_int(int *opt, const char *arg, int min, int max)
1006         int value = atoi(arg);
1008         if (min <= value && value <= max) {
1009                 *opt = value;
1010                 return OPT_OK;
1011         }
1013         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1016 static bool
1017 set_color(int *color, const char *name)
1019         if (map_enum(color, color_map, name))
1020                 return TRUE;
1021         if (!prefixcmp(name, "color"))
1022                 return parse_int(color, name + 5, 0, 255) == OK;
1023         return FALSE;
1026 /* Wants: object fgcolor bgcolor [attribute] */
1027 static enum option_code
1028 option_color_command(int argc, const char *argv[])
1030         struct line_info *info;
1032         if (argc < 3)
1033                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1035         info = get_line_info(argv[0]);
1036         if (!info) {
1037                 static const struct enum_map obsolete[] = {
1038                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1039                         ENUM_MAP("main-date",   LINE_DATE),
1040                         ENUM_MAP("main-author", LINE_AUTHOR),
1041                 };
1042                 int index;
1044                 if (!map_enum(&index, obsolete, argv[0]))
1045                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1046                 info = &line_info[index];
1047         }
1049         if (!set_color(&info->fg, argv[1]) ||
1050             !set_color(&info->bg, argv[2]))
1051                 return OPT_ERR_UNKNOWN_COLOR;
1053         info->attr = 0;
1054         while (argc-- > 3) {
1055                 int attr;
1057                 if (!set_attribute(&attr, argv[argc]))
1058                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1059                 info->attr |= attr;
1060         }
1062         return OPT_OK;
1065 static enum option_code
1066 parse_bool(bool *opt, const char *arg)
1068         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1069                 ? TRUE : FALSE;
1070         return OPT_OK;
1073 static enum option_code
1074 parse_enum_do(unsigned int *opt, const char *arg,
1075               const struct enum_map *map, size_t map_size)
1077         bool is_true;
1079         assert(map_size > 1);
1081         if (map_enum_do(map, map_size, (int *) opt, arg))
1082                 return OPT_OK;
1084         parse_bool(&is_true, arg);
1085         *opt = is_true ? map[1].value : map[0].value;
1086         return OPT_OK;
1089 #define parse_enum(opt, arg, map) \
1090         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1092 static enum option_code
1093 parse_string(char *opt, const char *arg, size_t optsize)
1095         int arglen = strlen(arg);
1097         switch (arg[0]) {
1098         case '\"':
1099         case '\'':
1100                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1101                         return OPT_ERR_UNMATCHED_QUOTATION;
1102                 arg += 1; arglen -= 2;
1103         default:
1104                 string_ncopy_do(opt, optsize, arg, arglen);
1105                 return OPT_OK;
1106         }
1109 static enum option_code
1110 parse_args(const char ***args, const char *argv[])
1112         if (*args == NULL && !argv_copy(args, argv))
1113                 return OPT_ERR_OUT_OF_MEMORY;
1114         return OPT_OK;
1117 /* Wants: name = value */
1118 static enum option_code
1119 option_set_command(int argc, const char *argv[])
1121         if (argc < 3)
1122                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1124         if (strcmp(argv[1], "="))
1125                 return OPT_ERR_NO_VALUE_ASSIGNED;
1127         if (!strcmp(argv[0], "blame-options"))
1128                 return parse_args(&opt_blame_argv, argv + 2);
1130         if (argc != 3)
1131                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1133         if (!strcmp(argv[0], "show-author"))
1134                 return parse_enum(&opt_author, argv[2], author_map);
1136         if (!strcmp(argv[0], "show-date"))
1137                 return parse_enum(&opt_date, argv[2], date_map);
1139         if (!strcmp(argv[0], "show-rev-graph"))
1140                 return parse_bool(&opt_rev_graph, argv[2]);
1142         if (!strcmp(argv[0], "show-refs"))
1143                 return parse_bool(&opt_show_refs, argv[2]);
1145         if (!strcmp(argv[0], "show-line-numbers"))
1146                 return parse_bool(&opt_line_number, argv[2]);
1148         if (!strcmp(argv[0], "line-graphics"))
1149                 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1151         if (!strcmp(argv[0], "line-number-interval"))
1152                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1154         if (!strcmp(argv[0], "author-width"))
1155                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1157         if (!strcmp(argv[0], "horizontal-scroll"))
1158                 return parse_step(&opt_hscroll, argv[2]);
1160         if (!strcmp(argv[0], "split-view-height"))
1161                 return parse_step(&opt_scale_split_view, argv[2]);
1163         if (!strcmp(argv[0], "tab-size"))
1164                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1166         if (!strcmp(argv[0], "commit-encoding"))
1167                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1169         if (!strcmp(argv[0], "status-untracked-dirs"))
1170                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1172         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1175 /* Wants: mode request key */
1176 static enum option_code
1177 option_bind_command(int argc, const char *argv[])
1179         enum request request;
1180         int keymap = -1;
1181         int key;
1183         if (argc < 3)
1184                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1186         if (!set_keymap(&keymap, argv[0]))
1187                 return OPT_ERR_UNKNOWN_KEY_MAP;
1189         key = get_key_value(argv[1]);
1190         if (key == ERR)
1191                 return OPT_ERR_UNKNOWN_KEY;
1193         request = get_request(argv[2]);
1194         if (request == REQ_UNKNOWN) {
1195                 static const struct enum_map obsolete[] = {
1196                         ENUM_MAP("cherry-pick",         REQ_NONE),
1197                         ENUM_MAP("screen-resize",       REQ_NONE),
1198                         ENUM_MAP("tree-parent",         REQ_PARENT),
1199                 };
1200                 int alias;
1202                 if (map_enum(&alias, obsolete, argv[2])) {
1203                         if (alias != REQ_NONE)
1204                                 add_keybinding(keymap, alias, key);
1205                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1206                 }
1207         }
1208         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1209                 request = add_run_request(keymap, key, argv + 2);
1210         if (request == REQ_UNKNOWN)
1211                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1213         add_keybinding(keymap, request, key);
1215         return OPT_OK;
1218 static enum option_code
1219 set_option(const char *opt, char *value)
1221         const char *argv[SIZEOF_ARG];
1222         int argc = 0;
1224         if (!argv_from_string(argv, &argc, value))
1225                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1227         if (!strcmp(opt, "color"))
1228                 return option_color_command(argc, argv);
1230         if (!strcmp(opt, "set"))
1231                 return option_set_command(argc, argv);
1233         if (!strcmp(opt, "bind"))
1234                 return option_bind_command(argc, argv);
1236         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1239 struct config_state {
1240         int lineno;
1241         bool errors;
1242 };
1244 static int
1245 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1247         struct config_state *config = data;
1248         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1250         config->lineno++;
1252         /* Check for comment markers, since read_properties() will
1253          * only ensure opt and value are split at first " \t". */
1254         optlen = strcspn(opt, "#");
1255         if (optlen == 0)
1256                 return OK;
1258         if (opt[optlen] == 0) {
1259                 /* Look for comment endings in the value. */
1260                 size_t len = strcspn(value, "#");
1262                 if (len < valuelen) {
1263                         valuelen = len;
1264                         value[valuelen] = 0;
1265                 }
1267                 status = set_option(opt, value);
1268         }
1270         if (status != OPT_OK) {
1271                 warn("Error on line %d, near '%.*s': %s",
1272                      config->lineno, (int) optlen, opt, option_errors[status]);
1273                 config->errors = TRUE;
1274         }
1276         /* Always keep going if errors are encountered. */
1277         return OK;
1280 static void
1281 load_option_file(const char *path)
1283         struct config_state config = { 0, FALSE };
1284         struct io io;
1286         /* It's OK that the file doesn't exist. */
1287         if (!io_open(&io, "%s", path))
1288                 return;
1290         if (io_load(&io, " \t", read_option, &config) == ERR ||
1291             config.errors == TRUE)
1292                 warn("Errors while loading %s.", path);
1295 static int
1296 load_options(void)
1298         const char *home = getenv("HOME");
1299         const char *tigrc_user = getenv("TIGRC_USER");
1300         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1301         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1302         char buf[SIZEOF_STR];
1304         if (!tigrc_system)
1305                 tigrc_system = SYSCONFDIR "/tigrc";
1306         load_option_file(tigrc_system);
1308         if (!tigrc_user) {
1309                 if (!home || !string_format(buf, "%s/.tigrc", home))
1310                         return ERR;
1311                 tigrc_user = buf;
1312         }
1313         load_option_file(tigrc_user);
1315         /* Add _after_ loading config files to avoid adding run requests
1316          * that conflict with keybindings. */
1317         add_builtin_run_requests();
1319         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1320                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1321                 int argc = 0;
1323                 if (!string_format(buf, "%s", tig_diff_opts) ||
1324                     !argv_from_string(diff_opts, &argc, buf))
1325                         die("TIG_DIFF_OPTS contains too many arguments");
1326                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1327                         die("Failed to format TIG_DIFF_OPTS arguments");
1328         }
1330         return OK;
1334 /*
1335  * The viewer
1336  */
1338 struct view;
1339 struct view_ops;
1341 /* The display array of active views and the index of the current view. */
1342 static struct view *display[2];
1343 static WINDOW *display_win[2];
1344 static WINDOW *display_title[2];
1345 static unsigned int current_view;
1347 #define foreach_displayed_view(view, i) \
1348         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1350 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1352 /* Current head and commit ID */
1353 static char ref_blob[SIZEOF_REF]        = "";
1354 static char ref_commit[SIZEOF_REF]      = "HEAD";
1355 static char ref_head[SIZEOF_REF]        = "HEAD";
1356 static char ref_branch[SIZEOF_REF]      = "";
1358 enum view_type {
1359         VIEW_MAIN,
1360         VIEW_DIFF,
1361         VIEW_LOG,
1362         VIEW_TREE,
1363         VIEW_BLOB,
1364         VIEW_BLAME,
1365         VIEW_BRANCH,
1366         VIEW_HELP,
1367         VIEW_PAGER,
1368         VIEW_STATUS,
1369         VIEW_STAGE,
1370 };
1372 struct view {
1373         enum view_type type;    /* View type */
1374         const char *name;       /* View name */
1375         const char *id;         /* Points to either of ref_{head,commit,blob} */
1377         struct view_ops *ops;   /* View operations */
1379         enum keymap keymap;     /* What keymap does this view have */
1380         bool git_dir;           /* Whether the view requires a git directory. */
1382         char ref[SIZEOF_REF];   /* Hovered commit reference */
1383         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1385         int height, width;      /* The width and height of the main window */
1386         WINDOW *win;            /* The main window */
1388         /* Navigation */
1389         unsigned long offset;   /* Offset of the window top */
1390         unsigned long yoffset;  /* Offset from the window side. */
1391         unsigned long lineno;   /* Current line number */
1392         unsigned long p_offset; /* Previous offset of the window top */
1393         unsigned long p_yoffset;/* Previous offset from the window side */
1394         unsigned long p_lineno; /* Previous current line number */
1395         bool p_restore;         /* Should the previous position be restored. */
1397         /* Searching */
1398         char grep[SIZEOF_STR];  /* Search string */
1399         regex_t *regex;         /* Pre-compiled regexp */
1401         /* If non-NULL, points to the view that opened this view. If this view
1402          * is closed tig will switch back to the parent view. */
1403         struct view *parent;
1404         struct view *prev;
1406         /* Buffering */
1407         size_t lines;           /* Total number of lines */
1408         struct line *line;      /* Line index */
1409         unsigned int digits;    /* Number of digits in the lines member. */
1411         /* Drawing */
1412         struct line *curline;   /* Line currently being drawn. */
1413         enum line_type curtype; /* Attribute currently used for drawing. */
1414         unsigned long col;      /* Column when drawing. */
1415         bool has_scrolled;      /* View was scrolled. */
1417         /* Loading */
1418         const char **argv;      /* Shell command arguments. */
1419         const char *dir;        /* Directory from which to execute. */
1420         struct io io;
1421         struct io *pipe;
1422         time_t start_time;
1423         time_t update_secs;
1424 };
1426 enum open_flags {
1427         OPEN_DEFAULT = 0,       /* Use default view switching. */
1428         OPEN_SPLIT = 1,         /* Split current view. */
1429         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1430         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
1431         OPEN_PREPARED = 32,     /* Open already prepared command. */
1432         OPEN_EXTRA = 64,        /* Open extra data from command. */
1433 };
1435 struct view_ops {
1436         /* What type of content being displayed. Used in the title bar. */
1437         const char *type;
1438         /* Open and reads in all view content. */
1439         bool (*open)(struct view *view, enum open_flags flags);
1440         /* Read one line; updates view->line. */
1441         bool (*read)(struct view *view, char *data);
1442         /* Draw one line; @lineno must be < view->height. */
1443         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1444         /* Depending on view handle a special requests. */
1445         enum request (*request)(struct view *view, enum request request, struct line *line);
1446         /* Search for regexp in a line. */
1447         bool (*grep)(struct view *view, struct line *line);
1448         /* Select line */
1449         void (*select)(struct view *view, struct line *line);
1450 };
1452 static struct view_ops blame_ops;
1453 static struct view_ops blob_ops;
1454 static struct view_ops diff_ops;
1455 static struct view_ops help_ops;
1456 static struct view_ops log_ops;
1457 static struct view_ops main_ops;
1458 static struct view_ops pager_ops;
1459 static struct view_ops stage_ops;
1460 static struct view_ops status_ops;
1461 static struct view_ops tree_ops;
1462 static struct view_ops branch_ops;
1464 #define VIEW_STR(type, name, ref, ops, map, git) \
1465         { type, name, ref, ops, map, git }
1467 #define VIEW_(id, name, ops, git, ref) \
1468         VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1470 static struct view views[] = {
1471         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1472         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1473         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1474         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1475         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1476         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1477         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1478         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1479         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1480         VIEW_(STATUS, "status", &status_ops, TRUE,  "status"),
1481         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1482 };
1484 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1486 #define foreach_view(view, i) \
1487         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1489 #define view_is_displayed(view) \
1490         (view == display[0] || view == display[1])
1492 static enum request
1493 view_request(struct view *view, enum request request)
1495         if (!view || !view->lines)
1496                 return request;
1497         return view->ops->request(view, request, &view->line[view->lineno]);
1501 /*
1502  * View drawing.
1503  */
1505 static inline void
1506 set_view_attr(struct view *view, enum line_type type)
1508         if (!view->curline->selected && view->curtype != type) {
1509                 (void) wattrset(view->win, get_line_attr(type));
1510                 wchgat(view->win, -1, 0, type, NULL);
1511                 view->curtype = type;
1512         }
1515 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1517 static bool
1518 draw_chars(struct view *view, enum line_type type, const char *string,
1519            int max_len, bool use_tilde)
1521         static char out_buffer[BUFSIZ * 2];
1522         int len = 0;
1523         int col = 0;
1524         int trimmed = FALSE;
1525         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1527         if (max_len <= 0)
1528                 return VIEW_MAX_LEN(view) <= 0;
1530         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1532         set_view_attr(view, type);
1533         if (len > 0) {
1534                 if (opt_iconv_out != ICONV_NONE) {
1535                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1536                         size_t inlen = len + 1;
1538                         char *outbuf = out_buffer;
1539                         size_t outlen = sizeof(out_buffer);
1541                         size_t ret;
1543                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1544                         if (ret != (size_t) -1) {
1545                                 string = out_buffer;
1546                                 len = sizeof(out_buffer) - outlen;
1547                         }
1548                 }
1550                 waddnstr(view->win, string, len);
1552                 if (trimmed && use_tilde) {
1553                         set_view_attr(view, LINE_DELIMITER);
1554                         waddch(view->win, '~');
1555                         col++;
1556                 }
1557         }
1559         view->col += col;
1560         return VIEW_MAX_LEN(view) <= 0;
1563 static bool
1564 draw_space(struct view *view, enum line_type type, int max, int spaces)
1566         static char space[] = "                    ";
1568         spaces = MIN(max, spaces);
1570         while (spaces > 0) {
1571                 int len = MIN(spaces, sizeof(space) - 1);
1573                 if (draw_chars(view, type, space, len, FALSE))
1574                         return TRUE;
1575                 spaces -= len;
1576         }
1578         return VIEW_MAX_LEN(view) <= 0;
1581 static bool
1582 draw_text(struct view *view, enum line_type type, const char *string)
1584         char text[SIZEOF_STR];
1586         do {
1587                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1589                 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1590                         return TRUE;
1591                 string += pos;
1592         } while (*string);
1594         return VIEW_MAX_LEN(view) <= 0;
1597 static bool
1598 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1600         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1601         int max = VIEW_MAX_LEN(view);
1602         int i;
1604         if (max < size)
1605                 size = max;
1607         set_view_attr(view, type);
1608         /* Using waddch() instead of waddnstr() ensures that
1609          * they'll be rendered correctly for the cursor line. */
1610         for (i = skip; i < size; i++)
1611                 waddch(view->win, graphic[i]);
1613         view->col += size;
1614         if (separator) {
1615                 if (size < max && skip <= size)
1616                         waddch(view->win, ' ');
1617                 view->col++;
1618         }
1620         return VIEW_MAX_LEN(view) <= 0;
1623 static bool
1624 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1626         int max = MIN(VIEW_MAX_LEN(view), len);
1627         int col = view->col;
1629         if (!text) 
1630                 return draw_space(view, type, max, max);
1632         return draw_chars(view, type, text, max - 1, trim)
1633             || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1636 static bool
1637 draw_date(struct view *view, struct time *time)
1639         const char *date = mkdate(time, opt_date);
1640         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1642         if (opt_date == DATE_NO)
1643                 return FALSE;
1645         return draw_field(view, LINE_DATE, date, cols, FALSE);
1648 static bool
1649 draw_author(struct view *view, const char *author)
1651         bool trim = author_trim(opt_author_cols);
1652         const char *text = mkauthor(author, opt_author_cols, opt_author);
1654         return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1657 static bool
1658 draw_mode(struct view *view, mode_t mode)
1660         const char *str = mkmode(mode);
1662         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1665 static bool
1666 draw_lineno(struct view *view, unsigned int lineno)
1668         char number[10];
1669         int digits3 = view->digits < 3 ? 3 : view->digits;
1670         int max = MIN(VIEW_MAX_LEN(view), digits3);
1671         char *text = NULL;
1672         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1674         lineno += view->offset + 1;
1675         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1676                 static char fmt[] = "%1ld";
1678                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1679                 if (string_format(number, fmt, lineno))
1680                         text = number;
1681         }
1682         if (text)
1683                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1684         else
1685                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1686         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1689 static bool
1690 draw_refs(struct view *view, struct ref_list *refs)
1692         size_t i;
1694         if (!opt_show_refs || !refs)
1695                 return FALSE;
1697         for (i = 0; i < refs->size; i++) {
1698                 struct ref *ref = refs->refs[i];
1699                 enum line_type type;
1701                 if (ref->head)
1702                         type = LINE_MAIN_HEAD;
1703                 else if (ref->ltag)
1704                         type = LINE_MAIN_LOCAL_TAG;
1705                 else if (ref->tag)
1706                         type = LINE_MAIN_TAG;
1707                 else if (ref->tracked)
1708                         type = LINE_MAIN_TRACKED;
1709                 else if (ref->remote)
1710                         type = LINE_MAIN_REMOTE;
1711                 else
1712                         type = LINE_MAIN_REF;
1714                 if (draw_text(view, type, "[") ||
1715                     draw_text(view, type, ref->name) ||
1716                     draw_text(view, type, "]"))
1717                         return TRUE;
1719                 if (draw_text(view, LINE_DEFAULT, " "))
1720                         return TRUE;
1721         }
1723         return FALSE;
1726 static bool
1727 draw_view_line(struct view *view, unsigned int lineno)
1729         struct line *line;
1730         bool selected = (view->offset + lineno == view->lineno);
1732         assert(view_is_displayed(view));
1734         if (view->offset + lineno >= view->lines)
1735                 return FALSE;
1737         line = &view->line[view->offset + lineno];
1739         wmove(view->win, lineno, 0);
1740         if (line->cleareol)
1741                 wclrtoeol(view->win);
1742         view->col = 0;
1743         view->curline = line;
1744         view->curtype = LINE_NONE;
1745         line->selected = FALSE;
1746         line->dirty = line->cleareol = 0;
1748         if (selected) {
1749                 set_view_attr(view, LINE_CURSOR);
1750                 line->selected = TRUE;
1751                 view->ops->select(view, line);
1752         }
1754         return view->ops->draw(view, line, lineno);
1757 static void
1758 redraw_view_dirty(struct view *view)
1760         bool dirty = FALSE;
1761         int lineno;
1763         for (lineno = 0; lineno < view->height; lineno++) {
1764                 if (view->offset + lineno >= view->lines)
1765                         break;
1766                 if (!view->line[view->offset + lineno].dirty)
1767                         continue;
1768                 dirty = TRUE;
1769                 if (!draw_view_line(view, lineno))
1770                         break;
1771         }
1773         if (!dirty)
1774                 return;
1775         wnoutrefresh(view->win);
1778 static void
1779 redraw_view_from(struct view *view, int lineno)
1781         assert(0 <= lineno && lineno < view->height);
1783         for (; lineno < view->height; lineno++) {
1784                 if (!draw_view_line(view, lineno))
1785                         break;
1786         }
1788         wnoutrefresh(view->win);
1791 static void
1792 redraw_view(struct view *view)
1794         werase(view->win);
1795         redraw_view_from(view, 0);
1799 static void
1800 update_view_title(struct view *view)
1802         char buf[SIZEOF_STR];
1803         char state[SIZEOF_STR];
1804         size_t bufpos = 0, statelen = 0;
1805         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1807         assert(view_is_displayed(view));
1809         if (view->type != VIEW_STATUS && view->lines) {
1810                 unsigned int view_lines = view->offset + view->height;
1811                 unsigned int lines = view->lines
1812                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1813                                    : 0;
1815                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1816                                    view->ops->type,
1817                                    view->lineno + 1,
1818                                    view->lines,
1819                                    lines);
1821         }
1823         if (view->pipe) {
1824                 time_t secs = time(NULL) - view->start_time;
1826                 /* Three git seconds are a long time ... */
1827                 if (secs > 2)
1828                         string_format_from(state, &statelen, " loading %lds", secs);
1829         }
1831         string_format_from(buf, &bufpos, "[%s]", view->name);
1832         if (*view->ref && bufpos < view->width) {
1833                 size_t refsize = strlen(view->ref);
1834                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1836                 if (minsize < view->width)
1837                         refsize = view->width - minsize + 7;
1838                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1839         }
1841         if (statelen && bufpos < view->width) {
1842                 string_format_from(buf, &bufpos, "%s", state);
1843         }
1845         if (view == display[current_view])
1846                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1847         else
1848                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1850         mvwaddnstr(window, 0, 0, buf, bufpos);
1851         wclrtoeol(window);
1852         wnoutrefresh(window);
1855 static int
1856 apply_step(double step, int value)
1858         if (step >= 1)
1859                 return (int) step;
1860         value *= step + 0.01;
1861         return value ? value : 1;
1864 static void
1865 resize_display(void)
1867         int offset, i;
1868         struct view *base = display[0];
1869         struct view *view = display[1] ? display[1] : display[0];
1871         /* Setup window dimensions */
1873         getmaxyx(stdscr, base->height, base->width);
1875         /* Make room for the status window. */
1876         base->height -= 1;
1878         if (view != base) {
1879                 /* Horizontal split. */
1880                 view->width   = base->width;
1881                 view->height  = apply_step(opt_scale_split_view, base->height);
1882                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1883                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1884                 base->height -= view->height;
1886                 /* Make room for the title bar. */
1887                 view->height -= 1;
1888         }
1890         /* Make room for the title bar. */
1891         base->height -= 1;
1893         offset = 0;
1895         foreach_displayed_view (view, i) {
1896                 if (!display_win[i]) {
1897                         display_win[i] = newwin(view->height, view->width, offset, 0);
1898                         if (!display_win[i])
1899                                 die("Failed to create %s view", view->name);
1901                         scrollok(display_win[i], FALSE);
1903                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1904                         if (!display_title[i])
1905                                 die("Failed to create title window");
1907                 } else {
1908                         wresize(display_win[i], view->height, view->width);
1909                         mvwin(display_win[i],   offset, 0);
1910                         mvwin(display_title[i], offset + view->height, 0);
1911                 }
1913                 view->win = display_win[i];
1915                 offset += view->height + 1;
1916         }
1919 static void
1920 redraw_display(bool clear)
1922         struct view *view;
1923         int i;
1925         foreach_displayed_view (view, i) {
1926                 if (clear)
1927                         wclear(view->win);
1928                 redraw_view(view);
1929                 update_view_title(view);
1930         }
1934 /*
1935  * Option management
1936  */
1938 #define TOGGLE_MENU \
1939         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1940         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1941         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1942         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1943         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1944         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1946 static void
1947 toggle_option(enum request request)
1949         const struct {
1950                 enum request request;
1951                 const struct enum_map *map;
1952                 size_t map_size;
1953         } data[] = {            
1954 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1955                 TOGGLE_MENU
1956 #undef  TOGGLE_
1957         };
1958         const struct menu_item menu[] = {
1959 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1960                 TOGGLE_MENU
1961 #undef  TOGGLE_
1962                 { 0 }
1963         };
1964         int i = 0;
1966         if (request == REQ_OPTIONS) {
1967                 if (!prompt_menu("Toggle option", menu, &i))
1968                         return;
1969         } else {
1970                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1971                         i++;
1972                 if (i >= ARRAY_SIZE(data))
1973                         die("Invalid request (%d)", request);
1974         }
1976         if (data[i].map != NULL) {
1977                 unsigned int *opt = menu[i].data;
1979                 *opt = (*opt + 1) % data[i].map_size;
1980                 redraw_display(FALSE);
1981                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1983         } else {
1984                 bool *option = menu[i].data;
1986                 *option = !*option;
1987                 redraw_display(FALSE);
1988                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1989         }
1992 static void
1993 maximize_view(struct view *view, bool redraw)
1995         memset(display, 0, sizeof(display));
1996         current_view = 0;
1997         display[current_view] = view;
1998         resize_display();
1999         if (redraw) {
2000                 redraw_display(FALSE);
2001                 report("");
2002         }
2006 /*
2007  * Navigation
2008  */
2010 static bool
2011 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2013         if (lineno >= view->lines)
2014                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2016         if (offset > lineno || offset + view->height <= lineno) {
2017                 unsigned long half = view->height / 2;
2019                 if (lineno > half)
2020                         offset = lineno - half;
2021                 else
2022                         offset = 0;
2023         }
2025         if (offset != view->offset || lineno != view->lineno) {
2026                 view->offset = offset;
2027                 view->lineno = lineno;
2028                 return TRUE;
2029         }
2031         return FALSE;
2034 /* Scrolling backend */
2035 static void
2036 do_scroll_view(struct view *view, int lines)
2038         bool redraw_current_line = FALSE;
2040         /* The rendering expects the new offset. */
2041         view->offset += lines;
2043         assert(0 <= view->offset && view->offset < view->lines);
2044         assert(lines);
2046         /* Move current line into the view. */
2047         if (view->lineno < view->offset) {
2048                 view->lineno = view->offset;
2049                 redraw_current_line = TRUE;
2050         } else if (view->lineno >= view->offset + view->height) {
2051                 view->lineno = view->offset + view->height - 1;
2052                 redraw_current_line = TRUE;
2053         }
2055         assert(view->offset <= view->lineno && view->lineno < view->lines);
2057         /* Redraw the whole screen if scrolling is pointless. */
2058         if (view->height < ABS(lines)) {
2059                 redraw_view(view);
2061         } else {
2062                 int line = lines > 0 ? view->height - lines : 0;
2063                 int end = line + ABS(lines);
2065                 scrollok(view->win, TRUE);
2066                 wscrl(view->win, lines);
2067                 scrollok(view->win, FALSE);
2069                 while (line < end && draw_view_line(view, line))
2070                         line++;
2072                 if (redraw_current_line)
2073                         draw_view_line(view, view->lineno - view->offset);
2074                 wnoutrefresh(view->win);
2075         }
2077         view->has_scrolled = TRUE;
2078         report("");
2081 /* Scroll frontend */
2082 static void
2083 scroll_view(struct view *view, enum request request)
2085         int lines = 1;
2087         assert(view_is_displayed(view));
2089         switch (request) {
2090         case REQ_SCROLL_FIRST_COL:
2091                 view->yoffset = 0;
2092                 redraw_view_from(view, 0);
2093                 report("");
2094                 return;
2095         case REQ_SCROLL_LEFT:
2096                 if (view->yoffset == 0) {
2097                         report("Cannot scroll beyond the first column");
2098                         return;
2099                 }
2100                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2101                         view->yoffset = 0;
2102                 else
2103                         view->yoffset -= apply_step(opt_hscroll, view->width);
2104                 redraw_view_from(view, 0);
2105                 report("");
2106                 return;
2107         case REQ_SCROLL_RIGHT:
2108                 view->yoffset += apply_step(opt_hscroll, view->width);
2109                 redraw_view(view);
2110                 report("");
2111                 return;
2112         case REQ_SCROLL_PAGE_DOWN:
2113                 lines = view->height;
2114         case REQ_SCROLL_LINE_DOWN:
2115                 if (view->offset + lines > view->lines)
2116                         lines = view->lines - view->offset;
2118                 if (lines == 0 || view->offset + view->height >= view->lines) {
2119                         report("Cannot scroll beyond the last line");
2120                         return;
2121                 }
2122                 break;
2124         case REQ_SCROLL_PAGE_UP:
2125                 lines = view->height;
2126         case REQ_SCROLL_LINE_UP:
2127                 if (lines > view->offset)
2128                         lines = view->offset;
2130                 if (lines == 0) {
2131                         report("Cannot scroll beyond the first line");
2132                         return;
2133                 }
2135                 lines = -lines;
2136                 break;
2138         default:
2139                 die("request %d not handled in switch", request);
2140         }
2142         do_scroll_view(view, lines);
2145 /* Cursor moving */
2146 static void
2147 move_view(struct view *view, enum request request)
2149         int scroll_steps = 0;
2150         int steps;
2152         switch (request) {
2153         case REQ_MOVE_FIRST_LINE:
2154                 steps = -view->lineno;
2155                 break;
2157         case REQ_MOVE_LAST_LINE:
2158                 steps = view->lines - view->lineno - 1;
2159                 break;
2161         case REQ_MOVE_PAGE_UP:
2162                 steps = view->height > view->lineno
2163                       ? -view->lineno : -view->height;
2164                 break;
2166         case REQ_MOVE_PAGE_DOWN:
2167                 steps = view->lineno + view->height >= view->lines
2168                       ? view->lines - view->lineno - 1 : view->height;
2169                 break;
2171         case REQ_MOVE_UP:
2172                 steps = -1;
2173                 break;
2175         case REQ_MOVE_DOWN:
2176                 steps = 1;
2177                 break;
2179         default:
2180                 die("request %d not handled in switch", request);
2181         }
2183         if (steps <= 0 && view->lineno == 0) {
2184                 report("Cannot move beyond the first line");
2185                 return;
2187         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2188                 report("Cannot move beyond the last line");
2189                 return;
2190         }
2192         /* Move the current line */
2193         view->lineno += steps;
2194         assert(0 <= view->lineno && view->lineno < view->lines);
2196         /* Check whether the view needs to be scrolled */
2197         if (view->lineno < view->offset ||
2198             view->lineno >= view->offset + view->height) {
2199                 scroll_steps = steps;
2200                 if (steps < 0 && -steps > view->offset) {
2201                         scroll_steps = -view->offset;
2203                 } else if (steps > 0) {
2204                         if (view->lineno == view->lines - 1 &&
2205                             view->lines > view->height) {
2206                                 scroll_steps = view->lines - view->offset - 1;
2207                                 if (scroll_steps >= view->height)
2208                                         scroll_steps -= view->height - 1;
2209                         }
2210                 }
2211         }
2213         if (!view_is_displayed(view)) {
2214                 view->offset += scroll_steps;
2215                 assert(0 <= view->offset && view->offset < view->lines);
2216                 view->ops->select(view, &view->line[view->lineno]);
2217                 return;
2218         }
2220         /* Repaint the old "current" line if we be scrolling */
2221         if (ABS(steps) < view->height)
2222                 draw_view_line(view, view->lineno - steps - view->offset);
2224         if (scroll_steps) {
2225                 do_scroll_view(view, scroll_steps);
2226                 return;
2227         }
2229         /* Draw the current line */
2230         draw_view_line(view, view->lineno - view->offset);
2232         wnoutrefresh(view->win);
2233         report("");
2237 /*
2238  * Searching
2239  */
2241 static void search_view(struct view *view, enum request request);
2243 static bool
2244 grep_text(struct view *view, const char *text[])
2246         regmatch_t pmatch;
2247         size_t i;
2249         for (i = 0; text[i]; i++)
2250                 if (*text[i] &&
2251                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2252                         return TRUE;
2253         return FALSE;
2256 static void
2257 select_view_line(struct view *view, unsigned long lineno)
2259         unsigned long old_lineno = view->lineno;
2260         unsigned long old_offset = view->offset;
2262         if (goto_view_line(view, view->offset, lineno)) {
2263                 if (view_is_displayed(view)) {
2264                         if (old_offset != view->offset) {
2265                                 redraw_view(view);
2266                         } else {
2267                                 draw_view_line(view, old_lineno - view->offset);
2268                                 draw_view_line(view, view->lineno - view->offset);
2269                                 wnoutrefresh(view->win);
2270                         }
2271                 } else {
2272                         view->ops->select(view, &view->line[view->lineno]);
2273                 }
2274         }
2277 static void
2278 find_next(struct view *view, enum request request)
2280         unsigned long lineno = view->lineno;
2281         int direction;
2283         if (!*view->grep) {
2284                 if (!*opt_search)
2285                         report("No previous search");
2286                 else
2287                         search_view(view, request);
2288                 return;
2289         }
2291         switch (request) {
2292         case REQ_SEARCH:
2293         case REQ_FIND_NEXT:
2294                 direction = 1;
2295                 break;
2297         case REQ_SEARCH_BACK:
2298         case REQ_FIND_PREV:
2299                 direction = -1;
2300                 break;
2302         default:
2303                 return;
2304         }
2306         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2307                 lineno += direction;
2309         /* Note, lineno is unsigned long so will wrap around in which case it
2310          * will become bigger than view->lines. */
2311         for (; lineno < view->lines; lineno += direction) {
2312                 if (view->ops->grep(view, &view->line[lineno])) {
2313                         select_view_line(view, lineno);
2314                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2315                         return;
2316                 }
2317         }
2319         report("No match found for '%s'", view->grep);
2322 static void
2323 search_view(struct view *view, enum request request)
2325         int regex_err;
2327         if (view->regex) {
2328                 regfree(view->regex);
2329                 *view->grep = 0;
2330         } else {
2331                 view->regex = calloc(1, sizeof(*view->regex));
2332                 if (!view->regex)
2333                         return;
2334         }
2336         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2337         if (regex_err != 0) {
2338                 char buf[SIZEOF_STR] = "unknown error";
2340                 regerror(regex_err, view->regex, buf, sizeof(buf));
2341                 report("Search failed: %s", buf);
2342                 return;
2343         }
2345         string_copy(view->grep, opt_search);
2347         find_next(view, request);
2350 /*
2351  * Incremental updating
2352  */
2354 static void
2355 reset_view(struct view *view)
2357         int i;
2359         for (i = 0; i < view->lines; i++)
2360                 free(view->line[i].data);
2361         free(view->line);
2363         view->p_offset = view->offset;
2364         view->p_yoffset = view->yoffset;
2365         view->p_lineno = view->lineno;
2367         view->line = NULL;
2368         view->offset = 0;
2369         view->yoffset = 0;
2370         view->lines  = 0;
2371         view->lineno = 0;
2372         view->vid[0] = 0;
2373         view->update_secs = 0;
2376 static const char *
2377 format_arg(const char *name)
2379         static struct {
2380                 const char *name;
2381                 size_t namelen;
2382                 const char *value;
2383                 const char *value_if_empty;
2384         } vars[] = {
2385 #define FORMAT_VAR(name, value, value_if_empty) \
2386         { name, STRING_SIZE(name), value, value_if_empty }
2387                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2388                 FORMAT_VAR("%(file)",           opt_file,       ""),
2389                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2390                 FORMAT_VAR("%(head)",           ref_head,       ""),
2391                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2392                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2393                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2394         };
2395         int i;
2397         for (i = 0; i < ARRAY_SIZE(vars); i++)
2398                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2399                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2401         report("Unknown replacement: `%s`", name);
2402         return NULL;
2405 static bool
2406 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2408         char buf[SIZEOF_STR];
2409         int argc;
2411         argv_free(*dst_argv);
2413         for (argc = 0; src_argv[argc]; argc++) {
2414                 const char *arg = src_argv[argc];
2415                 size_t bufpos = 0;
2417                 if (!strcmp(arg, "%(fileargs)")) {
2418                         if (!argv_append_array(dst_argv, opt_file_argv))
2419                                 break;
2420                         continue;
2422                 } else if (!strcmp(arg, "%(diffargs)")) {
2423                         if (!argv_append_array(dst_argv, opt_diff_argv))
2424                                 break;
2425                         continue;
2427                 } else if (!strcmp(arg, "%(blameargs)")) {
2428                         if (!argv_append_array(dst_argv, opt_blame_argv))
2429                                 break;
2430                         continue;
2432                 } else if (!strcmp(arg, "%(revargs)") ||
2433                            (first && !strcmp(arg, "%(commit)"))) {
2434                         if (!argv_append_array(dst_argv, opt_rev_argv))
2435                                 break;
2436                         continue;
2437                 }
2439                 while (arg) {
2440                         char *next = strstr(arg, "%(");
2441                         int len = next - arg;
2442                         const char *value;
2444                         if (!next) {
2445                                 len = strlen(arg);
2446                                 value = "";
2448                         } else {
2449                                 value = format_arg(next);
2451                                 if (!value) {
2452                                         return FALSE;
2453                                 }
2454                         }
2456                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2457                                 return FALSE;
2459                         arg = next ? strchr(next, ')') + 1 : NULL;
2460                 }
2462                 if (!argv_append(dst_argv, buf))
2463                         break;
2464         }
2466         return src_argv[argc] == NULL;
2469 static bool
2470 restore_view_position(struct view *view)
2472         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2473                 return FALSE;
2475         /* Changing the view position cancels the restoring. */
2476         /* FIXME: Changing back to the first line is not detected. */
2477         if (view->offset != 0 || view->lineno != 0) {
2478                 view->p_restore = FALSE;
2479                 return FALSE;
2480         }
2482         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2483             view_is_displayed(view))
2484                 werase(view->win);
2486         view->yoffset = view->p_yoffset;
2487         view->p_restore = FALSE;
2489         return TRUE;
2492 static void
2493 end_update(struct view *view, bool force)
2495         if (!view->pipe)
2496                 return;
2497         while (!view->ops->read(view, NULL))
2498                 if (!force)
2499                         return;
2500         if (force)
2501                 io_kill(view->pipe);
2502         io_done(view->pipe);
2503         view->pipe = NULL;
2506 static void
2507 setup_update(struct view *view, const char *vid)
2509         reset_view(view);
2510         string_copy_rev(view->vid, vid);
2511         view->pipe = &view->io;
2512         view->start_time = time(NULL);
2515 static bool
2516 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2518         bool extra = !!(flags & (OPEN_EXTRA));
2519         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2520         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2522         if (!reload && !strcmp(view->vid, view->id))
2523                 return TRUE;
2525         if (view->pipe) {
2526                 if (extra)
2527                         io_done(view->pipe);
2528                 else
2529                         end_update(view, TRUE);
2530         }
2532         if (!refresh) {
2533                 view->dir = dir;
2534                 if (!format_argv(&view->argv, argv, !view->prev))
2535                         return FALSE;
2537                 /* Put the current ref_* value to the view title ref
2538                  * member. This is needed by the blob view. Most other
2539                  * views sets it automatically after loading because the
2540                  * first line is a commit line. */
2541                 string_copy_rev(view->ref, view->id);
2542         }
2544         if (view->argv && view->argv[0] &&
2545             !io_run(&view->io, IO_RD, view->dir, view->argv))
2546                 return FALSE;
2548         if (!extra)
2549                 setup_update(view, view->id);
2551         return TRUE;
2554 static bool
2555 view_open(struct view *view, enum open_flags flags)
2557         return begin_update(view, NULL, NULL, flags);
2560 static bool
2561 update_view(struct view *view)
2563         char out_buffer[BUFSIZ * 2];
2564         char *line;
2565         /* Clear the view and redraw everything since the tree sorting
2566          * might have rearranged things. */
2567         bool redraw = view->lines == 0;
2568         bool can_read = TRUE;
2570         if (!view->pipe)
2571                 return TRUE;
2573         if (!io_can_read(view->pipe, FALSE)) {
2574                 if (view->lines == 0 && view_is_displayed(view)) {
2575                         time_t secs = time(NULL) - view->start_time;
2577                         if (secs > 1 && secs > view->update_secs) {
2578                                 if (view->update_secs == 0)
2579                                         redraw_view(view);
2580                                 update_view_title(view);
2581                                 view->update_secs = secs;
2582                         }
2583                 }
2584                 return TRUE;
2585         }
2587         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2588                 if (opt_iconv_in != ICONV_NONE) {
2589                         ICONV_CONST char *inbuf = line;
2590                         size_t inlen = strlen(line) + 1;
2592                         char *outbuf = out_buffer;
2593                         size_t outlen = sizeof(out_buffer);
2595                         size_t ret;
2597                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2598                         if (ret != (size_t) -1)
2599                                 line = out_buffer;
2600                 }
2602                 if (!view->ops->read(view, line)) {
2603                         report("Allocation failure");
2604                         end_update(view, TRUE);
2605                         return FALSE;
2606                 }
2607         }
2609         {
2610                 unsigned long lines = view->lines;
2611                 int digits;
2613                 for (digits = 0; lines; digits++)
2614                         lines /= 10;
2616                 /* Keep the displayed view in sync with line number scaling. */
2617                 if (digits != view->digits) {
2618                         view->digits = digits;
2619                         if (opt_line_number || view->type == VIEW_BLAME)
2620                                 redraw = TRUE;
2621                 }
2622         }
2624         if (io_error(view->pipe)) {
2625                 report("Failed to read: %s", io_strerror(view->pipe));
2626                 end_update(view, TRUE);
2628         } else if (io_eof(view->pipe)) {
2629                 if (view_is_displayed(view))
2630                         report("");
2631                 end_update(view, FALSE);
2632         }
2634         if (restore_view_position(view))
2635                 redraw = TRUE;
2637         if (!view_is_displayed(view))
2638                 return TRUE;
2640         if (redraw)
2641                 redraw_view_from(view, 0);
2642         else
2643                 redraw_view_dirty(view);
2645         /* Update the title _after_ the redraw so that if the redraw picks up a
2646          * commit reference in view->ref it'll be available here. */
2647         update_view_title(view);
2648         return TRUE;
2651 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2653 static struct line *
2654 add_line_data(struct view *view, void *data, enum line_type type)
2656         struct line *line;
2658         if (!realloc_lines(&view->line, view->lines, 1))
2659                 return NULL;
2661         line = &view->line[view->lines++];
2662         memset(line, 0, sizeof(*line));
2663         line->type = type;
2664         line->data = data;
2665         line->dirty = 1;
2667         return line;
2670 static struct line *
2671 add_line_text(struct view *view, const char *text, enum line_type type)
2673         char *data = text ? strdup(text) : NULL;
2675         return data ? add_line_data(view, data, type) : NULL;
2678 static struct line *
2679 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2681         char buf[SIZEOF_STR];
2682         va_list args;
2684         va_start(args, fmt);
2685         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2686                 buf[0] = 0;
2687         va_end(args);
2689         return buf[0] ? add_line_text(view, buf, type) : NULL;
2692 /*
2693  * View opening
2694  */
2696 static void
2697 load_view(struct view *view, enum open_flags flags)
2699         if (view->pipe)
2700                 end_update(view, TRUE);
2701         if (!view->ops->open(view, flags)) {
2702                 report("Failed to load %s view", view->name);
2703                 return;
2704         }
2705         restore_view_position(view);
2707         if (view->pipe && view->lines == 0) {
2708                 /* Clear the old view and let the incremental updating refill
2709                  * the screen. */
2710                 werase(view->win);
2711                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2712                 report("");
2713         } else if (view_is_displayed(view)) {
2714                 redraw_view(view);
2715                 report("");
2716         }
2719 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2721 static void
2722 split_view(struct view *prev, struct view *view)
2724         display[1] = view;
2725         current_view = 1;
2726         view->parent = prev;
2727         resize_display();
2729         if (prev->lineno - prev->offset >= prev->height) {
2730                 /* Take the title line into account. */
2731                 int lines = prev->lineno - prev->offset - prev->height + 1;
2733                 /* Scroll the view that was split if the current line is
2734                  * outside the new limited view. */
2735                 do_scroll_view(prev, lines);
2736         }
2738         if (view != prev && view_is_displayed(prev)) {
2739                 /* "Blur" the previous view. */
2740                 update_view_title(prev);
2741         }
2744 static void
2745 open_view(struct view *prev, enum request request, enum open_flags flags)
2747         bool split = !!(flags & OPEN_SPLIT);
2748         bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2749         struct view *view = VIEW(request);
2750         int nviews = displayed_views();
2752         assert(flags ^ OPEN_REFRESH);
2754         if (view == prev && nviews == 1 && !reload) {
2755                 report("Already in %s view", view->name);
2756                 return;
2757         }
2759         if (view->git_dir && !opt_git_dir[0]) {
2760                 report("The %s view is disabled in pager view", view->name);
2761                 return;
2762         }
2764         if (split) {
2765                 split_view(prev, view);
2766         } else {
2767                 maximize_view(view, FALSE);
2768         }
2770         /* No prev signals that this is the first loaded view. */
2771         if (prev && view != prev) {
2772                 view->prev = prev;
2773         }
2775         load_view(view, flags);
2778 static void
2779 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2781         enum request request = view - views + REQ_OFFSET + 1;
2783         if (view->pipe)
2784                 end_update(view, TRUE);
2785         view->dir = dir;
2786         
2787         if (!argv_copy(&view->argv, argv)) {
2788                 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2789         } else {
2790                 open_view(prev, request, flags | OPEN_PREPARED);
2791         }
2794 static void
2795 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2797         const char *file_argv[] = { opt_cdup, file , NULL };
2799         open_argv(prev, view, file_argv, opt_cdup, flags); 
2802 static void
2803 open_external_viewer(const char *argv[], const char *dir)
2805         def_prog_mode();           /* save current tty modes */
2806         endwin();                  /* restore original tty modes */
2807         io_run_fg(argv, dir);
2808         fprintf(stderr, "Press Enter to continue");
2809         getc(opt_tty);
2810         reset_prog_mode();
2811         redraw_display(TRUE);
2814 static void
2815 open_mergetool(const char *file)
2817         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2819         open_external_viewer(mergetool_argv, opt_cdup);
2822 static void
2823 open_editor(const char *file)
2825         const char *editor_argv[] = { "vi", file, NULL };
2826         const char *editor;
2828         editor = getenv("GIT_EDITOR");
2829         if (!editor && *opt_editor)
2830                 editor = opt_editor;
2831         if (!editor)
2832                 editor = getenv("VISUAL");
2833         if (!editor)
2834                 editor = getenv("EDITOR");
2835         if (!editor)
2836                 editor = "vi";
2838         editor_argv[0] = editor;
2839         open_external_viewer(editor_argv, opt_cdup);
2842 static void
2843 open_run_request(enum request request)
2845         struct run_request *req = get_run_request(request);
2846         const char **argv = NULL;
2848         if (!req) {
2849                 report("Unknown run request");
2850                 return;
2851         }
2853         if (format_argv(&argv, req->argv, FALSE))
2854                 open_external_viewer(argv, NULL);
2855         if (argv)
2856                 argv_free(argv);
2857         free(argv);
2860 /*
2861  * User request switch noodle
2862  */
2864 static int
2865 view_driver(struct view *view, enum request request)
2867         int i;
2869         if (request == REQ_NONE)
2870                 return TRUE;
2872         if (request > REQ_NONE) {
2873                 open_run_request(request);
2874                 view_request(view, REQ_REFRESH);
2875                 return TRUE;
2876         }
2878         request = view_request(view, request);
2879         if (request == REQ_NONE)
2880                 return TRUE;
2882         switch (request) {
2883         case REQ_MOVE_UP:
2884         case REQ_MOVE_DOWN:
2885         case REQ_MOVE_PAGE_UP:
2886         case REQ_MOVE_PAGE_DOWN:
2887         case REQ_MOVE_FIRST_LINE:
2888         case REQ_MOVE_LAST_LINE:
2889                 move_view(view, request);
2890                 break;
2892         case REQ_SCROLL_FIRST_COL:
2893         case REQ_SCROLL_LEFT:
2894         case REQ_SCROLL_RIGHT:
2895         case REQ_SCROLL_LINE_DOWN:
2896         case REQ_SCROLL_LINE_UP:
2897         case REQ_SCROLL_PAGE_DOWN:
2898         case REQ_SCROLL_PAGE_UP:
2899                 scroll_view(view, request);
2900                 break;
2902         case REQ_VIEW_BLAME:
2903                 if (!opt_file[0]) {
2904                         report("No file chosen, press %s to open tree view",
2905                                get_key(view->keymap, REQ_VIEW_TREE));
2906                         break;
2907                 }
2908                 open_view(view, request, OPEN_DEFAULT);
2909                 break;
2911         case REQ_VIEW_BLOB:
2912                 if (!ref_blob[0]) {
2913                         report("No file chosen, press %s to open tree view",
2914                                get_key(view->keymap, REQ_VIEW_TREE));
2915                         break;
2916                 }
2917                 open_view(view, request, OPEN_DEFAULT);
2918                 break;
2920         case REQ_VIEW_PAGER:
2921                 if (view == NULL) {
2922                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2923                                 die("Failed to open stdin");
2924                         open_view(view, request, OPEN_PREPARED);
2925                         break;
2926                 }
2928                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2929                         report("No pager content, press %s to run command from prompt",
2930                                get_key(view->keymap, REQ_PROMPT));
2931                         break;
2932                 }
2933                 open_view(view, request, OPEN_DEFAULT);
2934                 break;
2936         case REQ_VIEW_STAGE:
2937                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2938                         report("No stage content, press %s to open the status view and choose file",
2939                                get_key(view->keymap, REQ_VIEW_STATUS));
2940                         break;
2941                 }
2942                 open_view(view, request, OPEN_DEFAULT);
2943                 break;
2945         case REQ_VIEW_STATUS:
2946                 if (opt_is_inside_work_tree == FALSE) {
2947                         report("The status view requires a working tree");
2948                         break;
2949                 }
2950                 open_view(view, request, OPEN_DEFAULT);
2951                 break;
2953         case REQ_VIEW_MAIN:
2954         case REQ_VIEW_DIFF:
2955         case REQ_VIEW_LOG:
2956         case REQ_VIEW_TREE:
2957         case REQ_VIEW_HELP:
2958         case REQ_VIEW_BRANCH:
2959                 open_view(view, request, OPEN_DEFAULT);
2960                 break;
2962         case REQ_NEXT:
2963         case REQ_PREVIOUS:
2964                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2966                 if (view->parent) {
2967                         int line;
2969                         view = view->parent;
2970                         line = view->lineno;
2971                         move_view(view, request);
2972                         if (view_is_displayed(view))
2973                                 update_view_title(view);
2974                         if (line != view->lineno)
2975                                 view_request(view, REQ_ENTER);
2976                 } else {
2977                         move_view(view, request);
2978                 }
2979                 break;
2981         case REQ_VIEW_NEXT:
2982         {
2983                 int nviews = displayed_views();
2984                 int next_view = (current_view + 1) % nviews;
2986                 if (next_view == current_view) {
2987                         report("Only one view is displayed");
2988                         break;
2989                 }
2991                 current_view = next_view;
2992                 /* Blur out the title of the previous view. */
2993                 update_view_title(view);
2994                 report("");
2995                 break;
2996         }
2997         case REQ_REFRESH:
2998                 report("Refreshing is not yet supported for the %s view", view->name);
2999                 break;
3001         case REQ_MAXIMIZE:
3002                 if (displayed_views() == 2)
3003                         maximize_view(view, TRUE);
3004                 break;
3006         case REQ_OPTIONS:
3007         case REQ_TOGGLE_LINENO:
3008         case REQ_TOGGLE_DATE:
3009         case REQ_TOGGLE_AUTHOR:
3010         case REQ_TOGGLE_GRAPHIC:
3011         case REQ_TOGGLE_REV_GRAPH:
3012         case REQ_TOGGLE_REFS:
3013                 toggle_option(request);
3014                 break;
3016         case REQ_TOGGLE_SORT_FIELD:
3017         case REQ_TOGGLE_SORT_ORDER:
3018                 report("Sorting is not yet supported for the %s view", view->name);
3019                 break;
3021         case REQ_SEARCH:
3022         case REQ_SEARCH_BACK:
3023                 search_view(view, request);
3024                 break;
3026         case REQ_FIND_NEXT:
3027         case REQ_FIND_PREV:
3028                 find_next(view, request);
3029                 break;
3031         case REQ_STOP_LOADING:
3032                 foreach_view(view, i) {
3033                         if (view->pipe)
3034                                 report("Stopped loading the %s view", view->name),
3035                         end_update(view, TRUE);
3036                 }
3037                 break;
3039         case REQ_SHOW_VERSION:
3040                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3041                 return TRUE;
3043         case REQ_SCREEN_REDRAW:
3044                 redraw_display(TRUE);
3045                 break;
3047         case REQ_EDIT:
3048                 report("Nothing to edit");
3049                 break;
3051         case REQ_ENTER:
3052                 report("Nothing to enter");
3053                 break;
3055         case REQ_VIEW_CLOSE:
3056                 /* XXX: Mark closed views by letting view->prev point to the
3057                  * view itself. Parents to closed view should never be
3058                  * followed. */
3059                 if (view->prev && view->prev != view) {
3060                         maximize_view(view->prev, TRUE);
3061                         view->prev = view;
3062                         break;
3063                 }
3064                 /* Fall-through */
3065         case REQ_QUIT:
3066                 return FALSE;
3068         default:
3069                 report("Unknown key, press %s for help",
3070                        get_key(view->keymap, REQ_VIEW_HELP));
3071                 return TRUE;
3072         }
3074         return TRUE;
3078 /*
3079  * View backend utilities
3080  */
3082 enum sort_field {
3083         ORDERBY_NAME,
3084         ORDERBY_DATE,
3085         ORDERBY_AUTHOR,
3086 };
3088 struct sort_state {
3089         const enum sort_field *fields;
3090         size_t size, current;
3091         bool reverse;
3092 };
3094 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3095 #define get_sort_field(state) ((state).fields[(state).current])
3096 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3098 static void
3099 sort_view(struct view *view, enum request request, struct sort_state *state,
3100           int (*compare)(const void *, const void *))
3102         switch (request) {
3103         case REQ_TOGGLE_SORT_FIELD:
3104                 state->current = (state->current + 1) % state->size;
3105                 break;
3107         case REQ_TOGGLE_SORT_ORDER:
3108                 state->reverse = !state->reverse;
3109                 break;
3110         default:
3111                 die("Not a sort request");
3112         }
3114         qsort(view->line, view->lines, sizeof(*view->line), compare);
3115         redraw_view(view);
3118 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3120 /* Small author cache to reduce memory consumption. It uses binary
3121  * search to lookup or find place to position new entries. No entries
3122  * are ever freed. */
3123 static const char *
3124 get_author(const char *name)
3126         static const char **authors;
3127         static size_t authors_size;
3128         int from = 0, to = authors_size - 1;
3130         while (from <= to) {
3131                 size_t pos = (to + from) / 2;
3132                 int cmp = strcmp(name, authors[pos]);
3134                 if (!cmp)
3135                         return authors[pos];
3137                 if (cmp < 0)
3138                         to = pos - 1;
3139                 else
3140                         from = pos + 1;
3141         }
3143         if (!realloc_authors(&authors, authors_size, 1))
3144                 return NULL;
3145         name = strdup(name);
3146         if (!name)
3147                 return NULL;
3149         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3150         authors[from] = name;
3151         authors_size++;
3153         return name;
3156 static void
3157 parse_timesec(struct time *time, const char *sec)
3159         time->sec = (time_t) atol(sec);
3162 static void
3163 parse_timezone(struct time *time, const char *zone)
3165         long tz;
3167         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3168         tz += ('0' - zone[2]) * 60 * 60;
3169         tz += ('0' - zone[3]) * 60 * 10;
3170         tz += ('0' - zone[4]) * 60;
3172         if (zone[0] == '-')
3173                 tz = -tz;
3175         time->tz = tz;
3176         time->sec -= tz;
3179 /* Parse author lines where the name may be empty:
3180  *      author  <email@address.tld> 1138474660 +0100
3181  */
3182 static void
3183 parse_author_line(char *ident, const char **author, struct time *time)
3185         char *nameend = strchr(ident, '<');
3186         char *emailend = strchr(ident, '>');
3188         if (nameend && emailend)
3189                 *nameend = *emailend = 0;
3190         ident = chomp_string(ident);
3191         if (!*ident) {
3192                 if (nameend)
3193                         ident = chomp_string(nameend + 1);
3194                 if (!*ident)
3195                         ident = "Unknown";
3196         }
3198         *author = get_author(ident);
3200         /* Parse epoch and timezone */
3201         if (emailend && emailend[1] == ' ') {
3202                 char *secs = emailend + 2;
3203                 char *zone = strchr(secs, ' ');
3205                 parse_timesec(time, secs);
3207                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3208                         parse_timezone(time, zone + 1);
3209         }
3212 /*
3213  * Pager backend
3214  */
3216 static bool
3217 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3219         if (opt_line_number && draw_lineno(view, lineno))
3220                 return TRUE;
3222         draw_text(view, line->type, line->data);
3223         return TRUE;
3226 static bool
3227 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3229         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3230         char ref[SIZEOF_STR];
3232         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3233                 return TRUE;
3235         /* This is the only fatal call, since it can "corrupt" the buffer. */
3236         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3237                 return FALSE;
3239         return TRUE;
3242 static void
3243 add_pager_refs(struct view *view, struct line *line)
3245         char buf[SIZEOF_STR];
3246         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3247         struct ref_list *list;
3248         size_t bufpos = 0, i;
3249         const char *sep = "Refs: ";
3250         bool is_tag = FALSE;
3252         assert(line->type == LINE_COMMIT);
3254         list = get_ref_list(commit_id);
3255         if (!list) {
3256                 if (view->type == VIEW_DIFF)
3257                         goto try_add_describe_ref;
3258                 return;
3259         }
3261         for (i = 0; i < list->size; i++) {
3262                 struct ref *ref = list->refs[i];
3263                 const char *fmt = ref->tag    ? "%s[%s]" :
3264                                   ref->remote ? "%s<%s>" : "%s%s";
3266                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3267                         return;
3268                 sep = ", ";
3269                 if (ref->tag)
3270                         is_tag = TRUE;
3271         }
3273         if (!is_tag && view->type == VIEW_DIFF) {
3274 try_add_describe_ref:
3275                 /* Add <tag>-g<commit_id> "fake" reference. */
3276                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3277                         return;
3278         }
3280         if (bufpos == 0)
3281                 return;
3283         add_line_text(view, buf, LINE_PP_REFS);
3286 static bool
3287 pager_read(struct view *view, char *data)
3289         struct line *line;
3291         if (!data)
3292                 return TRUE;
3294         line = add_line_text(view, data, get_line_type(data));
3295         if (!line)
3296                 return FALSE;
3298         if (line->type == LINE_COMMIT &&
3299             (view->type == VIEW_DIFF ||
3300              view->type == VIEW_LOG))
3301                 add_pager_refs(view, line);
3303         return TRUE;
3306 static enum request
3307 pager_request(struct view *view, enum request request, struct line *line)
3309         int split = 0;
3311         if (request != REQ_ENTER)
3312                 return request;
3314         if (line->type == LINE_COMMIT &&
3315            (view->type == VIEW_LOG ||
3316             view->type == VIEW_PAGER)) {
3317                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3318                 split = 1;
3319         }
3321         /* Always scroll the view even if it was split. That way
3322          * you can use Enter to scroll through the log view and
3323          * split open each commit diff. */
3324         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3326         /* FIXME: A minor workaround. Scrolling the view will call report("")
3327          * but if we are scrolling a non-current view this won't properly
3328          * update the view title. */
3329         if (split)
3330                 update_view_title(view);
3332         return REQ_NONE;
3335 static bool
3336 pager_grep(struct view *view, struct line *line)
3338         const char *text[] = { line->data, NULL };
3340         return grep_text(view, text);
3343 static void
3344 pager_select(struct view *view, struct line *line)
3346         if (line->type == LINE_COMMIT) {
3347                 char *text = (char *)line->data + STRING_SIZE("commit ");
3349                 if (view->type != VIEW_PAGER)
3350                         string_copy_rev(view->ref, text);
3351                 string_copy_rev(ref_commit, text);
3352         }
3355 static struct view_ops pager_ops = {
3356         "line",
3357         view_open,
3358         pager_read,
3359         pager_draw,
3360         pager_request,
3361         pager_grep,
3362         pager_select,
3363 };
3365 static bool
3366 log_open(struct view *view, enum open_flags flags)
3368         static const char *log_argv[] = {
3369                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3370         };
3372         return begin_update(view, NULL, log_argv, flags);
3375 static enum request
3376 log_request(struct view *view, enum request request, struct line *line)
3378         switch (request) {
3379         case REQ_REFRESH:
3380                 load_refs();
3381                 refresh_view(view);
3382                 return REQ_NONE;
3383         default:
3384                 return pager_request(view, request, line);
3385         }
3388 static struct view_ops log_ops = {
3389         "line",
3390         log_open,
3391         pager_read,
3392         pager_draw,
3393         log_request,
3394         pager_grep,
3395         pager_select,
3396 };
3398 static bool
3399 diff_open(struct view *view, enum open_flags flags)
3401         static const char *diff_argv[] = {
3402                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3403                         "--patch-with-stat", "--find-copies-harder", "-C",
3404                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3405         };
3407         return begin_update(view, NULL, diff_argv, flags);
3410 static bool
3411 diff_read(struct view *view, char *data)
3413         if (!data) {
3414                 /* Fall back to retry if no diff will be shown. */
3415                 if (view->lines == 0 && opt_file_argv) {
3416                         int pos = argv_size(view->argv)
3417                                 - argv_size(opt_file_argv) - 1;
3419                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3420                                 for (; view->argv[pos]; pos++) {
3421                                         free((void *) view->argv[pos]);
3422                                         view->argv[pos] = NULL;
3423                                 }
3425                                 if (view->pipe)
3426                                         io_done(view->pipe);
3427                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3428                                         return FALSE;
3429                         }
3430                 }
3431                 return TRUE;
3432         }
3434         return pager_read(view, data);
3437 static struct view_ops diff_ops = {
3438         "line",
3439         diff_open,
3440         diff_read,
3441         pager_draw,
3442         pager_request,
3443         pager_grep,
3444         pager_select,
3445 };
3447 /*
3448  * Help backend
3449  */
3451 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
3453 static bool
3454 help_open_keymap_title(struct view *view, enum keymap keymap)
3456         struct line *line;
3458         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3459                                help_keymap_hidden[keymap] ? '+' : '-',
3460                                enum_name(keymap_map[keymap]));
3461         if (line)
3462                 line->other = keymap;
3464         return help_keymap_hidden[keymap];
3467 static void
3468 help_open_keymap(struct view *view, enum keymap keymap)
3470         const char *group = NULL;
3471         char buf[SIZEOF_STR];
3472         size_t bufpos;
3473         bool add_title = TRUE;
3474         int i;
3476         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3477                 const char *key = NULL;
3479                 if (req_info[i].request == REQ_NONE)
3480                         continue;
3482                 if (!req_info[i].request) {
3483                         group = req_info[i].help;
3484                         continue;
3485                 }
3487                 key = get_keys(keymap, req_info[i].request, TRUE);
3488                 if (!key || !*key)
3489                         continue;
3491                 if (add_title && help_open_keymap_title(view, keymap))
3492                         return;
3493                 add_title = FALSE;
3495                 if (group) {
3496                         add_line_text(view, group, LINE_HELP_GROUP);
3497                         group = NULL;
3498                 }
3500                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3501                                 enum_name(req_info[i]), req_info[i].help);
3502         }
3504         group = "External commands:";
3506         for (i = 0; i < run_requests; i++) {
3507                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3508                 const char *key;
3509                 int argc;
3511                 if (!req || req->keymap != keymap)
3512                         continue;
3514                 key = get_key_name(req->key);
3515                 if (!*key)
3516                         key = "(no key defined)";
3518                 if (add_title && help_open_keymap_title(view, keymap))
3519                         return;
3520                 if (group) {
3521                         add_line_text(view, group, LINE_HELP_GROUP);
3522                         group = NULL;
3523                 }
3525                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3526                         if (!string_format_from(buf, &bufpos, "%s%s",
3527                                                 argc ? " " : "", req->argv[argc]))
3528                                 return;
3530                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3531         }
3534 static bool
3535 help_open(struct view *view, enum open_flags flags)
3537         enum keymap keymap;
3539         reset_view(view);
3540         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3541         add_line_text(view, "", LINE_DEFAULT);
3543         for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
3544                 help_open_keymap(view, keymap);
3546         return TRUE;
3549 static enum request
3550 help_request(struct view *view, enum request request, struct line *line)
3552         switch (request) {
3553         case REQ_ENTER:
3554                 if (line->type == LINE_HELP_KEYMAP) {
3555                         help_keymap_hidden[line->other] =
3556                                 !help_keymap_hidden[line->other];
3557                         refresh_view(view);
3558                 }
3560                 return REQ_NONE;
3561         default:
3562                 return pager_request(view, request, line);
3563         }
3566 static struct view_ops help_ops = {
3567         "line",
3568         help_open,
3569         NULL,
3570         pager_draw,
3571         help_request,
3572         pager_grep,
3573         pager_select,
3574 };
3577 /*
3578  * Tree backend
3579  */
3581 struct tree_stack_entry {
3582         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3583         unsigned long lineno;           /* Line number to restore */
3584         char *name;                     /* Position of name in opt_path */
3585 };
3587 /* The top of the path stack. */
3588 static struct tree_stack_entry *tree_stack = NULL;
3589 unsigned long tree_lineno = 0;
3591 static void
3592 pop_tree_stack_entry(void)
3594         struct tree_stack_entry *entry = tree_stack;
3596         tree_lineno = entry->lineno;
3597         entry->name[0] = 0;
3598         tree_stack = entry->prev;
3599         free(entry);
3602 static void
3603 push_tree_stack_entry(const char *name, unsigned long lineno)
3605         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3606         size_t pathlen = strlen(opt_path);
3608         if (!entry)
3609                 return;
3611         entry->prev = tree_stack;
3612         entry->name = opt_path + pathlen;
3613         tree_stack = entry;
3615         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3616                 pop_tree_stack_entry();
3617                 return;
3618         }
3620         /* Move the current line to the first tree entry. */
3621         tree_lineno = 1;
3622         entry->lineno = lineno;
3625 /* Parse output from git-ls-tree(1):
3626  *
3627  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3628  */
3630 #define SIZEOF_TREE_ATTR \
3631         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3633 #define SIZEOF_TREE_MODE \
3634         STRING_SIZE("100644 ")
3636 #define TREE_ID_OFFSET \
3637         STRING_SIZE("100644 blob ")
3639 struct tree_entry {
3640         char id[SIZEOF_REV];
3641         mode_t mode;
3642         struct time time;               /* Date from the author ident. */
3643         const char *author;             /* Author of the commit. */
3644         char name[1];
3645 };
3647 static const char *
3648 tree_path(const struct line *line)
3650         return ((struct tree_entry *) line->data)->name;
3653 static int
3654 tree_compare_entry(const struct line *line1, const struct line *line2)
3656         if (line1->type != line2->type)
3657                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3658         return strcmp(tree_path(line1), tree_path(line2));
3661 static const enum sort_field tree_sort_fields[] = {
3662         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3663 };
3664 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3666 static int
3667 tree_compare(const void *l1, const void *l2)
3669         const struct line *line1 = (const struct line *) l1;
3670         const struct line *line2 = (const struct line *) l2;
3671         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3672         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3674         if (line1->type == LINE_TREE_HEAD)
3675                 return -1;
3676         if (line2->type == LINE_TREE_HEAD)
3677                 return 1;
3679         switch (get_sort_field(tree_sort_state)) {
3680         case ORDERBY_DATE:
3681                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3683         case ORDERBY_AUTHOR:
3684                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3686         case ORDERBY_NAME:
3687         default:
3688                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3689         }
3693 static struct line *
3694 tree_entry(struct view *view, enum line_type type, const char *path,
3695            const char *mode, const char *id)
3697         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3698         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3700         if (!entry || !line) {
3701                 free(entry);
3702                 return NULL;
3703         }
3705         strncpy(entry->name, path, strlen(path));
3706         if (mode)
3707                 entry->mode = strtoul(mode, NULL, 8);
3708         if (id)
3709                 string_copy_rev(entry->id, id);
3711         return line;
3714 static bool
3715 tree_read_date(struct view *view, char *text, bool *read_date)
3717         static const char *author_name;
3718         static struct time author_time;
3720         if (!text && *read_date) {
3721                 *read_date = FALSE;
3722                 return TRUE;
3724         } else if (!text) {
3725                 /* Find next entry to process */
3726                 const char *log_file[] = {
3727                         "git", "log", "--no-color", "--pretty=raw",
3728                                 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3729                 };
3731                 if (!view->lines) {
3732                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3733                         report("Tree is empty");
3734                         return TRUE;
3735                 }
3737                 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3738                         report("Failed to load tree data");
3739                         return TRUE;
3740                 }
3742                 *read_date = TRUE;
3743                 return FALSE;
3745         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3746                 parse_author_line(text + STRING_SIZE("author "),
3747                                   &author_name, &author_time);
3749         } else if (*text == ':') {
3750                 char *pos;
3751                 size_t annotated = 1;
3752                 size_t i;
3754                 pos = strchr(text, '\t');
3755                 if (!pos)
3756                         return TRUE;
3757                 text = pos + 1;
3758                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3759                         text += strlen(opt_path);
3760                 pos = strchr(text, '/');
3761                 if (pos)
3762                         *pos = 0;
3764                 for (i = 1; i < view->lines; i++) {
3765                         struct line *line = &view->line[i];
3766                         struct tree_entry *entry = line->data;
3768                         annotated += !!entry->author;
3769                         if (entry->author || strcmp(entry->name, text))
3770                                 continue;
3772                         entry->author = author_name;
3773                         entry->time = author_time;
3774                         line->dirty = 1;
3775                         break;
3776                 }
3778                 if (annotated == view->lines)
3779                         io_kill(view->pipe);
3780         }
3781         return TRUE;
3784 static bool
3785 tree_read(struct view *view, char *text)
3787         static bool read_date = FALSE;
3788         struct tree_entry *data;
3789         struct line *entry, *line;
3790         enum line_type type;
3791         size_t textlen = text ? strlen(text) : 0;
3792         char *path = text + SIZEOF_TREE_ATTR;
3794         if (read_date || !text)
3795                 return tree_read_date(view, text, &read_date);
3797         if (textlen <= SIZEOF_TREE_ATTR)
3798                 return FALSE;
3799         if (view->lines == 0 &&
3800             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3801                 return FALSE;
3803         /* Strip the path part ... */
3804         if (*opt_path) {
3805                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3806                 size_t striplen = strlen(opt_path);
3808                 if (pathlen > striplen)
3809                         memmove(path, path + striplen,
3810                                 pathlen - striplen + 1);
3812                 /* Insert "link" to parent directory. */
3813                 if (view->lines == 1 &&
3814                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3815                         return FALSE;
3816         }
3818         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3819         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3820         if (!entry)
3821                 return FALSE;
3822         data = entry->data;
3824         /* Skip "Directory ..." and ".." line. */
3825         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3826                 if (tree_compare_entry(line, entry) <= 0)
3827                         continue;
3829                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3831                 line->data = data;
3832                 line->type = type;
3833                 for (; line <= entry; line++)
3834                         line->dirty = line->cleareol = 1;
3835                 return TRUE;
3836         }
3838         if (tree_lineno > view->lineno) {
3839                 view->lineno = tree_lineno;
3840                 tree_lineno = 0;
3841         }
3843         return TRUE;
3846 static bool
3847 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3849         struct tree_entry *entry = line->data;
3851         if (line->type == LINE_TREE_HEAD) {
3852                 if (draw_text(view, line->type, "Directory path /"))
3853                         return TRUE;
3854         } else {
3855                 if (draw_mode(view, entry->mode))
3856                         return TRUE;
3858                 if (draw_author(view, entry->author))
3859                         return TRUE;
3861                 if (draw_date(view, &entry->time))
3862                         return TRUE;
3863         }
3865         draw_text(view, line->type, entry->name);
3866         return TRUE;
3869 static void
3870 open_blob_editor(const char *id)
3872         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3873         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3874         int fd = mkstemp(file);
3876         if (fd == -1)
3877                 report("Failed to create temporary file");
3878         else if (!io_run_append(blob_argv, fd))
3879                 report("Failed to save blob data to file");
3880         else
3881                 open_editor(file);
3882         if (fd != -1)
3883                 unlink(file);
3886 static enum request
3887 tree_request(struct view *view, enum request request, struct line *line)
3889         enum open_flags flags;
3890         struct tree_entry *entry = line->data;
3892         switch (request) {
3893         case REQ_VIEW_BLAME:
3894                 if (line->type != LINE_TREE_FILE) {
3895                         report("Blame only supported for files");
3896                         return REQ_NONE;
3897                 }
3899                 string_copy(opt_ref, view->vid);
3900                 return request;
3902         case REQ_EDIT:
3903                 if (line->type != LINE_TREE_FILE) {
3904                         report("Edit only supported for files");
3905                 } else if (!is_head_commit(view->vid)) {
3906                         open_blob_editor(entry->id);
3907                 } else {
3908                         open_editor(opt_file);
3909                 }
3910                 return REQ_NONE;
3912         case REQ_TOGGLE_SORT_FIELD:
3913         case REQ_TOGGLE_SORT_ORDER:
3914                 sort_view(view, request, &tree_sort_state, tree_compare);
3915                 return REQ_NONE;
3917         case REQ_PARENT:
3918                 if (!*opt_path) {
3919                         /* quit view if at top of tree */
3920                         return REQ_VIEW_CLOSE;
3921                 }
3922                 /* fake 'cd  ..' */
3923                 line = &view->line[1];
3924                 break;
3926         case REQ_ENTER:
3927                 break;
3929         default:
3930                 return request;
3931         }
3933         /* Cleanup the stack if the tree view is at a different tree. */
3934         while (!*opt_path && tree_stack)
3935                 pop_tree_stack_entry();
3937         switch (line->type) {
3938         case LINE_TREE_DIR:
3939                 /* Depending on whether it is a subdirectory or parent link
3940                  * mangle the path buffer. */
3941                 if (line == &view->line[1] && *opt_path) {
3942                         pop_tree_stack_entry();
3944                 } else {
3945                         const char *basename = tree_path(line);
3947                         push_tree_stack_entry(basename, view->lineno);
3948                 }
3950                 /* Trees and subtrees share the same ID, so they are not not
3951                  * unique like blobs. */
3952                 flags = OPEN_RELOAD;
3953                 request = REQ_VIEW_TREE;
3954                 break;
3956         case LINE_TREE_FILE:
3957                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3958                 request = REQ_VIEW_BLOB;
3959                 break;
3961         default:
3962                 return REQ_NONE;
3963         }
3965         open_view(view, request, flags);
3966         if (request == REQ_VIEW_TREE)
3967                 view->lineno = tree_lineno;
3969         return REQ_NONE;
3972 static bool
3973 tree_grep(struct view *view, struct line *line)
3975         struct tree_entry *entry = line->data;
3976         const char *text[] = {
3977                 entry->name,
3978                 opt_author ? entry->author : "",
3979                 mkdate(&entry->time, opt_date),
3980                 NULL
3981         };
3983         return grep_text(view, text);
3986 static void
3987 tree_select(struct view *view, struct line *line)
3989         struct tree_entry *entry = line->data;
3991         if (line->type == LINE_TREE_FILE) {
3992                 string_copy_rev(ref_blob, entry->id);
3993                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3995         } else if (line->type != LINE_TREE_DIR) {
3996                 return;
3997         }
3999         string_copy_rev(view->ref, entry->id);
4002 static bool
4003 tree_open(struct view *view, enum open_flags flags)
4005         static const char *tree_argv[] = {
4006                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4007         };
4009         if (view->lines == 0 && opt_prefix[0]) {
4010                 char *pos = opt_prefix;
4012                 while (pos && *pos) {
4013                         char *end = strchr(pos, '/');
4015                         if (end)
4016                                 *end = 0;
4017                         push_tree_stack_entry(pos, 0);
4018                         pos = end;
4019                         if (end) {
4020                                 *end = '/';
4021                                 pos++;
4022                         }
4023                 }
4025         } else if (strcmp(view->vid, view->id)) {
4026                 opt_path[0] = 0;
4027         }
4029         return begin_update(view, opt_cdup, tree_argv, flags);
4032 static struct view_ops tree_ops = {
4033         "file",
4034         tree_open,
4035         tree_read,
4036         tree_draw,
4037         tree_request,
4038         tree_grep,
4039         tree_select,
4040 };
4042 static bool
4043 blob_open(struct view *view, enum open_flags flags)
4045         static const char *blob_argv[] = {
4046                 "git", "cat-file", "blob", "%(blob)", NULL
4047         };
4049         return begin_update(view, NULL, blob_argv, flags);
4052 static bool
4053 blob_read(struct view *view, char *line)
4055         if (!line)
4056                 return TRUE;
4057         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4060 static enum request
4061 blob_request(struct view *view, enum request request, struct line *line)
4063         switch (request) {
4064         case REQ_EDIT:
4065                 open_blob_editor(view->vid);
4066                 return REQ_NONE;
4067         default:
4068                 return pager_request(view, request, line);
4069         }
4072 static struct view_ops blob_ops = {
4073         "line",
4074         blob_open,
4075         blob_read,
4076         pager_draw,
4077         blob_request,
4078         pager_grep,
4079         pager_select,
4080 };
4082 /*
4083  * Blame backend
4084  *
4085  * Loading the blame view is a two phase job:
4086  *
4087  *  1. File content is read either using opt_file from the
4088  *     filesystem or using git-cat-file.
4089  *  2. Then blame information is incrementally added by
4090  *     reading output from git-blame.
4091  */
4093 struct blame_commit {
4094         char id[SIZEOF_REV];            /* SHA1 ID. */
4095         char title[128];                /* First line of the commit message. */
4096         const char *author;             /* Author of the commit. */
4097         struct time time;               /* Date from the author ident. */
4098         char filename[128];             /* Name of file. */
4099         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4100         char parent_filename[128];      /* Parent/previous name of file. */
4101 };
4103 struct blame {
4104         struct blame_commit *commit;
4105         unsigned long lineno;
4106         char text[1];
4107 };
4109 static bool
4110 blame_open(struct view *view, enum open_flags flags)
4112         const char *file_argv[] = { opt_cdup, opt_file , NULL };
4113         char path[SIZEOF_STR];
4114         size_t i;
4116         if (!view->prev && *opt_prefix) {
4117                 string_copy(path, opt_file);
4118                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4119                         return FALSE;
4120         }
4122         if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4123                 const char *blame_cat_file_argv[] = {
4124                         "git", "cat-file", "blob", path, NULL
4125                 };
4127                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4128                     !begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4129                         return FALSE;
4130         }
4132         /* First pass: remove multiple references to the same commit. */
4133         for (i = 0; i < view->lines; i++) {
4134                 struct blame *blame = view->line[i].data;
4136                 if (blame->commit && blame->commit->id[0])
4137                         blame->commit->id[0] = 0;
4138                 else
4139                         blame->commit = NULL;
4140         }
4142         /* Second pass: free existing references. */
4143         for (i = 0; i < view->lines; i++) {
4144                 struct blame *blame = view->line[i].data;
4146                 if (blame->commit)
4147                         free(blame->commit);
4148         }
4150         string_format(view->vid, "%s:%s", opt_ref, opt_file);
4151         string_format(view->ref, "%s ...", opt_file);
4153         return TRUE;
4156 static struct blame_commit *
4157 get_blame_commit(struct view *view, const char *id)
4159         size_t i;
4161         for (i = 0; i < view->lines; i++) {
4162                 struct blame *blame = view->line[i].data;
4164                 if (!blame->commit)
4165                         continue;
4167                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4168                         return blame->commit;
4169         }
4171         {
4172                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4174                 if (commit)
4175                         string_ncopy(commit->id, id, SIZEOF_REV);
4176                 return commit;
4177         }
4180 static bool
4181 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4183         const char *pos = *posref;
4185         *posref = NULL;
4186         pos = strchr(pos + 1, ' ');
4187         if (!pos || !isdigit(pos[1]))
4188                 return FALSE;
4189         *number = atoi(pos + 1);
4190         if (*number < min || *number > max)
4191                 return FALSE;
4193         *posref = pos;
4194         return TRUE;
4197 static struct blame_commit *
4198 parse_blame_commit(struct view *view, const char *text, int *blamed)
4200         struct blame_commit *commit;
4201         struct blame *blame;
4202         const char *pos = text + SIZEOF_REV - 2;
4203         size_t orig_lineno = 0;
4204         size_t lineno;
4205         size_t group;
4207         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4208                 return NULL;
4210         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4211             !parse_number(&pos, &lineno, 1, view->lines) ||
4212             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4213                 return NULL;
4215         commit = get_blame_commit(view, text);
4216         if (!commit)
4217                 return NULL;
4219         *blamed += group;
4220         while (group--) {
4221                 struct line *line = &view->line[lineno + group - 1];
4223                 blame = line->data;
4224                 blame->commit = commit;
4225                 blame->lineno = orig_lineno + group - 1;
4226                 line->dirty = 1;
4227         }
4229         return commit;
4232 static bool
4233 blame_read_file(struct view *view, const char *line, bool *read_file)
4235         if (!line) {
4236                 const char *blame_argv[] = {
4237                         "git", "blame", "%(blameargs)", "--incremental",
4238                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4239                 };
4241                 if (view->lines == 0 && !view->prev)
4242                         die("No blame exist for %s", view->vid);
4244                 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4245                         report("Failed to load blame data");
4246                         return TRUE;
4247                 }
4249                 *read_file = FALSE;
4250                 return FALSE;
4252         } else {
4253                 size_t linelen = strlen(line);
4254                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4256                 if (!blame)
4257                         return FALSE;
4259                 blame->commit = NULL;
4260                 strncpy(blame->text, line, linelen);
4261                 blame->text[linelen] = 0;
4262                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4263         }
4266 static bool
4267 match_blame_header(const char *name, char **line)
4269         size_t namelen = strlen(name);
4270         bool matched = !strncmp(name, *line, namelen);
4272         if (matched)
4273                 *line += namelen;
4275         return matched;
4278 static bool
4279 blame_read(struct view *view, char *line)
4281         static struct blame_commit *commit = NULL;
4282         static int blamed = 0;
4283         static bool read_file = TRUE;
4285         if (read_file)
4286                 return blame_read_file(view, line, &read_file);
4288         if (!line) {
4289                 /* Reset all! */
4290                 commit = NULL;
4291                 blamed = 0;
4292                 read_file = TRUE;
4293                 string_format(view->ref, "%s", view->vid);
4294                 if (view_is_displayed(view)) {
4295                         update_view_title(view);
4296                         redraw_view_from(view, 0);
4297                 }
4298                 return TRUE;
4299         }
4301         if (!commit) {
4302                 commit = parse_blame_commit(view, line, &blamed);
4303                 string_format(view->ref, "%s %2d%%", view->vid,
4304                               view->lines ? blamed * 100 / view->lines : 0);
4306         } else if (match_blame_header("author ", &line)) {
4307                 commit->author = get_author(line);
4309         } else if (match_blame_header("author-time ", &line)) {
4310                 parse_timesec(&commit->time, line);
4312         } else if (match_blame_header("author-tz ", &line)) {
4313                 parse_timezone(&commit->time, line);
4315         } else if (match_blame_header("summary ", &line)) {
4316                 string_ncopy(commit->title, line, strlen(line));
4318         } else if (match_blame_header("previous ", &line)) {
4319                 if (strlen(line) <= SIZEOF_REV)
4320                         return FALSE;
4321                 string_copy_rev(commit->parent_id, line);
4322                 line += SIZEOF_REV;
4323                 string_ncopy(commit->parent_filename, line, strlen(line));
4325         } else if (match_blame_header("filename ", &line)) {
4326                 string_ncopy(commit->filename, line, strlen(line));
4327                 commit = NULL;
4328         }
4330         return TRUE;
4333 static bool
4334 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4336         struct blame *blame = line->data;
4337         struct time *time = NULL;
4338         const char *id = NULL, *author = NULL;
4340         if (blame->commit && *blame->commit->filename) {
4341                 id = blame->commit->id;
4342                 author = blame->commit->author;
4343                 time = &blame->commit->time;
4344         }
4346         if (draw_date(view, time))
4347                 return TRUE;
4349         if (draw_author(view, author))
4350                 return TRUE;
4352         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4353                 return TRUE;
4355         if (draw_lineno(view, lineno))
4356                 return TRUE;
4358         draw_text(view, LINE_DEFAULT, blame->text);
4359         return TRUE;
4362 static bool
4363 check_blame_commit(struct blame *blame, bool check_null_id)
4365         if (!blame->commit)
4366                 report("Commit data not loaded yet");
4367         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4368                 report("No commit exist for the selected line");
4369         else
4370                 return TRUE;
4371         return FALSE;
4374 static void
4375 setup_blame_parent_line(struct view *view, struct blame *blame)
4377         char from[SIZEOF_REF + SIZEOF_STR];
4378         char to[SIZEOF_REF + SIZEOF_STR];
4379         const char *diff_tree_argv[] = {
4380                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4381                         "-U0", from, to, "--", NULL
4382         };
4383         struct io io;
4384         int parent_lineno = -1;
4385         int blamed_lineno = -1;
4386         char *line;
4388         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4389             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4390             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4391                 return;
4393         while ((line = io_get(&io, '\n', TRUE))) {
4394                 if (*line == '@') {
4395                         char *pos = strchr(line, '+');
4397                         parent_lineno = atoi(line + 4);
4398                         if (pos)
4399                                 blamed_lineno = atoi(pos + 1);
4401                 } else if (*line == '+' && parent_lineno != -1) {
4402                         if (blame->lineno == blamed_lineno - 1 &&
4403                             !strcmp(blame->text, line + 1)) {
4404                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4405                                 break;
4406                         }
4407                         blamed_lineno++;
4408                 }
4409         }
4411         io_done(&io);
4414 static enum request
4415 blame_request(struct view *view, enum request request, struct line *line)
4417         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4418         struct blame *blame = line->data;
4420         switch (request) {
4421         case REQ_VIEW_BLAME:
4422                 if (check_blame_commit(blame, TRUE)) {
4423                         string_copy(opt_ref, blame->commit->id);
4424                         string_copy(opt_file, blame->commit->filename);
4425                         if (blame->lineno)
4426                                 view->lineno = blame->lineno;
4427                         refresh_view(view);
4428                 }
4429                 break;
4431         case REQ_PARENT:
4432                 if (!check_blame_commit(blame, TRUE))
4433                         break;
4434                 if (!*blame->commit->parent_id) {
4435                         report("The selected commit has no parents");
4436                 } else {
4437                         string_copy_rev(opt_ref, blame->commit->parent_id);
4438                         string_copy(opt_file, blame->commit->parent_filename);
4439                         setup_blame_parent_line(view, blame);
4440                         refresh_view(view);
4441                 }
4442                 break;
4444         case REQ_ENTER:
4445                 if (!check_blame_commit(blame, FALSE))
4446                         break;
4448                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4449                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4450                         break;
4452                 if (!strcmp(blame->commit->id, NULL_ID)) {
4453                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4454                         const char *diff_index_argv[] = {
4455                                 "git", "diff-index", "--root", "--patch-with-stat",
4456                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4457                         };
4459                         if (!*blame->commit->parent_id) {
4460                                 diff_index_argv[1] = "diff";
4461                                 diff_index_argv[2] = "--no-color";
4462                                 diff_index_argv[6] = "--";
4463                                 diff_index_argv[7] = "/dev/null";
4464                         }
4466                         open_argv(view, diff, diff_index_argv, NULL, flags);
4467                 } else {
4468                         open_view(view, REQ_VIEW_DIFF, flags);
4469                 }
4470                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4471                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4472                 break;
4474         default:
4475                 return request;
4476         }
4478         return REQ_NONE;
4481 static bool
4482 blame_grep(struct view *view, struct line *line)
4484         struct blame *blame = line->data;
4485         struct blame_commit *commit = blame->commit;
4486         const char *text[] = {
4487                 blame->text,
4488                 commit ? commit->title : "",
4489                 commit ? commit->id : "",
4490                 commit && opt_author ? commit->author : "",
4491                 commit ? mkdate(&commit->time, opt_date) : "",
4492                 NULL
4493         };
4495         return grep_text(view, text);
4498 static void
4499 blame_select(struct view *view, struct line *line)
4501         struct blame *blame = line->data;
4502         struct blame_commit *commit = blame->commit;
4504         if (!commit)
4505                 return;
4507         if (!strcmp(commit->id, NULL_ID))
4508                 string_ncopy(ref_commit, "HEAD", 4);
4509         else
4510                 string_copy_rev(ref_commit, commit->id);
4513 static struct view_ops blame_ops = {
4514         "line",
4515         blame_open,
4516         blame_read,
4517         blame_draw,
4518         blame_request,
4519         blame_grep,
4520         blame_select,
4521 };
4523 /*
4524  * Branch backend
4525  */
4527 struct branch {
4528         const char *author;             /* Author of the last commit. */
4529         struct time time;               /* Date of the last activity. */
4530         const struct ref *ref;          /* Name and commit ID information. */
4531 };
4533 static const struct ref branch_all;
4535 static const enum sort_field branch_sort_fields[] = {
4536         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4537 };
4538 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4540 static int
4541 branch_compare(const void *l1, const void *l2)
4543         const struct branch *branch1 = ((const struct line *) l1)->data;
4544         const struct branch *branch2 = ((const struct line *) l2)->data;
4546         switch (get_sort_field(branch_sort_state)) {
4547         case ORDERBY_DATE:
4548                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4550         case ORDERBY_AUTHOR:
4551                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4553         case ORDERBY_NAME:
4554         default:
4555                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4556         }
4559 static bool
4560 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4562         struct branch *branch = line->data;
4563         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4565         if (draw_date(view, &branch->time))
4566                 return TRUE;
4568         if (draw_author(view, branch->author))
4569                 return TRUE;
4571         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4572         return TRUE;
4575 static enum request
4576 branch_request(struct view *view, enum request request, struct line *line)
4578         struct branch *branch = line->data;
4580         switch (request) {
4581         case REQ_REFRESH:
4582                 load_refs();
4583                 refresh_view(view);
4584                 return REQ_NONE;
4586         case REQ_TOGGLE_SORT_FIELD:
4587         case REQ_TOGGLE_SORT_ORDER:
4588                 sort_view(view, request, &branch_sort_state, branch_compare);
4589                 return REQ_NONE;
4591         case REQ_ENTER:
4592         {
4593                 const struct ref *ref = branch->ref;
4594                 const char *all_branches_argv[] = {
4595                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4596                               "--topo-order",
4597                               ref == &branch_all ? "--all" : ref->name, NULL
4598                 };
4599                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4601                 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4602                 return REQ_NONE;
4603         }
4604         default:
4605                 return request;
4606         }
4609 static bool
4610 branch_read(struct view *view, char *line)
4612         static char id[SIZEOF_REV];
4613         struct branch *reference;
4614         size_t i;
4616         if (!line)
4617                 return TRUE;
4619         switch (get_line_type(line)) {
4620         case LINE_COMMIT:
4621                 string_copy_rev(id, line + STRING_SIZE("commit "));
4622                 return TRUE;
4624         case LINE_AUTHOR:
4625                 for (i = 0, reference = NULL; i < view->lines; i++) {
4626                         struct branch *branch = view->line[i].data;
4628                         if (strcmp(branch->ref->id, id))
4629                                 continue;
4631                         view->line[i].dirty = TRUE;
4632                         if (reference) {
4633                                 branch->author = reference->author;
4634                                 branch->time = reference->time;
4635                                 continue;
4636                         }
4638                         parse_author_line(line + STRING_SIZE("author "),
4639                                           &branch->author, &branch->time);
4640                         reference = branch;
4641                 }
4642                 return TRUE;
4644         default:
4645                 return TRUE;
4646         }
4650 static bool
4651 branch_open_visitor(void *data, const struct ref *ref)
4653         struct view *view = data;
4654         struct branch *branch;
4656         if (ref->tag || ref->ltag || ref->remote)
4657                 return TRUE;
4659         branch = calloc(1, sizeof(*branch));
4660         if (!branch)
4661                 return FALSE;
4663         branch->ref = ref;
4664         return !!add_line_data(view, branch, LINE_DEFAULT);
4667 static bool
4668 branch_open(struct view *view, enum open_flags flags)
4670         const char *branch_log[] = {
4671                 "git", "log", "--no-color", "--pretty=raw",
4672                         "--simplify-by-decoration", "--all", NULL
4673         };
4675         if (!begin_update(view, NULL, branch_log, flags)) {
4676                 report("Failed to load branch data");
4677                 return TRUE;
4678         }
4680         branch_open_visitor(view, &branch_all);
4681         foreach_ref(branch_open_visitor, view);
4682         view->p_restore = TRUE;
4684         return TRUE;
4687 static bool
4688 branch_grep(struct view *view, struct line *line)
4690         struct branch *branch = line->data;
4691         const char *text[] = {
4692                 branch->ref->name,
4693                 branch->author,
4694                 NULL
4695         };
4697         return grep_text(view, text);
4700 static void
4701 branch_select(struct view *view, struct line *line)
4703         struct branch *branch = line->data;
4705         string_copy_rev(view->ref, branch->ref->id);
4706         string_copy_rev(ref_commit, branch->ref->id);
4707         string_copy_rev(ref_head, branch->ref->id);
4708         string_copy_rev(ref_branch, branch->ref->name);
4711 static struct view_ops branch_ops = {
4712         "branch",
4713         branch_open,
4714         branch_read,
4715         branch_draw,
4716         branch_request,
4717         branch_grep,
4718         branch_select,
4719 };
4721 /*
4722  * Status backend
4723  */
4725 struct status {
4726         char status;
4727         struct {
4728                 mode_t mode;
4729                 char rev[SIZEOF_REV];
4730                 char name[SIZEOF_STR];
4731         } old;
4732         struct {
4733                 mode_t mode;
4734                 char rev[SIZEOF_REV];
4735                 char name[SIZEOF_STR];
4736         } new;
4737 };
4739 static char status_onbranch[SIZEOF_STR];
4740 static struct status stage_status;
4741 static enum line_type stage_line_type;
4742 static size_t stage_chunks;
4743 static int *stage_chunk;
4745 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4747 /* This should work even for the "On branch" line. */
4748 static inline bool
4749 status_has_none(struct view *view, struct line *line)
4751         return line < view->line + view->lines && !line[1].data;
4754 /* Get fields from the diff line:
4755  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4756  */
4757 static inline bool
4758 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4760         const char *old_mode = buf +  1;
4761         const char *new_mode = buf +  8;
4762         const char *old_rev  = buf + 15;
4763         const char *new_rev  = buf + 56;
4764         const char *status   = buf + 97;
4766         if (bufsize < 98 ||
4767             old_mode[-1] != ':' ||
4768             new_mode[-1] != ' ' ||
4769             old_rev[-1]  != ' ' ||
4770             new_rev[-1]  != ' ' ||
4771             status[-1]   != ' ')
4772                 return FALSE;
4774         file->status = *status;
4776         string_copy_rev(file->old.rev, old_rev);
4777         string_copy_rev(file->new.rev, new_rev);
4779         file->old.mode = strtoul(old_mode, NULL, 8);
4780         file->new.mode = strtoul(new_mode, NULL, 8);
4782         file->old.name[0] = file->new.name[0] = 0;
4784         return TRUE;
4787 static bool
4788 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4790         struct status *unmerged = NULL;
4791         char *buf;
4792         struct io io;
4794         if (!io_run(&io, IO_RD, opt_cdup, argv))
4795                 return FALSE;
4797         add_line_data(view, NULL, type);
4799         while ((buf = io_get(&io, 0, TRUE))) {
4800                 struct status *file = unmerged;
4802                 if (!file) {
4803                         file = calloc(1, sizeof(*file));
4804                         if (!file || !add_line_data(view, file, type))
4805                                 goto error_out;
4806                 }
4808                 /* Parse diff info part. */
4809                 if (status) {
4810                         file->status = status;
4811                         if (status == 'A')
4812                                 string_copy(file->old.rev, NULL_ID);
4814                 } else if (!file->status || file == unmerged) {
4815                         if (!status_get_diff(file, buf, strlen(buf)))
4816                                 goto error_out;
4818                         buf = io_get(&io, 0, TRUE);
4819                         if (!buf)
4820                                 break;
4822                         /* Collapse all modified entries that follow an
4823                          * associated unmerged entry. */
4824                         if (unmerged == file) {
4825                                 unmerged->status = 'U';
4826                                 unmerged = NULL;
4827                         } else if (file->status == 'U') {
4828                                 unmerged = file;
4829                         }
4830                 }
4832                 /* Grab the old name for rename/copy. */
4833                 if (!*file->old.name &&
4834                     (file->status == 'R' || file->status == 'C')) {
4835                         string_ncopy(file->old.name, buf, strlen(buf));
4837                         buf = io_get(&io, 0, TRUE);
4838                         if (!buf)
4839                                 break;
4840                 }
4842                 /* git-ls-files just delivers a NUL separated list of
4843                  * file names similar to the second half of the
4844                  * git-diff-* output. */
4845                 string_ncopy(file->new.name, buf, strlen(buf));
4846                 if (!*file->old.name)
4847                         string_copy(file->old.name, file->new.name);
4848                 file = NULL;
4849         }
4851         if (io_error(&io)) {
4852 error_out:
4853                 io_done(&io);
4854                 return FALSE;
4855         }
4857         if (!view->line[view->lines - 1].data)
4858                 add_line_data(view, NULL, LINE_STAT_NONE);
4860         io_done(&io);
4861         return TRUE;
4864 /* Don't show unmerged entries in the staged section. */
4865 static const char *status_diff_index_argv[] = {
4866         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4867                              "--cached", "-M", "HEAD", NULL
4868 };
4870 static const char *status_diff_files_argv[] = {
4871         "git", "diff-files", "-z", NULL
4872 };
4874 static const char *status_list_other_argv[] = {
4875         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4876 };
4878 static const char *status_list_no_head_argv[] = {
4879         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4880 };
4882 static const char *update_index_argv[] = {
4883         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4884 };
4886 /* Restore the previous line number to stay in the context or select a
4887  * line with something that can be updated. */
4888 static void
4889 status_restore(struct view *view)
4891         if (view->p_lineno >= view->lines)
4892                 view->p_lineno = view->lines - 1;
4893         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4894                 view->p_lineno++;
4895         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4896                 view->p_lineno--;
4898         /* If the above fails, always skip the "On branch" line. */
4899         if (view->p_lineno < view->lines)
4900                 view->lineno = view->p_lineno;
4901         else
4902                 view->lineno = 1;
4904         if (view->lineno < view->offset)
4905                 view->offset = view->lineno;
4906         else if (view->offset + view->height <= view->lineno)
4907                 view->offset = view->lineno - view->height + 1;
4909         view->p_restore = FALSE;
4912 static void
4913 status_update_onbranch(void)
4915         static const char *paths[][2] = {
4916                 { "rebase-apply/rebasing",      "Rebasing" },
4917                 { "rebase-apply/applying",      "Applying mailbox" },
4918                 { "rebase-apply/",              "Rebasing mailbox" },
4919                 { "rebase-merge/interactive",   "Interactive rebase" },
4920                 { "rebase-merge/",              "Rebase merge" },
4921                 { "MERGE_HEAD",                 "Merging" },
4922                 { "BISECT_LOG",                 "Bisecting" },
4923                 { "HEAD",                       "On branch" },
4924         };
4925         char buf[SIZEOF_STR];
4926         struct stat stat;
4927         int i;
4929         if (is_initial_commit()) {
4930                 string_copy(status_onbranch, "Initial commit");
4931                 return;
4932         }
4934         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4935                 char *head = opt_head;
4937                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4938                     lstat(buf, &stat) < 0)
4939                         continue;
4941                 if (!*opt_head) {
4942                         struct io io;
4944                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4945                             io_read_buf(&io, buf, sizeof(buf))) {
4946                                 head = buf;
4947                                 if (!prefixcmp(head, "refs/heads/"))
4948                                         head += STRING_SIZE("refs/heads/");
4949                         }
4950                 }
4952                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4953                         string_copy(status_onbranch, opt_head);
4954                 return;
4955         }
4957         string_copy(status_onbranch, "Not currently on any branch");
4960 /* First parse staged info using git-diff-index(1), then parse unstaged
4961  * info using git-diff-files(1), and finally untracked files using
4962  * git-ls-files(1). */
4963 static bool
4964 status_open(struct view *view, enum open_flags flags)
4966         reset_view(view);
4968         add_line_data(view, NULL, LINE_STAT_HEAD);
4969         status_update_onbranch();
4971         io_run_bg(update_index_argv);
4973         if (is_initial_commit()) {
4974                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4975                         return FALSE;
4976         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4977                 return FALSE;
4978         }
4980         if (!opt_untracked_dirs_content)
4981                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4983         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4984             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4985                 return FALSE;
4987         /* Restore the exact position or use the specialized restore
4988          * mode? */
4989         if (!view->p_restore)
4990                 status_restore(view);
4991         return TRUE;
4994 static bool
4995 status_draw(struct view *view, struct line *line, unsigned int lineno)
4997         struct status *status = line->data;
4998         enum line_type type;
4999         const char *text;
5001         if (!status) {
5002                 switch (line->type) {
5003                 case LINE_STAT_STAGED:
5004                         type = LINE_STAT_SECTION;
5005                         text = "Changes to be committed:";
5006                         break;
5008                 case LINE_STAT_UNSTAGED:
5009                         type = LINE_STAT_SECTION;
5010                         text = "Changed but not updated:";
5011                         break;
5013                 case LINE_STAT_UNTRACKED:
5014                         type = LINE_STAT_SECTION;
5015                         text = "Untracked files:";
5016                         break;
5018                 case LINE_STAT_NONE:
5019                         type = LINE_DEFAULT;
5020                         text = "  (no files)";
5021                         break;
5023                 case LINE_STAT_HEAD:
5024                         type = LINE_STAT_HEAD;
5025                         text = status_onbranch;
5026                         break;
5028                 default:
5029                         return FALSE;
5030                 }
5031         } else {
5032                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5034                 buf[0] = status->status;
5035                 if (draw_text(view, line->type, buf))
5036                         return TRUE;
5037                 type = LINE_DEFAULT;
5038                 text = status->new.name;
5039         }
5041         draw_text(view, type, text);
5042         return TRUE;
5045 static enum request
5046 status_enter(struct view *view, struct line *line)
5048         struct status *status = line->data;
5049         const char *oldpath = status ? status->old.name : NULL;
5050         /* Diffs for unmerged entries are empty when passing the new
5051          * path, so leave it empty. */
5052         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5053         const char *info;
5054         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5055         struct view *stage = VIEW(REQ_VIEW_STAGE);
5057         if (line->type == LINE_STAT_NONE ||
5058             (!status && line[1].type == LINE_STAT_NONE)) {
5059                 report("No file to diff");
5060                 return REQ_NONE;
5061         }
5063         switch (line->type) {
5064         case LINE_STAT_STAGED:
5065                 if (is_initial_commit()) {
5066                         const char *no_head_diff_argv[] = {
5067                                 "git", "diff", "--no-color", "--patch-with-stat",
5068                                         "--", "/dev/null", newpath, NULL
5069                         };
5071                         open_argv(view, stage, no_head_diff_argv, opt_cdup, flags); 
5072                 } else {
5073                         const char *index_show_argv[] = {
5074                                 "git", "diff-index", "--root", "--patch-with-stat",
5075                                         "-C", "-M", "--cached", "HEAD", "--",
5076                                         oldpath, newpath, NULL
5077                         };
5079                         open_argv(view, stage, index_show_argv, opt_cdup, flags);
5080                 }
5082                 if (status)
5083                         info = "Staged changes to %s";
5084                 else
5085                         info = "Staged changes";
5086                 break;
5088         case LINE_STAT_UNSTAGED:
5089         {
5090                 const char *files_show_argv[] = {
5091                         "git", "diff-files", "--root", "--patch-with-stat",
5092                                 "-C", "-M", "--", oldpath, newpath, NULL
5093                 };
5095                 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5096                 if (status)
5097                         info = "Unstaged changes to %s";
5098                 else
5099                         info = "Unstaged changes";
5100                 break;
5101         }
5102         case LINE_STAT_UNTRACKED:
5103                 if (!newpath) {
5104                         report("No file to show");
5105                         return REQ_NONE;
5106                 }
5108                 if (!suffixcmp(status->new.name, -1, "/")) {
5109                         report("Cannot display a directory");
5110                         return REQ_NONE;
5111                 }
5113                 open_file(view, stage, newpath, flags);
5114                 info = "Untracked file %s";
5115                 break;
5117         case LINE_STAT_HEAD:
5118                 return REQ_NONE;
5120         default:
5121                 die("line type %d not handled in switch", line->type);
5122         }
5124         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5125                 if (status) {
5126                         stage_status = *status;
5127                 } else {
5128                         memset(&stage_status, 0, sizeof(stage_status));
5129                 }
5131                 stage_line_type = line->type;
5132                 stage_chunks = 0;
5133                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5134         }
5136         return REQ_NONE;
5139 static bool
5140 status_exists(struct status *status, enum line_type type)
5142         struct view *view = VIEW(REQ_VIEW_STATUS);
5143         unsigned long lineno;
5145         for (lineno = 0; lineno < view->lines; lineno++) {
5146                 struct line *line = &view->line[lineno];
5147                 struct status *pos = line->data;
5149                 if (line->type != type)
5150                         continue;
5151                 if (!pos && (!status || !status->status) && line[1].data) {
5152                         select_view_line(view, lineno);
5153                         return TRUE;
5154                 }
5155                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5156                         select_view_line(view, lineno);
5157                         return TRUE;
5158                 }
5159         }
5161         return FALSE;
5165 static bool
5166 status_update_prepare(struct io *io, enum line_type type)
5168         const char *staged_argv[] = {
5169                 "git", "update-index", "-z", "--index-info", NULL
5170         };
5171         const char *others_argv[] = {
5172                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5173         };
5175         switch (type) {
5176         case LINE_STAT_STAGED:
5177                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5179         case LINE_STAT_UNSTAGED:
5180         case LINE_STAT_UNTRACKED:
5181                 return io_run(io, IO_WR, opt_cdup, others_argv);
5183         default:
5184                 die("line type %d not handled in switch", type);
5185                 return FALSE;
5186         }
5189 static bool
5190 status_update_write(struct io *io, struct status *status, enum line_type type)
5192         char buf[SIZEOF_STR];
5193         size_t bufsize = 0;
5195         switch (type) {
5196         case LINE_STAT_STAGED:
5197                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5198                                         status->old.mode,
5199                                         status->old.rev,
5200                                         status->old.name, 0))
5201                         return FALSE;
5202                 break;
5204         case LINE_STAT_UNSTAGED:
5205         case LINE_STAT_UNTRACKED:
5206                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5207                         return FALSE;
5208                 break;
5210         default:
5211                 die("line type %d not handled in switch", type);
5212         }
5214         return io_write(io, buf, bufsize);
5217 static bool
5218 status_update_file(struct status *status, enum line_type type)
5220         struct io io;
5221         bool result;
5223         if (!status_update_prepare(&io, type))
5224                 return FALSE;
5226         result = status_update_write(&io, status, type);
5227         return io_done(&io) && result;
5230 static bool
5231 status_update_files(struct view *view, struct line *line)
5233         char buf[sizeof(view->ref)];
5234         struct io io;
5235         bool result = TRUE;
5236         struct line *pos = view->line + view->lines;
5237         int files = 0;
5238         int file, done;
5239         int cursor_y = -1, cursor_x = -1;
5241         if (!status_update_prepare(&io, line->type))
5242                 return FALSE;
5244         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5245                 files++;
5247         string_copy(buf, view->ref);
5248         getsyx(cursor_y, cursor_x);
5249         for (file = 0, done = 5; result && file < files; line++, file++) {
5250                 int almost_done = file * 100 / files;
5252                 if (almost_done > done) {
5253                         done = almost_done;
5254                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5255                                       file, files, done);
5256                         update_view_title(view);
5257                         setsyx(cursor_y, cursor_x);
5258                         doupdate();
5259                 }
5260                 result = status_update_write(&io, line->data, line->type);
5261         }
5262         string_copy(view->ref, buf);
5264         return io_done(&io) && result;
5267 static bool
5268 status_update(struct view *view)
5270         struct line *line = &view->line[view->lineno];
5272         assert(view->lines);
5274         if (!line->data) {
5275                 /* This should work even for the "On branch" line. */
5276                 if (line < view->line + view->lines && !line[1].data) {
5277                         report("Nothing to update");
5278                         return FALSE;
5279                 }
5281                 if (!status_update_files(view, line + 1)) {
5282                         report("Failed to update file status");
5283                         return FALSE;
5284                 }
5286         } else if (!status_update_file(line->data, line->type)) {
5287                 report("Failed to update file status");
5288                 return FALSE;
5289         }
5291         return TRUE;
5294 static bool
5295 status_revert(struct status *status, enum line_type type, bool has_none)
5297         if (!status || type != LINE_STAT_UNSTAGED) {
5298                 if (type == LINE_STAT_STAGED) {
5299                         report("Cannot revert changes to staged files");
5300                 } else if (type == LINE_STAT_UNTRACKED) {
5301                         report("Cannot revert changes to untracked files");
5302                 } else if (has_none) {
5303                         report("Nothing to revert");
5304                 } else {
5305                         report("Cannot revert changes to multiple files");
5306                 }
5308         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5309                 char mode[10] = "100644";
5310                 const char *reset_argv[] = {
5311                         "git", "update-index", "--cacheinfo", mode,
5312                                 status->old.rev, status->old.name, NULL
5313                 };
5314                 const char *checkout_argv[] = {
5315                         "git", "checkout", "--", status->old.name, NULL
5316                 };
5318                 if (status->status == 'U') {
5319                         string_format(mode, "%5o", status->old.mode);
5321                         if (status->old.mode == 0 && status->new.mode == 0) {
5322                                 reset_argv[2] = "--force-remove";
5323                                 reset_argv[3] = status->old.name;
5324                                 reset_argv[4] = NULL;
5325                         }
5327                         if (!io_run_fg(reset_argv, opt_cdup))
5328                                 return FALSE;
5329                         if (status->old.mode == 0 && status->new.mode == 0)
5330                                 return TRUE;
5331                 }
5333                 return io_run_fg(checkout_argv, opt_cdup);
5334         }
5336         return FALSE;
5339 static enum request
5340 status_request(struct view *view, enum request request, struct line *line)
5342         struct status *status = line->data;
5344         switch (request) {
5345         case REQ_STATUS_UPDATE:
5346                 if (!status_update(view))
5347                         return REQ_NONE;
5348                 break;
5350         case REQ_STATUS_REVERT:
5351                 if (!status_revert(status, line->type, status_has_none(view, line)))
5352                         return REQ_NONE;
5353                 break;
5355         case REQ_STATUS_MERGE:
5356                 if (!status || status->status != 'U') {
5357                         report("Merging only possible for files with unmerged status ('U').");
5358                         return REQ_NONE;
5359                 }
5360                 open_mergetool(status->new.name);
5361                 break;
5363         case REQ_EDIT:
5364                 if (!status)
5365                         return request;
5366                 if (status->status == 'D') {
5367                         report("File has been deleted.");
5368                         return REQ_NONE;
5369                 }
5371                 open_editor(status->new.name);
5372                 break;
5374         case REQ_VIEW_BLAME:
5375                 if (status)
5376                         opt_ref[0] = 0;
5377                 return request;
5379         case REQ_ENTER:
5380                 /* After returning the status view has been split to
5381                  * show the stage view. No further reloading is
5382                  * necessary. */
5383                 return status_enter(view, line);
5385         case REQ_REFRESH:
5386                 /* Simply reload the view. */
5387                 break;
5389         default:
5390                 return request;
5391         }
5393         refresh_view(view);
5395         return REQ_NONE;
5398 static void
5399 status_select(struct view *view, struct line *line)
5401         struct status *status = line->data;
5402         char file[SIZEOF_STR] = "all files";
5403         const char *text;
5404         const char *key;
5406         if (status && !string_format(file, "'%s'", status->new.name))
5407                 return;
5409         if (!status && line[1].type == LINE_STAT_NONE)
5410                 line++;
5412         switch (line->type) {
5413         case LINE_STAT_STAGED:
5414                 text = "Press %s to unstage %s for commit";
5415                 break;
5417         case LINE_STAT_UNSTAGED:
5418                 text = "Press %s to stage %s for commit";
5419                 break;
5421         case LINE_STAT_UNTRACKED:
5422                 text = "Press %s to stage %s for addition";
5423                 break;
5425         case LINE_STAT_HEAD:
5426         case LINE_STAT_NONE:
5427                 text = "Nothing to update";
5428                 break;
5430         default:
5431                 die("line type %d not handled in switch", line->type);
5432         }
5434         if (status && status->status == 'U') {
5435                 text = "Press %s to resolve conflict in %s";
5436                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5438         } else {
5439                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5440         }
5442         string_format(view->ref, text, key, file);
5443         if (status)
5444                 string_copy(opt_file, status->new.name);
5447 static bool
5448 status_grep(struct view *view, struct line *line)
5450         struct status *status = line->data;
5452         if (status) {
5453                 const char buf[2] = { status->status, 0 };
5454                 const char *text[] = { status->new.name, buf, NULL };
5456                 return grep_text(view, text);
5457         }
5459         return FALSE;
5462 static struct view_ops status_ops = {
5463         "file",
5464         status_open,
5465         NULL,
5466         status_draw,
5467         status_request,
5468         status_grep,
5469         status_select,
5470 };
5473 static bool
5474 stage_diff_write(struct io *io, struct line *line, struct line *end)
5476         while (line < end) {
5477                 if (!io_write(io, line->data, strlen(line->data)) ||
5478                     !io_write(io, "\n", 1))
5479                         return FALSE;
5480                 line++;
5481                 if (line->type == LINE_DIFF_CHUNK ||
5482                     line->type == LINE_DIFF_HEADER)
5483                         break;
5484         }
5486         return TRUE;
5489 static struct line *
5490 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5492         for (; view->line < line; line--)
5493                 if (line->type == type)
5494                         return line;
5496         return NULL;
5499 static bool
5500 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5502         const char *apply_argv[SIZEOF_ARG] = {
5503                 "git", "apply", "--whitespace=nowarn", NULL
5504         };
5505         struct line *diff_hdr;
5506         struct io io;
5507         int argc = 3;
5509         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5510         if (!diff_hdr)
5511                 return FALSE;
5513         if (!revert)
5514                 apply_argv[argc++] = "--cached";
5515         if (revert || stage_line_type == LINE_STAT_STAGED)
5516                 apply_argv[argc++] = "-R";
5517         apply_argv[argc++] = "-";
5518         apply_argv[argc++] = NULL;
5519         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5520                 return FALSE;
5522         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5523             !stage_diff_write(&io, chunk, view->line + view->lines))
5524                 chunk = NULL;
5526         io_done(&io);
5527         io_run_bg(update_index_argv);
5529         return chunk ? TRUE : FALSE;
5532 static bool
5533 stage_update(struct view *view, struct line *line)
5535         struct line *chunk = NULL;
5537         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5538                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5540         if (chunk) {
5541                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5542                         report("Failed to apply chunk");
5543                         return FALSE;
5544                 }
5546         } else if (!stage_status.status) {
5547                 view = VIEW(REQ_VIEW_STATUS);
5549                 for (line = view->line; line < view->line + view->lines; line++)
5550                         if (line->type == stage_line_type)
5551                                 break;
5553                 if (!status_update_files(view, line + 1)) {
5554                         report("Failed to update files");
5555                         return FALSE;
5556                 }
5558         } else if (!status_update_file(&stage_status, stage_line_type)) {
5559                 report("Failed to update file");
5560                 return FALSE;
5561         }
5563         return TRUE;
5566 static bool
5567 stage_revert(struct view *view, struct line *line)
5569         struct line *chunk = NULL;
5571         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5572                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5574         if (chunk) {
5575                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5576                         return FALSE;
5578                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5579                         report("Failed to revert chunk");
5580                         return FALSE;
5581                 }
5582                 return TRUE;
5584         } else {
5585                 return status_revert(stage_status.status ? &stage_status : NULL,
5586                                      stage_line_type, FALSE);
5587         }
5591 static void
5592 stage_next(struct view *view, struct line *line)
5594         int i;
5596         if (!stage_chunks) {
5597                 for (line = view->line; line < view->line + view->lines; line++) {
5598                         if (line->type != LINE_DIFF_CHUNK)
5599                                 continue;
5601                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5602                                 report("Allocation failure");
5603                                 return;
5604                         }
5606                         stage_chunk[stage_chunks++] = line - view->line;
5607                 }
5608         }
5610         for (i = 0; i < stage_chunks; i++) {
5611                 if (stage_chunk[i] > view->lineno) {
5612                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5613                         report("Chunk %d of %d", i + 1, stage_chunks);
5614                         return;
5615                 }
5616         }
5618         report("No next chunk found");
5621 static enum request
5622 stage_request(struct view *view, enum request request, struct line *line)
5624         switch (request) {
5625         case REQ_STATUS_UPDATE:
5626                 if (!stage_update(view, line))
5627                         return REQ_NONE;
5628                 break;
5630         case REQ_STATUS_REVERT:
5631                 if (!stage_revert(view, line))
5632                         return REQ_NONE;
5633                 break;
5635         case REQ_STAGE_NEXT:
5636                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5637                         report("File is untracked; press %s to add",
5638                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5639                         return REQ_NONE;
5640                 }
5641                 stage_next(view, line);
5642                 return REQ_NONE;
5644         case REQ_EDIT:
5645                 if (!stage_status.new.name[0])
5646                         return request;
5647                 if (stage_status.status == 'D') {
5648                         report("File has been deleted.");
5649                         return REQ_NONE;
5650                 }
5652                 open_editor(stage_status.new.name);
5653                 break;
5655         case REQ_REFRESH:
5656                 /* Reload everything ... */
5657                 break;
5659         case REQ_VIEW_BLAME:
5660                 if (stage_status.new.name[0]) {
5661                         string_copy(opt_file, stage_status.new.name);
5662                         opt_ref[0] = 0;
5663                 }
5664                 return request;
5666         case REQ_ENTER:
5667                 return pager_request(view, request, line);
5669         default:
5670                 return request;
5671         }
5673         refresh_view(view->parent);
5675         /* Check whether the staged entry still exists, and close the
5676          * stage view if it doesn't. */
5677         if (!status_exists(&stage_status, stage_line_type)) {
5678                 status_restore(VIEW(REQ_VIEW_STATUS));
5679                 return REQ_VIEW_CLOSE;
5680         }
5682         refresh_view(view);
5684         return REQ_NONE;
5687 static struct view_ops stage_ops = {
5688         "line",
5689         view_open,
5690         pager_read,
5691         pager_draw,
5692         stage_request,
5693         pager_grep,
5694         pager_select,
5695 };
5698 /*
5699  * Revision graph
5700  */
5702 static const enum line_type graph_colors[] = {
5703         LINE_GRAPH_LINE_0,
5704         LINE_GRAPH_LINE_1,
5705         LINE_GRAPH_LINE_2,
5706         LINE_GRAPH_LINE_3,
5707         LINE_GRAPH_LINE_4,
5708         LINE_GRAPH_LINE_5,
5709         LINE_GRAPH_LINE_6,
5710 };
5712 static enum line_type get_graph_color(struct graph_symbol *symbol)
5714         if (symbol->commit)
5715                 return LINE_GRAPH_COMMIT;
5716         assert(symbol->color < ARRAY_SIZE(graph_colors));
5717         return graph_colors[symbol->color];
5720 static bool
5721 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5723         const char *chars = graph_symbol_to_utf8(symbol);
5725         return draw_text(view, color, chars + !!first); 
5728 static bool
5729 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5731         const char *chars = graph_symbol_to_ascii(symbol);
5733         return draw_text(view, color, chars + !!first); 
5736 static bool
5737 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5739         const chtype *chars = graph_symbol_to_chtype(symbol);
5741         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5744 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5746 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5748         static const draw_graph_fn fns[] = {
5749                 draw_graph_ascii,
5750                 draw_graph_chtype,
5751                 draw_graph_utf8
5752         };
5753         draw_graph_fn fn = fns[opt_line_graphics];
5754         int i;
5756         for (i = 0; i < canvas->size; i++) {
5757                 struct graph_symbol *symbol = &canvas->symbols[i];
5758                 enum line_type color = get_graph_color(symbol);
5760                 if (fn(view, symbol, color, i == 0))
5761                         return TRUE;
5762         }
5764         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5767 /*
5768  * Main view backend
5769  */
5771 struct commit {
5772         char id[SIZEOF_REV];            /* SHA1 ID. */
5773         char title[128];                /* First line of the commit message. */
5774         const char *author;             /* Author of the commit. */
5775         struct time time;               /* Date from the author ident. */
5776         struct ref_list *refs;          /* Repository references. */
5777         struct graph_canvas graph;      /* Ancestry chain graphics. */
5778 };
5780 static bool
5781 main_open(struct view *view, enum open_flags flags)
5783         static const char *main_argv[] = {
5784                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5785                         "--topo-order", "%(diffargs)", "%(revargs)",
5786                         "--", "%(fileargs)", NULL
5787         };
5789         return begin_update(view, NULL, main_argv, flags);
5792 static bool
5793 main_draw(struct view *view, struct line *line, unsigned int lineno)
5795         struct commit *commit = line->data;
5797         if (!commit->author)
5798                 return FALSE;
5800         if (draw_date(view, &commit->time))
5801                 return TRUE;
5803         if (draw_author(view, commit->author))
5804                 return TRUE;
5806         if (opt_rev_graph && draw_graph(view, &commit->graph))
5807                 return TRUE;
5809         if (draw_refs(view, commit->refs))
5810                 return TRUE;
5812         draw_text(view, LINE_DEFAULT, commit->title);
5813         return TRUE;
5816 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5817 static bool
5818 main_read(struct view *view, char *line)
5820         static struct graph graph;
5821         enum line_type type;
5822         struct commit *commit;
5824         if (!line) {
5825                 if (!view->lines && !view->prev)
5826                         die("No revisions match the given arguments.");
5827                 if (view->lines > 0) {
5828                         commit = view->line[view->lines - 1].data;
5829                         view->line[view->lines - 1].dirty = 1;
5830                         if (!commit->author) {
5831                                 view->lines--;
5832                                 free(commit);
5833                         }
5834                 }
5836                 done_graph(&graph);
5837                 return TRUE;
5838         }
5840         type = get_line_type(line);
5841         if (type == LINE_COMMIT) {
5842                 bool is_boundary;
5844                 commit = calloc(1, sizeof(struct commit));
5845                 if (!commit)
5846                         return FALSE;
5848                 line += STRING_SIZE("commit ");
5849                 is_boundary = *line == '-';
5850                 if (is_boundary)
5851                         line++;
5853                 string_copy_rev(commit->id, line);
5854                 commit->refs = get_ref_list(commit->id);
5855                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5856                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5857                 return TRUE;
5858         }
5860         if (!view->lines)
5861                 return TRUE;
5862         commit = view->line[view->lines - 1].data;
5864         switch (type) {
5865         case LINE_PARENT:
5866                 if (!graph.has_parents)
5867                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5868                 break;
5870         case LINE_AUTHOR:
5871                 parse_author_line(line + STRING_SIZE("author "),
5872                                   &commit->author, &commit->time);
5873                 graph_render_parents(&graph);
5874                 break;
5876         default:
5877                 /* Fill in the commit title if it has not already been set. */
5878                 if (commit->title[0])
5879                         break;
5881                 /* Require titles to start with a non-space character at the
5882                  * offset used by git log. */
5883                 if (strncmp(line, "    ", 4))
5884                         break;
5885                 line += 4;
5886                 /* Well, if the title starts with a whitespace character,
5887                  * try to be forgiving.  Otherwise we end up with no title. */
5888                 while (isspace(*line))
5889                         line++;
5890                 if (*line == '\0')
5891                         break;
5892                 /* FIXME: More graceful handling of titles; append "..." to
5893                  * shortened titles, etc. */
5895                 string_expand(commit->title, sizeof(commit->title), line, 1);
5896                 view->line[view->lines - 1].dirty = 1;
5897         }
5899         return TRUE;
5902 static enum request
5903 main_request(struct view *view, enum request request, struct line *line)
5905         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5907         switch (request) {
5908         case REQ_ENTER:
5909                 if (view_is_displayed(view) && display[0] != view)
5910                         maximize_view(view, TRUE);
5911                 open_view(view, REQ_VIEW_DIFF, flags);
5912                 break;
5913         case REQ_REFRESH:
5914                 load_refs();
5915                 refresh_view(view);
5916                 break;
5917         default:
5918                 return request;
5919         }
5921         return REQ_NONE;
5924 static bool
5925 grep_refs(struct ref_list *list, regex_t *regex)
5927         regmatch_t pmatch;
5928         size_t i;
5930         if (!opt_show_refs || !list)
5931                 return FALSE;
5933         for (i = 0; i < list->size; i++) {
5934                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5935                         return TRUE;
5936         }
5938         return FALSE;
5941 static bool
5942 main_grep(struct view *view, struct line *line)
5944         struct commit *commit = line->data;
5945         const char *text[] = {
5946                 commit->title,
5947                 opt_author ? commit->author : "",
5948                 mkdate(&commit->time, opt_date),
5949                 NULL
5950         };
5952         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5955 static void
5956 main_select(struct view *view, struct line *line)
5958         struct commit *commit = line->data;
5960         string_copy_rev(view->ref, commit->id);
5961         string_copy_rev(ref_commit, view->ref);
5964 static struct view_ops main_ops = {
5965         "commit",
5966         main_open,
5967         main_read,
5968         main_draw,
5969         main_request,
5970         main_grep,
5971         main_select,
5972 };
5975 /*
5976  * Status management
5977  */
5979 /* Whether or not the curses interface has been initialized. */
5980 static bool cursed = FALSE;
5982 /* Terminal hacks and workarounds. */
5983 static bool use_scroll_redrawwin;
5984 static bool use_scroll_status_wclear;
5986 /* The status window is used for polling keystrokes. */
5987 static WINDOW *status_win;
5989 /* Reading from the prompt? */
5990 static bool input_mode = FALSE;
5992 static bool status_empty = FALSE;
5994 /* Update status and title window. */
5995 static void
5996 report(const char *msg, ...)
5998         struct view *view = display[current_view];
6000         if (input_mode)
6001                 return;
6003         if (!view) {
6004                 char buf[SIZEOF_STR];
6005                 va_list args;
6007                 va_start(args, msg);
6008                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6009                         buf[sizeof(buf) - 1] = 0;
6010                         buf[sizeof(buf) - 2] = '.';
6011                         buf[sizeof(buf) - 3] = '.';
6012                         buf[sizeof(buf) - 4] = '.';
6013                 }
6014                 va_end(args);
6015                 die("%s", buf);
6016         }
6018         if (!status_empty || *msg) {
6019                 va_list args;
6021                 va_start(args, msg);
6023                 wmove(status_win, 0, 0);
6024                 if (view->has_scrolled && use_scroll_status_wclear)
6025                         wclear(status_win);
6026                 if (*msg) {
6027                         vwprintw(status_win, msg, args);
6028                         status_empty = FALSE;
6029                 } else {
6030                         status_empty = TRUE;
6031                 }
6032                 wclrtoeol(status_win);
6033                 wnoutrefresh(status_win);
6035                 va_end(args);
6036         }
6038         update_view_title(view);
6041 static void
6042 init_display(void)
6044         const char *term;
6045         int x, y;
6047         /* Initialize the curses library */
6048         if (isatty(STDIN_FILENO)) {
6049                 cursed = !!initscr();
6050                 opt_tty = stdin;
6051         } else {
6052                 /* Leave stdin and stdout alone when acting as a pager. */
6053                 opt_tty = fopen("/dev/tty", "r+");
6054                 if (!opt_tty)
6055                         die("Failed to open /dev/tty");
6056                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6057         }
6059         if (!cursed)
6060                 die("Failed to initialize curses");
6062         nonl();         /* Disable conversion and detect newlines from input. */
6063         cbreak();       /* Take input chars one at a time, no wait for \n */
6064         noecho();       /* Don't echo input */
6065         leaveok(stdscr, FALSE);
6067         if (has_colors())
6068                 init_colors();
6070         getmaxyx(stdscr, y, x);
6071         status_win = newwin(1, x, y - 1, 0);
6072         if (!status_win)
6073                 die("Failed to create status window");
6075         /* Enable keyboard mapping */
6076         keypad(status_win, TRUE);
6077         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6079 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6080         set_tabsize(opt_tab_size);
6081 #else
6082         TABSIZE = opt_tab_size;
6083 #endif
6085         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6086         if (term && !strcmp(term, "gnome-terminal")) {
6087                 /* In the gnome-terminal-emulator, the message from
6088                  * scrolling up one line when impossible followed by
6089                  * scrolling down one line causes corruption of the
6090                  * status line. This is fixed by calling wclear. */
6091                 use_scroll_status_wclear = TRUE;
6092                 use_scroll_redrawwin = FALSE;
6094         } else if (term && !strcmp(term, "xrvt-xpm")) {
6095                 /* No problems with full optimizations in xrvt-(unicode)
6096                  * and aterm. */
6097                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6099         } else {
6100                 /* When scrolling in (u)xterm the last line in the
6101                  * scrolling direction will update slowly. */
6102                 use_scroll_redrawwin = TRUE;
6103                 use_scroll_status_wclear = FALSE;
6104         }
6107 static int
6108 get_input(int prompt_position)
6110         struct view *view;
6111         int i, key, cursor_y, cursor_x;
6113         if (prompt_position)
6114                 input_mode = TRUE;
6116         while (TRUE) {
6117                 bool loading = FALSE;
6119                 foreach_view (view, i) {
6120                         update_view(view);
6121                         if (view_is_displayed(view) && view->has_scrolled &&
6122                             use_scroll_redrawwin)
6123                                 redrawwin(view->win);
6124                         view->has_scrolled = FALSE;
6125                         if (view->pipe)
6126                                 loading = TRUE;
6127                 }
6129                 /* Update the cursor position. */
6130                 if (prompt_position) {
6131                         getbegyx(status_win, cursor_y, cursor_x);
6132                         cursor_x = prompt_position;
6133                 } else {
6134                         view = display[current_view];
6135                         getbegyx(view->win, cursor_y, cursor_x);
6136                         cursor_x = view->width - 1;
6137                         cursor_y += view->lineno - view->offset;
6138                 }
6139                 setsyx(cursor_y, cursor_x);
6141                 /* Refresh, accept single keystroke of input */
6142                 doupdate();
6143                 nodelay(status_win, loading);
6144                 key = wgetch(status_win);
6146                 /* wgetch() with nodelay() enabled returns ERR when
6147                  * there's no input. */
6148                 if (key == ERR) {
6150                 } else if (key == KEY_RESIZE) {
6151                         int height, width;
6153                         getmaxyx(stdscr, height, width);
6155                         wresize(status_win, 1, width);
6156                         mvwin(status_win, height - 1, 0);
6157                         wnoutrefresh(status_win);
6158                         resize_display();
6159                         redraw_display(TRUE);
6161                 } else {
6162                         input_mode = FALSE;
6163                         return key;
6164                 }
6165         }
6168 static char *
6169 prompt_input(const char *prompt, input_handler handler, void *data)
6171         enum input_status status = INPUT_OK;
6172         static char buf[SIZEOF_STR];
6173         size_t pos = 0;
6175         buf[pos] = 0;
6177         while (status == INPUT_OK || status == INPUT_SKIP) {
6178                 int key;
6180                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6181                 wclrtoeol(status_win);
6183                 key = get_input(pos + 1);
6184                 switch (key) {
6185                 case KEY_RETURN:
6186                 case KEY_ENTER:
6187                 case '\n':
6188                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6189                         break;
6191                 case KEY_BACKSPACE:
6192                         if (pos > 0)
6193                                 buf[--pos] = 0;
6194                         else
6195                                 status = INPUT_CANCEL;
6196                         break;
6198                 case KEY_ESC:
6199                         status = INPUT_CANCEL;
6200                         break;
6202                 default:
6203                         if (pos >= sizeof(buf)) {
6204                                 report("Input string too long");
6205                                 return NULL;
6206                         }
6208                         status = handler(data, buf, key);
6209                         if (status == INPUT_OK)
6210                                 buf[pos++] = (char) key;
6211                 }
6212         }
6214         /* Clear the status window */
6215         status_empty = FALSE;
6216         report("");
6218         if (status == INPUT_CANCEL)
6219                 return NULL;
6221         buf[pos++] = 0;
6223         return buf;
6226 static enum input_status
6227 prompt_yesno_handler(void *data, char *buf, int c)
6229         if (c == 'y' || c == 'Y')
6230                 return INPUT_STOP;
6231         if (c == 'n' || c == 'N')
6232                 return INPUT_CANCEL;
6233         return INPUT_SKIP;
6236 static bool
6237 prompt_yesno(const char *prompt)
6239         char prompt2[SIZEOF_STR];
6241         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6242                 return FALSE;
6244         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6247 static enum input_status
6248 read_prompt_handler(void *data, char *buf, int c)
6250         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6253 static char *
6254 read_prompt(const char *prompt)
6256         return prompt_input(prompt, read_prompt_handler, NULL);
6259 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6261         enum input_status status = INPUT_OK;
6262         int size = 0;
6264         while (items[size].text)
6265                 size++;
6267         while (status == INPUT_OK) {
6268                 const struct menu_item *item = &items[*selected];
6269                 int key;
6270                 int i;
6272                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6273                           prompt, *selected + 1, size);
6274                 if (item->hotkey)
6275                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6276                 wprintw(status_win, "%s", item->text);
6277                 wclrtoeol(status_win);
6279                 key = get_input(COLS - 1);
6280                 switch (key) {
6281                 case KEY_RETURN:
6282                 case KEY_ENTER:
6283                 case '\n':
6284                         status = INPUT_STOP;
6285                         break;
6287                 case KEY_LEFT:
6288                 case KEY_UP:
6289                         *selected = *selected - 1;
6290                         if (*selected < 0)
6291                                 *selected = size - 1;
6292                         break;
6294                 case KEY_RIGHT:
6295                 case KEY_DOWN:
6296                         *selected = (*selected + 1) % size;
6297                         break;
6299                 case KEY_ESC:
6300                         status = INPUT_CANCEL;
6301                         break;
6303                 default:
6304                         for (i = 0; items[i].text; i++)
6305                                 if (items[i].hotkey == key) {
6306                                         *selected = i;
6307                                         status = INPUT_STOP;
6308                                         break;
6309                                 }
6310                 }
6311         }
6313         /* Clear the status window */
6314         status_empty = FALSE;
6315         report("");
6317         return status != INPUT_CANCEL;
6320 /*
6321  * Repository properties
6322  */
6324 static struct ref **refs = NULL;
6325 static size_t refs_size = 0;
6326 static struct ref *refs_head = NULL;
6328 static struct ref_list **ref_lists = NULL;
6329 static size_t ref_lists_size = 0;
6331 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6332 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6333 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6335 static int
6336 compare_refs(const void *ref1_, const void *ref2_)
6338         const struct ref *ref1 = *(const struct ref **)ref1_;
6339         const struct ref *ref2 = *(const struct ref **)ref2_;
6341         if (ref1->tag != ref2->tag)
6342                 return ref2->tag - ref1->tag;
6343         if (ref1->ltag != ref2->ltag)
6344                 return ref2->ltag - ref2->ltag;
6345         if (ref1->head != ref2->head)
6346                 return ref2->head - ref1->head;
6347         if (ref1->tracked != ref2->tracked)
6348                 return ref2->tracked - ref1->tracked;
6349         if (ref1->remote != ref2->remote)
6350                 return ref2->remote - ref1->remote;
6351         return strcmp(ref1->name, ref2->name);
6354 static void
6355 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6357         size_t i;
6359         for (i = 0; i < refs_size; i++)
6360                 if (!visitor(data, refs[i]))
6361                         break;
6364 static struct ref *
6365 get_ref_head()
6367         return refs_head;
6370 static struct ref_list *
6371 get_ref_list(const char *id)
6373         struct ref_list *list;
6374         size_t i;
6376         for (i = 0; i < ref_lists_size; i++)
6377                 if (!strcmp(id, ref_lists[i]->id))
6378                         return ref_lists[i];
6380         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6381                 return NULL;
6382         list = calloc(1, sizeof(*list));
6383         if (!list)
6384                 return NULL;
6386         for (i = 0; i < refs_size; i++) {
6387                 if (!strcmp(id, refs[i]->id) &&
6388                     realloc_refs_list(&list->refs, list->size, 1))
6389                         list->refs[list->size++] = refs[i];
6390         }
6392         if (!list->refs) {
6393                 free(list);
6394                 return NULL;
6395         }
6397         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6398         ref_lists[ref_lists_size++] = list;
6399         return list;
6402 static int
6403 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6405         struct ref *ref = NULL;
6406         bool tag = FALSE;
6407         bool ltag = FALSE;
6408         bool remote = FALSE;
6409         bool tracked = FALSE;
6410         bool head = FALSE;
6411         int from = 0, to = refs_size - 1;
6413         if (!prefixcmp(name, "refs/tags/")) {
6414                 if (!suffixcmp(name, namelen, "^{}")) {
6415                         namelen -= 3;
6416                         name[namelen] = 0;
6417                 } else {
6418                         ltag = TRUE;
6419                 }
6421                 tag = TRUE;
6422                 namelen -= STRING_SIZE("refs/tags/");
6423                 name    += STRING_SIZE("refs/tags/");
6425         } else if (!prefixcmp(name, "refs/remotes/")) {
6426                 remote = TRUE;
6427                 namelen -= STRING_SIZE("refs/remotes/");
6428                 name    += STRING_SIZE("refs/remotes/");
6429                 tracked  = !strcmp(opt_remote, name);
6431         } else if (!prefixcmp(name, "refs/heads/")) {
6432                 namelen -= STRING_SIZE("refs/heads/");
6433                 name    += STRING_SIZE("refs/heads/");
6434                 if (!strncmp(opt_head, name, namelen))
6435                         return OK;
6437         } else if (!strcmp(name, "HEAD")) {
6438                 head     = TRUE;
6439                 if (*opt_head) {
6440                         namelen  = strlen(opt_head);
6441                         name     = opt_head;
6442                 }
6443         }
6445         /* If we are reloading or it's an annotated tag, replace the
6446          * previous SHA1 with the resolved commit id; relies on the fact
6447          * git-ls-remote lists the commit id of an annotated tag right
6448          * before the commit id it points to. */
6449         while (from <= to) {
6450                 size_t pos = (to + from) / 2;
6451                 int cmp = strcmp(name, refs[pos]->name);
6453                 if (!cmp) {
6454                         ref = refs[pos];
6455                         break;
6456                 }
6458                 if (cmp < 0)
6459                         to = pos - 1;
6460                 else
6461                         from = pos + 1;
6462         }
6464         if (!ref) {
6465                 if (!realloc_refs(&refs, refs_size, 1))
6466                         return ERR;
6467                 ref = calloc(1, sizeof(*ref) + namelen);
6468                 if (!ref)
6469                         return ERR;
6470                 memmove(refs + from + 1, refs + from,
6471                         (refs_size - from) * sizeof(*refs));
6472                 refs[from] = ref;
6473                 strncpy(ref->name, name, namelen);
6474                 refs_size++;
6475         }
6477         ref->head = head;
6478         ref->tag = tag;
6479         ref->ltag = ltag;
6480         ref->remote = remote;
6481         ref->tracked = tracked;
6482         string_copy_rev(ref->id, id);
6484         if (head)
6485                 refs_head = ref;
6486         return OK;
6489 static int
6490 load_refs(void)
6492         const char *head_argv[] = {
6493                 "git", "symbolic-ref", "HEAD", NULL
6494         };
6495         static const char *ls_remote_argv[SIZEOF_ARG] = {
6496                 "git", "ls-remote", opt_git_dir, NULL
6497         };
6498         static bool init = FALSE;
6499         size_t i;
6501         if (!init) {
6502                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6503                         die("TIG_LS_REMOTE contains too many arguments");
6504                 init = TRUE;
6505         }
6507         if (!*opt_git_dir)
6508                 return OK;
6510         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6511             !prefixcmp(opt_head, "refs/heads/")) {
6512                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6514                 memmove(opt_head, offset, strlen(offset) + 1);
6515         }
6517         refs_head = NULL;
6518         for (i = 0; i < refs_size; i++)
6519                 refs[i]->id[0] = 0;
6521         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6522                 return ERR;
6524         /* Update the ref lists to reflect changes. */
6525         for (i = 0; i < ref_lists_size; i++) {
6526                 struct ref_list *list = ref_lists[i];
6527                 size_t old, new;
6529                 for (old = new = 0; old < list->size; old++)
6530                         if (!strcmp(list->id, list->refs[old]->id))
6531                                 list->refs[new++] = list->refs[old];
6532                 list->size = new;
6533         }
6535         return OK;
6538 static void
6539 set_remote_branch(const char *name, const char *value, size_t valuelen)
6541         if (!strcmp(name, ".remote")) {
6542                 string_ncopy(opt_remote, value, valuelen);
6544         } else if (*opt_remote && !strcmp(name, ".merge")) {
6545                 size_t from = strlen(opt_remote);
6547                 if (!prefixcmp(value, "refs/heads/"))
6548                         value += STRING_SIZE("refs/heads/");
6550                 if (!string_format_from(opt_remote, &from, "/%s", value))
6551                         opt_remote[0] = 0;
6552         }
6555 static void
6556 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6558         const char *argv[SIZEOF_ARG] = { name, "=" };
6559         int argc = 1 + (cmd == option_set_command);
6560         enum option_code error;
6562         if (!argv_from_string(argv, &argc, value))
6563                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6564         else
6565                 error = cmd(argc, argv);
6567         if (error != OPT_OK)
6568                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6571 static bool
6572 set_environment_variable(const char *name, const char *value)
6574         size_t len = strlen(name) + 1 + strlen(value) + 1;
6575         char *env = malloc(len);
6577         if (env &&
6578             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6579             putenv(env) == 0)
6580                 return TRUE;
6581         free(env);
6582         return FALSE;
6585 static void
6586 set_work_tree(const char *value)
6588         char cwd[SIZEOF_STR];
6590         if (!getcwd(cwd, sizeof(cwd)))
6591                 die("Failed to get cwd path: %s", strerror(errno));
6592         if (chdir(opt_git_dir) < 0)
6593                 die("Failed to chdir(%s): %s", strerror(errno));
6594         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6595                 die("Failed to get git path: %s", strerror(errno));
6596         if (chdir(cwd) < 0)
6597                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6598         if (chdir(value) < 0)
6599                 die("Failed to chdir(%s): %s", value, strerror(errno));
6600         if (!getcwd(cwd, sizeof(cwd)))
6601                 die("Failed to get cwd path: %s", strerror(errno));
6602         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6603                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6604         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6605                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6606         opt_is_inside_work_tree = TRUE;
6609 static int
6610 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6612         if (!strcmp(name, "i18n.commitencoding"))
6613                 string_ncopy(opt_encoding, value, valuelen);
6615         else if (!strcmp(name, "core.editor"))
6616                 string_ncopy(opt_editor, value, valuelen);
6618         else if (!strcmp(name, "core.worktree"))
6619                 set_work_tree(value);
6621         else if (!prefixcmp(name, "tig.color."))
6622                 set_repo_config_option(name + 10, value, option_color_command);
6624         else if (!prefixcmp(name, "tig.bind."))
6625                 set_repo_config_option(name + 9, value, option_bind_command);
6627         else if (!prefixcmp(name, "tig."))
6628                 set_repo_config_option(name + 4, value, option_set_command);
6630         else if (*opt_head && !prefixcmp(name, "branch.") &&
6631                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6632                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6634         return OK;
6637 static int
6638 load_git_config(void)
6640         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6642         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6645 static int
6646 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6648         if (!opt_git_dir[0]) {
6649                 string_ncopy(opt_git_dir, name, namelen);
6651         } else if (opt_is_inside_work_tree == -1) {
6652                 /* This can be 3 different values depending on the
6653                  * version of git being used. If git-rev-parse does not
6654                  * understand --is-inside-work-tree it will simply echo
6655                  * the option else either "true" or "false" is printed.
6656                  * Default to true for the unknown case. */
6657                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6659         } else if (*name == '.') {
6660                 string_ncopy(opt_cdup, name, namelen);
6662         } else {
6663                 string_ncopy(opt_prefix, name, namelen);
6664         }
6666         return OK;
6669 static int
6670 load_repo_info(void)
6672         const char *rev_parse_argv[] = {
6673                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6674                         "--show-cdup", "--show-prefix", NULL
6675         };
6677         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6681 /*
6682  * Main
6683  */
6685 static const char usage[] =
6686 "tig " TIG_VERSION " (" __DATE__ ")\n"
6687 "\n"
6688 "Usage: tig        [options] [revs] [--] [paths]\n"
6689 "   or: tig show   [options] [revs] [--] [paths]\n"
6690 "   or: tig blame  [options] [rev] [--] path\n"
6691 "   or: tig status\n"
6692 "   or: tig <      [git command output]\n"
6693 "\n"
6694 "Options:\n"
6695 "  -v, --version   Show version and exit\n"
6696 "  -h, --help      Show help message and exit";
6698 static void __NORETURN
6699 quit(int sig)
6701         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6702         if (cursed)
6703                 endwin();
6704         exit(0);
6707 static void __NORETURN
6708 die(const char *err, ...)
6710         va_list args;
6712         endwin();
6714         va_start(args, err);
6715         fputs("tig: ", stderr);
6716         vfprintf(stderr, err, args);
6717         fputs("\n", stderr);
6718         va_end(args);
6720         exit(1);
6723 static void
6724 warn(const char *msg, ...)
6726         va_list args;
6728         va_start(args, msg);
6729         fputs("tig warning: ", stderr);
6730         vfprintf(stderr, msg, args);
6731         fputs("\n", stderr);
6732         va_end(args);
6735 static int
6736 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6738         const char ***filter_args = data;
6740         return argv_append(filter_args, name) ? OK : ERR;
6743 static void
6744 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6746         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6747         const char **all_argv = NULL;
6749         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6750             !argv_append_array(&all_argv, argv) ||
6751             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6752                 die("Failed to split arguments");
6753         argv_free(all_argv);
6754         free(all_argv);
6757 static void
6758 filter_options(const char *argv[])
6760         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6761         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6762         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6765 static enum request
6766 parse_options(int argc, const char *argv[])
6768         enum request request = REQ_VIEW_MAIN;
6769         const char *subcommand;
6770         bool seen_dashdash = FALSE;
6771         const char **filter_argv = NULL;
6772         int i;
6774         if (!isatty(STDIN_FILENO))
6775                 return REQ_VIEW_PAGER;
6777         if (argc <= 1)
6778                 return REQ_VIEW_MAIN;
6780         subcommand = argv[1];
6781         if (!strcmp(subcommand, "status")) {
6782                 if (argc > 2)
6783                         warn("ignoring arguments after `%s'", subcommand);
6784                 return REQ_VIEW_STATUS;
6786         } else if (!strcmp(subcommand, "blame")) {
6787                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6788                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6789                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6791                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6792                         die("invalid number of options to blame\n\n%s", usage);
6794                 if (opt_rev_argv) {
6795                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6796                 }
6798                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6799                 return REQ_VIEW_BLAME;
6801         } else if (!strcmp(subcommand, "show")) {
6802                 request = REQ_VIEW_DIFF;
6804         } else {
6805                 subcommand = NULL;
6806         }
6808         for (i = 1 + !!subcommand; i < argc; i++) {
6809                 const char *opt = argv[i];
6811                 if (seen_dashdash) {
6812                         argv_append(&opt_file_argv, opt);
6813                         continue;
6815                 } else if (!strcmp(opt, "--")) {
6816                         seen_dashdash = TRUE;
6817                         continue;
6819                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6820                         printf("tig version %s\n", TIG_VERSION);
6821                         quit(0);
6823                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6824                         printf("%s\n", usage);
6825                         quit(0);
6827                 } else if (!strcmp(opt, "--all")) {
6828                         argv_append(&opt_rev_argv, opt);
6829                         continue;
6830                 }
6832                 if (!argv_append(&filter_argv, opt))
6833                         die("command too long");
6834         }
6836         if (filter_argv)
6837                 filter_options(filter_argv);
6839         return request;
6842 int
6843 main(int argc, const char *argv[])
6845         const char *codeset = "UTF-8";
6846         enum request request = parse_options(argc, argv);
6847         struct view *view;
6849         signal(SIGINT, quit);
6850         signal(SIGPIPE, SIG_IGN);
6852         if (setlocale(LC_ALL, "")) {
6853                 codeset = nl_langinfo(CODESET);
6854         }
6856         if (load_repo_info() == ERR)
6857                 die("Failed to load repo info.");
6859         if (load_options() == ERR)
6860                 die("Failed to load user config.");
6862         if (load_git_config() == ERR)
6863                 die("Failed to load repo config.");
6865         /* Require a git repository unless when running in pager mode. */
6866         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6867                 die("Not a git repository");
6869         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6870                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6871                 if (opt_iconv_in == ICONV_NONE)
6872                         die("Failed to initialize character set conversion");
6873         }
6875         if (codeset && strcmp(codeset, "UTF-8")) {
6876                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6877                 if (opt_iconv_out == ICONV_NONE)
6878                         die("Failed to initialize character set conversion");
6879         }
6881         if (load_refs() == ERR)
6882                 die("Failed to load refs.");
6884         init_display();
6886         while (view_driver(display[current_view], request)) {
6887                 int key = get_input(0);
6889                 view = display[current_view];
6890                 request = get_keybinding(view->keymap, key);
6892                 /* Some low-level request handling. This keeps access to
6893                  * status_win restricted. */
6894                 switch (request) {
6895                 case REQ_NONE:
6896                         report("Unknown key, press %s for help",
6897                                get_key(view->keymap, REQ_VIEW_HELP));
6898                         break;
6899                 case REQ_PROMPT:
6900                 {
6901                         char *cmd = read_prompt(":");
6903                         if (cmd && isdigit(*cmd)) {
6904                                 int lineno = view->lineno + 1;
6906                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6907                                         select_view_line(view, lineno - 1);
6908                                         report("");
6909                                 } else {
6910                                         report("Unable to parse '%s' as a line number", cmd);
6911                                 }
6913                         } else if (cmd) {
6914                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6915                                 const char *argv[SIZEOF_ARG] = { "git" };
6916                                 int argc = 1;
6918                                 /* When running random commands, initially show the
6919                                  * command in the title. However, it maybe later be
6920                                  * overwritten if a commit line is selected. */
6921                                 string_ncopy(next->ref, cmd, strlen(cmd));
6923                                 if (!argv_from_string(argv, &argc, cmd)) {
6924                                         report("Too many arguments");
6925                                 } else {
6926                                         open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6927                                 }
6928                         }
6930                         request = REQ_NONE;
6931                         break;
6932                 }
6933                 case REQ_SEARCH:
6934                 case REQ_SEARCH_BACK:
6935                 {
6936                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6937                         char *search = read_prompt(prompt);
6939                         if (search)
6940                                 string_ncopy(opt_search, search, strlen(search));
6941                         else if (*opt_search)
6942                                 request = request == REQ_SEARCH ?
6943                                         REQ_FIND_NEXT :
6944                                         REQ_FIND_PREV;
6945                         else
6946                                 request = REQ_NONE;
6947                         break;
6948                 }
6949                 default:
6950                         break;
6951                 }
6952         }
6954         quit(0);
6956         return 0;