Code

d33d3eb528c8920328cb4b4e87d9b1fe6a9119a7
[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 == AUTHOR_NO)
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         if (opt_author == AUTHOR_NO)
1655                 return FALSE;
1657         return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1660 static bool
1661 draw_mode(struct view *view, mode_t mode)
1663         const char *str = mkmode(mode);
1665         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1668 static bool
1669 draw_lineno(struct view *view, unsigned int lineno)
1671         char number[10];
1672         int digits3 = view->digits < 3 ? 3 : view->digits;
1673         int max = MIN(VIEW_MAX_LEN(view), digits3);
1674         char *text = NULL;
1675         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1677         lineno += view->offset + 1;
1678         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1679                 static char fmt[] = "%1ld";
1681                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1682                 if (string_format(number, fmt, lineno))
1683                         text = number;
1684         }
1685         if (text)
1686                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1687         else
1688                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1689         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1692 static bool
1693 draw_refs(struct view *view, struct ref_list *refs)
1695         size_t i;
1697         if (!opt_show_refs || !refs)
1698                 return FALSE;
1700         for (i = 0; i < refs->size; i++) {
1701                 struct ref *ref = refs->refs[i];
1702                 enum line_type type;
1704                 if (ref->head)
1705                         type = LINE_MAIN_HEAD;
1706                 else if (ref->ltag)
1707                         type = LINE_MAIN_LOCAL_TAG;
1708                 else if (ref->tag)
1709                         type = LINE_MAIN_TAG;
1710                 else if (ref->tracked)
1711                         type = LINE_MAIN_TRACKED;
1712                 else if (ref->remote)
1713                         type = LINE_MAIN_REMOTE;
1714                 else
1715                         type = LINE_MAIN_REF;
1717                 if (draw_text(view, type, "[") ||
1718                     draw_text(view, type, ref->name) ||
1719                     draw_text(view, type, "]"))
1720                         return TRUE;
1722                 if (draw_text(view, LINE_DEFAULT, " "))
1723                         return TRUE;
1724         }
1726         return FALSE;
1729 static bool
1730 draw_view_line(struct view *view, unsigned int lineno)
1732         struct line *line;
1733         bool selected = (view->offset + lineno == view->lineno);
1735         assert(view_is_displayed(view));
1737         if (view->offset + lineno >= view->lines)
1738                 return FALSE;
1740         line = &view->line[view->offset + lineno];
1742         wmove(view->win, lineno, 0);
1743         if (line->cleareol)
1744                 wclrtoeol(view->win);
1745         view->col = 0;
1746         view->curline = line;
1747         view->curtype = LINE_NONE;
1748         line->selected = FALSE;
1749         line->dirty = line->cleareol = 0;
1751         if (selected) {
1752                 set_view_attr(view, LINE_CURSOR);
1753                 line->selected = TRUE;
1754                 view->ops->select(view, line);
1755         }
1757         return view->ops->draw(view, line, lineno);
1760 static void
1761 redraw_view_dirty(struct view *view)
1763         bool dirty = FALSE;
1764         int lineno;
1766         for (lineno = 0; lineno < view->height; lineno++) {
1767                 if (view->offset + lineno >= view->lines)
1768                         break;
1769                 if (!view->line[view->offset + lineno].dirty)
1770                         continue;
1771                 dirty = TRUE;
1772                 if (!draw_view_line(view, lineno))
1773                         break;
1774         }
1776         if (!dirty)
1777                 return;
1778         wnoutrefresh(view->win);
1781 static void
1782 redraw_view_from(struct view *view, int lineno)
1784         assert(0 <= lineno && lineno < view->height);
1786         for (; lineno < view->height; lineno++) {
1787                 if (!draw_view_line(view, lineno))
1788                         break;
1789         }
1791         wnoutrefresh(view->win);
1794 static void
1795 redraw_view(struct view *view)
1797         werase(view->win);
1798         redraw_view_from(view, 0);
1802 static void
1803 update_view_title(struct view *view)
1805         char buf[SIZEOF_STR];
1806         char state[SIZEOF_STR];
1807         size_t bufpos = 0, statelen = 0;
1808         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1810         assert(view_is_displayed(view));
1812         if (view->type != VIEW_STATUS && view->lines) {
1813                 unsigned int view_lines = view->offset + view->height;
1814                 unsigned int lines = view->lines
1815                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1816                                    : 0;
1818                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1819                                    view->ops->type,
1820                                    view->lineno + 1,
1821                                    view->lines,
1822                                    lines);
1824         }
1826         if (view->pipe) {
1827                 time_t secs = time(NULL) - view->start_time;
1829                 /* Three git seconds are a long time ... */
1830                 if (secs > 2)
1831                         string_format_from(state, &statelen, " loading %lds", secs);
1832         }
1834         string_format_from(buf, &bufpos, "[%s]", view->name);
1835         if (*view->ref && bufpos < view->width) {
1836                 size_t refsize = strlen(view->ref);
1837                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1839                 if (minsize < view->width)
1840                         refsize = view->width - minsize + 7;
1841                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1842         }
1844         if (statelen && bufpos < view->width) {
1845                 string_format_from(buf, &bufpos, "%s", state);
1846         }
1848         if (view == display[current_view])
1849                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1850         else
1851                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1853         mvwaddnstr(window, 0, 0, buf, bufpos);
1854         wclrtoeol(window);
1855         wnoutrefresh(window);
1858 static int
1859 apply_step(double step, int value)
1861         if (step >= 1)
1862                 return (int) step;
1863         value *= step + 0.01;
1864         return value ? value : 1;
1867 static void
1868 resize_display(void)
1870         int offset, i;
1871         struct view *base = display[0];
1872         struct view *view = display[1] ? display[1] : display[0];
1874         /* Setup window dimensions */
1876         getmaxyx(stdscr, base->height, base->width);
1878         /* Make room for the status window. */
1879         base->height -= 1;
1881         if (view != base) {
1882                 /* Horizontal split. */
1883                 view->width   = base->width;
1884                 view->height  = apply_step(opt_scale_split_view, base->height);
1885                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1886                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1887                 base->height -= view->height;
1889                 /* Make room for the title bar. */
1890                 view->height -= 1;
1891         }
1893         /* Make room for the title bar. */
1894         base->height -= 1;
1896         offset = 0;
1898         foreach_displayed_view (view, i) {
1899                 if (!display_win[i]) {
1900                         display_win[i] = newwin(view->height, view->width, offset, 0);
1901                         if (!display_win[i])
1902                                 die("Failed to create %s view", view->name);
1904                         scrollok(display_win[i], FALSE);
1906                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1907                         if (!display_title[i])
1908                                 die("Failed to create title window");
1910                 } else {
1911                         wresize(display_win[i], view->height, view->width);
1912                         mvwin(display_win[i],   offset, 0);
1913                         mvwin(display_title[i], offset + view->height, 0);
1914                 }
1916                 view->win = display_win[i];
1918                 offset += view->height + 1;
1919         }
1922 static void
1923 redraw_display(bool clear)
1925         struct view *view;
1926         int i;
1928         foreach_displayed_view (view, i) {
1929                 if (clear)
1930                         wclear(view->win);
1931                 redraw_view(view);
1932                 update_view_title(view);
1933         }
1937 /*
1938  * Option management
1939  */
1941 #define TOGGLE_MENU \
1942         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1943         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1944         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1945         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1946         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1947         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1949 static void
1950 toggle_option(enum request request)
1952         const struct {
1953                 enum request request;
1954                 const struct enum_map *map;
1955                 size_t map_size;
1956         } data[] = {            
1957 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1958                 TOGGLE_MENU
1959 #undef  TOGGLE_
1960         };
1961         const struct menu_item menu[] = {
1962 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1963                 TOGGLE_MENU
1964 #undef  TOGGLE_
1965                 { 0 }
1966         };
1967         int i = 0;
1969         if (request == REQ_OPTIONS) {
1970                 if (!prompt_menu("Toggle option", menu, &i))
1971                         return;
1972         } else {
1973                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1974                         i++;
1975                 if (i >= ARRAY_SIZE(data))
1976                         die("Invalid request (%d)", request);
1977         }
1979         if (data[i].map != NULL) {
1980                 unsigned int *opt = menu[i].data;
1982                 *opt = (*opt + 1) % data[i].map_size;
1983                 redraw_display(FALSE);
1984                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1986         } else {
1987                 bool *option = menu[i].data;
1989                 *option = !*option;
1990                 redraw_display(FALSE);
1991                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1992         }
1995 static void
1996 maximize_view(struct view *view, bool redraw)
1998         memset(display, 0, sizeof(display));
1999         current_view = 0;
2000         display[current_view] = view;
2001         resize_display();
2002         if (redraw) {
2003                 redraw_display(FALSE);
2004                 report("");
2005         }
2009 /*
2010  * Navigation
2011  */
2013 static bool
2014 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2016         if (lineno >= view->lines)
2017                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2019         if (offset > lineno || offset + view->height <= lineno) {
2020                 unsigned long half = view->height / 2;
2022                 if (lineno > half)
2023                         offset = lineno - half;
2024                 else
2025                         offset = 0;
2026         }
2028         if (offset != view->offset || lineno != view->lineno) {
2029                 view->offset = offset;
2030                 view->lineno = lineno;
2031                 return TRUE;
2032         }
2034         return FALSE;
2037 /* Scrolling backend */
2038 static void
2039 do_scroll_view(struct view *view, int lines)
2041         bool redraw_current_line = FALSE;
2043         /* The rendering expects the new offset. */
2044         view->offset += lines;
2046         assert(0 <= view->offset && view->offset < view->lines);
2047         assert(lines);
2049         /* Move current line into the view. */
2050         if (view->lineno < view->offset) {
2051                 view->lineno = view->offset;
2052                 redraw_current_line = TRUE;
2053         } else if (view->lineno >= view->offset + view->height) {
2054                 view->lineno = view->offset + view->height - 1;
2055                 redraw_current_line = TRUE;
2056         }
2058         assert(view->offset <= view->lineno && view->lineno < view->lines);
2060         /* Redraw the whole screen if scrolling is pointless. */
2061         if (view->height < ABS(lines)) {
2062                 redraw_view(view);
2064         } else {
2065                 int line = lines > 0 ? view->height - lines : 0;
2066                 int end = line + ABS(lines);
2068                 scrollok(view->win, TRUE);
2069                 wscrl(view->win, lines);
2070                 scrollok(view->win, FALSE);
2072                 while (line < end && draw_view_line(view, line))
2073                         line++;
2075                 if (redraw_current_line)
2076                         draw_view_line(view, view->lineno - view->offset);
2077                 wnoutrefresh(view->win);
2078         }
2080         view->has_scrolled = TRUE;
2081         report("");
2084 /* Scroll frontend */
2085 static void
2086 scroll_view(struct view *view, enum request request)
2088         int lines = 1;
2090         assert(view_is_displayed(view));
2092         switch (request) {
2093         case REQ_SCROLL_FIRST_COL:
2094                 view->yoffset = 0;
2095                 redraw_view_from(view, 0);
2096                 report("");
2097                 return;
2098         case REQ_SCROLL_LEFT:
2099                 if (view->yoffset == 0) {
2100                         report("Cannot scroll beyond the first column");
2101                         return;
2102                 }
2103                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2104                         view->yoffset = 0;
2105                 else
2106                         view->yoffset -= apply_step(opt_hscroll, view->width);
2107                 redraw_view_from(view, 0);
2108                 report("");
2109                 return;
2110         case REQ_SCROLL_RIGHT:
2111                 view->yoffset += apply_step(opt_hscroll, view->width);
2112                 redraw_view(view);
2113                 report("");
2114                 return;
2115         case REQ_SCROLL_PAGE_DOWN:
2116                 lines = view->height;
2117         case REQ_SCROLL_LINE_DOWN:
2118                 if (view->offset + lines > view->lines)
2119                         lines = view->lines - view->offset;
2121                 if (lines == 0 || view->offset + view->height >= view->lines) {
2122                         report("Cannot scroll beyond the last line");
2123                         return;
2124                 }
2125                 break;
2127         case REQ_SCROLL_PAGE_UP:
2128                 lines = view->height;
2129         case REQ_SCROLL_LINE_UP:
2130                 if (lines > view->offset)
2131                         lines = view->offset;
2133                 if (lines == 0) {
2134                         report("Cannot scroll beyond the first line");
2135                         return;
2136                 }
2138                 lines = -lines;
2139                 break;
2141         default:
2142                 die("request %d not handled in switch", request);
2143         }
2145         do_scroll_view(view, lines);
2148 /* Cursor moving */
2149 static void
2150 move_view(struct view *view, enum request request)
2152         int scroll_steps = 0;
2153         int steps;
2155         switch (request) {
2156         case REQ_MOVE_FIRST_LINE:
2157                 steps = -view->lineno;
2158                 break;
2160         case REQ_MOVE_LAST_LINE:
2161                 steps = view->lines - view->lineno - 1;
2162                 break;
2164         case REQ_MOVE_PAGE_UP:
2165                 steps = view->height > view->lineno
2166                       ? -view->lineno : -view->height;
2167                 break;
2169         case REQ_MOVE_PAGE_DOWN:
2170                 steps = view->lineno + view->height >= view->lines
2171                       ? view->lines - view->lineno - 1 : view->height;
2172                 break;
2174         case REQ_MOVE_UP:
2175                 steps = -1;
2176                 break;
2178         case REQ_MOVE_DOWN:
2179                 steps = 1;
2180                 break;
2182         default:
2183                 die("request %d not handled in switch", request);
2184         }
2186         if (steps <= 0 && view->lineno == 0) {
2187                 report("Cannot move beyond the first line");
2188                 return;
2190         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2191                 report("Cannot move beyond the last line");
2192                 return;
2193         }
2195         /* Move the current line */
2196         view->lineno += steps;
2197         assert(0 <= view->lineno && view->lineno < view->lines);
2199         /* Check whether the view needs to be scrolled */
2200         if (view->lineno < view->offset ||
2201             view->lineno >= view->offset + view->height) {
2202                 scroll_steps = steps;
2203                 if (steps < 0 && -steps > view->offset) {
2204                         scroll_steps = -view->offset;
2206                 } else if (steps > 0) {
2207                         if (view->lineno == view->lines - 1 &&
2208                             view->lines > view->height) {
2209                                 scroll_steps = view->lines - view->offset - 1;
2210                                 if (scroll_steps >= view->height)
2211                                         scroll_steps -= view->height - 1;
2212                         }
2213                 }
2214         }
2216         if (!view_is_displayed(view)) {
2217                 view->offset += scroll_steps;
2218                 assert(0 <= view->offset && view->offset < view->lines);
2219                 view->ops->select(view, &view->line[view->lineno]);
2220                 return;
2221         }
2223         /* Repaint the old "current" line if we be scrolling */
2224         if (ABS(steps) < view->height)
2225                 draw_view_line(view, view->lineno - steps - view->offset);
2227         if (scroll_steps) {
2228                 do_scroll_view(view, scroll_steps);
2229                 return;
2230         }
2232         /* Draw the current line */
2233         draw_view_line(view, view->lineno - view->offset);
2235         wnoutrefresh(view->win);
2236         report("");
2240 /*
2241  * Searching
2242  */
2244 static void search_view(struct view *view, enum request request);
2246 static bool
2247 grep_text(struct view *view, const char *text[])
2249         regmatch_t pmatch;
2250         size_t i;
2252         for (i = 0; text[i]; i++)
2253                 if (*text[i] &&
2254                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2255                         return TRUE;
2256         return FALSE;
2259 static void
2260 select_view_line(struct view *view, unsigned long lineno)
2262         unsigned long old_lineno = view->lineno;
2263         unsigned long old_offset = view->offset;
2265         if (goto_view_line(view, view->offset, lineno)) {
2266                 if (view_is_displayed(view)) {
2267                         if (old_offset != view->offset) {
2268                                 redraw_view(view);
2269                         } else {
2270                                 draw_view_line(view, old_lineno - view->offset);
2271                                 draw_view_line(view, view->lineno - view->offset);
2272                                 wnoutrefresh(view->win);
2273                         }
2274                 } else {
2275                         view->ops->select(view, &view->line[view->lineno]);
2276                 }
2277         }
2280 static void
2281 find_next(struct view *view, enum request request)
2283         unsigned long lineno = view->lineno;
2284         int direction;
2286         if (!*view->grep) {
2287                 if (!*opt_search)
2288                         report("No previous search");
2289                 else
2290                         search_view(view, request);
2291                 return;
2292         }
2294         switch (request) {
2295         case REQ_SEARCH:
2296         case REQ_FIND_NEXT:
2297                 direction = 1;
2298                 break;
2300         case REQ_SEARCH_BACK:
2301         case REQ_FIND_PREV:
2302                 direction = -1;
2303                 break;
2305         default:
2306                 return;
2307         }
2309         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2310                 lineno += direction;
2312         /* Note, lineno is unsigned long so will wrap around in which case it
2313          * will become bigger than view->lines. */
2314         for (; lineno < view->lines; lineno += direction) {
2315                 if (view->ops->grep(view, &view->line[lineno])) {
2316                         select_view_line(view, lineno);
2317                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2318                         return;
2319                 }
2320         }
2322         report("No match found for '%s'", view->grep);
2325 static void
2326 search_view(struct view *view, enum request request)
2328         int regex_err;
2330         if (view->regex) {
2331                 regfree(view->regex);
2332                 *view->grep = 0;
2333         } else {
2334                 view->regex = calloc(1, sizeof(*view->regex));
2335                 if (!view->regex)
2336                         return;
2337         }
2339         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2340         if (regex_err != 0) {
2341                 char buf[SIZEOF_STR] = "unknown error";
2343                 regerror(regex_err, view->regex, buf, sizeof(buf));
2344                 report("Search failed: %s", buf);
2345                 return;
2346         }
2348         string_copy(view->grep, opt_search);
2350         find_next(view, request);
2353 /*
2354  * Incremental updating
2355  */
2357 static void
2358 reset_view(struct view *view)
2360         int i;
2362         for (i = 0; i < view->lines; i++)
2363                 free(view->line[i].data);
2364         free(view->line);
2366         view->p_offset = view->offset;
2367         view->p_yoffset = view->yoffset;
2368         view->p_lineno = view->lineno;
2370         view->line = NULL;
2371         view->offset = 0;
2372         view->yoffset = 0;
2373         view->lines  = 0;
2374         view->lineno = 0;
2375         view->vid[0] = 0;
2376         view->update_secs = 0;
2379 static const char *
2380 format_arg(const char *name)
2382         static struct {
2383                 const char *name;
2384                 size_t namelen;
2385                 const char *value;
2386                 const char *value_if_empty;
2387         } vars[] = {
2388 #define FORMAT_VAR(name, value, value_if_empty) \
2389         { name, STRING_SIZE(name), value, value_if_empty }
2390                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2391                 FORMAT_VAR("%(file)",           opt_file,       ""),
2392                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2393                 FORMAT_VAR("%(head)",           ref_head,       ""),
2394                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2395                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2396                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2397         };
2398         int i;
2400         for (i = 0; i < ARRAY_SIZE(vars); i++)
2401                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2402                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2404         report("Unknown replacement: `%s`", name);
2405         return NULL;
2408 static bool
2409 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2411         char buf[SIZEOF_STR];
2412         int argc;
2414         argv_free(*dst_argv);
2416         for (argc = 0; src_argv[argc]; argc++) {
2417                 const char *arg = src_argv[argc];
2418                 size_t bufpos = 0;
2420                 if (!strcmp(arg, "%(fileargs)")) {
2421                         if (!argv_append_array(dst_argv, opt_file_argv))
2422                                 break;
2423                         continue;
2425                 } else if (!strcmp(arg, "%(diffargs)")) {
2426                         if (!argv_append_array(dst_argv, opt_diff_argv))
2427                                 break;
2428                         continue;
2430                 } else if (!strcmp(arg, "%(blameargs)")) {
2431                         if (!argv_append_array(dst_argv, opt_blame_argv))
2432                                 break;
2433                         continue;
2435                 } else if (!strcmp(arg, "%(revargs)") ||
2436                            (first && !strcmp(arg, "%(commit)"))) {
2437                         if (!argv_append_array(dst_argv, opt_rev_argv))
2438                                 break;
2439                         continue;
2440                 }
2442                 while (arg) {
2443                         char *next = strstr(arg, "%(");
2444                         int len = next - arg;
2445                         const char *value;
2447                         if (!next) {
2448                                 len = strlen(arg);
2449                                 value = "";
2451                         } else {
2452                                 value = format_arg(next);
2454                                 if (!value) {
2455                                         return FALSE;
2456                                 }
2457                         }
2459                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2460                                 return FALSE;
2462                         arg = next ? strchr(next, ')') + 1 : NULL;
2463                 }
2465                 if (!argv_append(dst_argv, buf))
2466                         break;
2467         }
2469         return src_argv[argc] == NULL;
2472 static bool
2473 restore_view_position(struct view *view)
2475         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2476                 return FALSE;
2478         /* Changing the view position cancels the restoring. */
2479         /* FIXME: Changing back to the first line is not detected. */
2480         if (view->offset != 0 || view->lineno != 0) {
2481                 view->p_restore = FALSE;
2482                 return FALSE;
2483         }
2485         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2486             view_is_displayed(view))
2487                 werase(view->win);
2489         view->yoffset = view->p_yoffset;
2490         view->p_restore = FALSE;
2492         return TRUE;
2495 static void
2496 end_update(struct view *view, bool force)
2498         if (!view->pipe)
2499                 return;
2500         while (!view->ops->read(view, NULL))
2501                 if (!force)
2502                         return;
2503         if (force)
2504                 io_kill(view->pipe);
2505         io_done(view->pipe);
2506         view->pipe = NULL;
2509 static void
2510 setup_update(struct view *view, const char *vid)
2512         reset_view(view);
2513         string_copy_rev(view->vid, vid);
2514         view->pipe = &view->io;
2515         view->start_time = time(NULL);
2518 static bool
2519 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2521         bool extra = !!(flags & (OPEN_EXTRA));
2522         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2523         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2525         if (!reload && !strcmp(view->vid, view->id))
2526                 return TRUE;
2528         if (view->pipe) {
2529                 if (extra)
2530                         io_done(view->pipe);
2531                 else
2532                         end_update(view, TRUE);
2533         }
2535         if (!refresh) {
2536                 view->dir = dir;
2537                 if (!format_argv(&view->argv, argv, !view->prev))
2538                         return FALSE;
2540                 /* Put the current ref_* value to the view title ref
2541                  * member. This is needed by the blob view. Most other
2542                  * views sets it automatically after loading because the
2543                  * first line is a commit line. */
2544                 string_copy_rev(view->ref, view->id);
2545         }
2547         if (view->argv && view->argv[0] &&
2548             !io_run(&view->io, IO_RD, view->dir, view->argv))
2549                 return FALSE;
2551         if (!extra)
2552                 setup_update(view, view->id);
2554         return TRUE;
2557 static bool
2558 view_open(struct view *view, enum open_flags flags)
2560         return begin_update(view, NULL, NULL, flags);
2563 static bool
2564 update_view(struct view *view)
2566         char out_buffer[BUFSIZ * 2];
2567         char *line;
2568         /* Clear the view and redraw everything since the tree sorting
2569          * might have rearranged things. */
2570         bool redraw = view->lines == 0;
2571         bool can_read = TRUE;
2573         if (!view->pipe)
2574                 return TRUE;
2576         if (!io_can_read(view->pipe, FALSE)) {
2577                 if (view->lines == 0 && view_is_displayed(view)) {
2578                         time_t secs = time(NULL) - view->start_time;
2580                         if (secs > 1 && secs > view->update_secs) {
2581                                 if (view->update_secs == 0)
2582                                         redraw_view(view);
2583                                 update_view_title(view);
2584                                 view->update_secs = secs;
2585                         }
2586                 }
2587                 return TRUE;
2588         }
2590         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2591                 if (opt_iconv_in != ICONV_NONE) {
2592                         ICONV_CONST char *inbuf = line;
2593                         size_t inlen = strlen(line) + 1;
2595                         char *outbuf = out_buffer;
2596                         size_t outlen = sizeof(out_buffer);
2598                         size_t ret;
2600                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2601                         if (ret != (size_t) -1)
2602                                 line = out_buffer;
2603                 }
2605                 if (!view->ops->read(view, line)) {
2606                         report("Allocation failure");
2607                         end_update(view, TRUE);
2608                         return FALSE;
2609                 }
2610         }
2612         {
2613                 unsigned long lines = view->lines;
2614                 int digits;
2616                 for (digits = 0; lines; digits++)
2617                         lines /= 10;
2619                 /* Keep the displayed view in sync with line number scaling. */
2620                 if (digits != view->digits) {
2621                         view->digits = digits;
2622                         if (opt_line_number || view->type == VIEW_BLAME)
2623                                 redraw = TRUE;
2624                 }
2625         }
2627         if (io_error(view->pipe)) {
2628                 report("Failed to read: %s", io_strerror(view->pipe));
2629                 end_update(view, TRUE);
2631         } else if (io_eof(view->pipe)) {
2632                 if (view_is_displayed(view))
2633                         report("");
2634                 end_update(view, FALSE);
2635         }
2637         if (restore_view_position(view))
2638                 redraw = TRUE;
2640         if (!view_is_displayed(view))
2641                 return TRUE;
2643         if (redraw)
2644                 redraw_view_from(view, 0);
2645         else
2646                 redraw_view_dirty(view);
2648         /* Update the title _after_ the redraw so that if the redraw picks up a
2649          * commit reference in view->ref it'll be available here. */
2650         update_view_title(view);
2651         return TRUE;
2654 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2656 static struct line *
2657 add_line_data(struct view *view, void *data, enum line_type type)
2659         struct line *line;
2661         if (!realloc_lines(&view->line, view->lines, 1))
2662                 return NULL;
2664         line = &view->line[view->lines++];
2665         memset(line, 0, sizeof(*line));
2666         line->type = type;
2667         line->data = data;
2668         line->dirty = 1;
2670         return line;
2673 static struct line *
2674 add_line_text(struct view *view, const char *text, enum line_type type)
2676         char *data = text ? strdup(text) : NULL;
2678         return data ? add_line_data(view, data, type) : NULL;
2681 static struct line *
2682 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2684         char buf[SIZEOF_STR];
2685         va_list args;
2687         va_start(args, fmt);
2688         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2689                 buf[0] = 0;
2690         va_end(args);
2692         return buf[0] ? add_line_text(view, buf, type) : NULL;
2695 /*
2696  * View opening
2697  */
2699 static void
2700 load_view(struct view *view, enum open_flags flags)
2702         if (view->pipe)
2703                 end_update(view, TRUE);
2704         if (!view->ops->open(view, flags)) {
2705                 report("Failed to load %s view", view->name);
2706                 return;
2707         }
2708         restore_view_position(view);
2710         if (view->pipe && view->lines == 0) {
2711                 /* Clear the old view and let the incremental updating refill
2712                  * the screen. */
2713                 werase(view->win);
2714                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2715                 report("");
2716         } else if (view_is_displayed(view)) {
2717                 redraw_view(view);
2718                 report("");
2719         }
2722 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2723 #define reload_view(view) load_view(view, OPEN_RELOAD)
2725 static void
2726 split_view(struct view *prev, struct view *view)
2728         display[1] = view;
2729         current_view = 1;
2730         view->parent = prev;
2731         resize_display();
2733         if (prev->lineno - prev->offset >= prev->height) {
2734                 /* Take the title line into account. */
2735                 int lines = prev->lineno - prev->offset - prev->height + 1;
2737                 /* Scroll the view that was split if the current line is
2738                  * outside the new limited view. */
2739                 do_scroll_view(prev, lines);
2740         }
2742         if (view != prev && view_is_displayed(prev)) {
2743                 /* "Blur" the previous view. */
2744                 update_view_title(prev);
2745         }
2748 static void
2749 open_view(struct view *prev, enum request request, enum open_flags flags)
2751         bool split = !!(flags & OPEN_SPLIT);
2752         bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2753         struct view *view = VIEW(request);
2754         int nviews = displayed_views();
2756         assert(flags ^ OPEN_REFRESH);
2758         if (view == prev && nviews == 1 && !reload) {
2759                 report("Already in %s view", view->name);
2760                 return;
2761         }
2763         if (view->git_dir && !opt_git_dir[0]) {
2764                 report("The %s view is disabled in pager view", view->name);
2765                 return;
2766         }
2768         if (split) {
2769                 split_view(prev, view);
2770         } else {
2771                 maximize_view(view, FALSE);
2772         }
2774         /* No prev signals that this is the first loaded view. */
2775         if (prev && view != prev) {
2776                 view->prev = prev;
2777         }
2779         load_view(view, flags);
2782 static void
2783 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2785         enum request request = view - views + REQ_OFFSET + 1;
2787         if (view->pipe)
2788                 end_update(view, TRUE);
2789         view->dir = dir;
2790         
2791         if (!argv_copy(&view->argv, argv)) {
2792                 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2793         } else {
2794                 open_view(prev, request, flags | OPEN_PREPARED);
2795         }
2798 static void
2799 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2801         const char *file_argv[] = { opt_cdup, file , NULL };
2803         open_argv(prev, view, file_argv, opt_cdup, flags); 
2806 static void
2807 open_external_viewer(const char *argv[], const char *dir)
2809         def_prog_mode();           /* save current tty modes */
2810         endwin();                  /* restore original tty modes */
2811         io_run_fg(argv, dir);
2812         fprintf(stderr, "Press Enter to continue");
2813         getc(opt_tty);
2814         reset_prog_mode();
2815         redraw_display(TRUE);
2818 static void
2819 open_mergetool(const char *file)
2821         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2823         open_external_viewer(mergetool_argv, opt_cdup);
2826 static void
2827 open_editor(const char *file)
2829         const char *editor_argv[] = { "vi", file, NULL };
2830         const char *editor;
2832         editor = getenv("GIT_EDITOR");
2833         if (!editor && *opt_editor)
2834                 editor = opt_editor;
2835         if (!editor)
2836                 editor = getenv("VISUAL");
2837         if (!editor)
2838                 editor = getenv("EDITOR");
2839         if (!editor)
2840                 editor = "vi";
2842         editor_argv[0] = editor;
2843         open_external_viewer(editor_argv, opt_cdup);
2846 static void
2847 open_run_request(enum request request)
2849         struct run_request *req = get_run_request(request);
2850         const char **argv = NULL;
2852         if (!req) {
2853                 report("Unknown run request");
2854                 return;
2855         }
2857         if (format_argv(&argv, req->argv, FALSE))
2858                 open_external_viewer(argv, NULL);
2859         if (argv)
2860                 argv_free(argv);
2861         free(argv);
2864 /*
2865  * User request switch noodle
2866  */
2868 static int
2869 view_driver(struct view *view, enum request request)
2871         int i;
2873         if (request == REQ_NONE)
2874                 return TRUE;
2876         if (request > REQ_NONE) {
2877                 open_run_request(request);
2878                 view_request(view, REQ_REFRESH);
2879                 return TRUE;
2880         }
2882         request = view_request(view, request);
2883         if (request == REQ_NONE)
2884                 return TRUE;
2886         switch (request) {
2887         case REQ_MOVE_UP:
2888         case REQ_MOVE_DOWN:
2889         case REQ_MOVE_PAGE_UP:
2890         case REQ_MOVE_PAGE_DOWN:
2891         case REQ_MOVE_FIRST_LINE:
2892         case REQ_MOVE_LAST_LINE:
2893                 move_view(view, request);
2894                 break;
2896         case REQ_SCROLL_FIRST_COL:
2897         case REQ_SCROLL_LEFT:
2898         case REQ_SCROLL_RIGHT:
2899         case REQ_SCROLL_LINE_DOWN:
2900         case REQ_SCROLL_LINE_UP:
2901         case REQ_SCROLL_PAGE_DOWN:
2902         case REQ_SCROLL_PAGE_UP:
2903                 scroll_view(view, request);
2904                 break;
2906         case REQ_VIEW_BLAME:
2907                 if (!opt_file[0]) {
2908                         report("No file chosen, press %s to open tree view",
2909                                get_key(view->keymap, REQ_VIEW_TREE));
2910                         break;
2911                 }
2912                 open_view(view, request, OPEN_DEFAULT);
2913                 break;
2915         case REQ_VIEW_BLOB:
2916                 if (!ref_blob[0]) {
2917                         report("No file chosen, press %s to open tree view",
2918                                get_key(view->keymap, REQ_VIEW_TREE));
2919                         break;
2920                 }
2921                 open_view(view, request, OPEN_DEFAULT);
2922                 break;
2924         case REQ_VIEW_PAGER:
2925                 if (view == NULL) {
2926                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2927                                 die("Failed to open stdin");
2928                         open_view(view, request, OPEN_PREPARED);
2929                         break;
2930                 }
2932                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2933                         report("No pager content, press %s to run command from prompt",
2934                                get_key(view->keymap, REQ_PROMPT));
2935                         break;
2936                 }
2937                 open_view(view, request, OPEN_DEFAULT);
2938                 break;
2940         case REQ_VIEW_STAGE:
2941                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2942                         report("No stage content, press %s to open the status view and choose file",
2943                                get_key(view->keymap, REQ_VIEW_STATUS));
2944                         break;
2945                 }
2946                 open_view(view, request, OPEN_DEFAULT);
2947                 break;
2949         case REQ_VIEW_STATUS:
2950                 if (opt_is_inside_work_tree == FALSE) {
2951                         report("The status view requires a working tree");
2952                         break;
2953                 }
2954                 open_view(view, request, OPEN_DEFAULT);
2955                 break;
2957         case REQ_VIEW_MAIN:
2958         case REQ_VIEW_DIFF:
2959         case REQ_VIEW_LOG:
2960         case REQ_VIEW_TREE:
2961         case REQ_VIEW_HELP:
2962         case REQ_VIEW_BRANCH:
2963                 open_view(view, request, OPEN_DEFAULT);
2964                 break;
2966         case REQ_NEXT:
2967         case REQ_PREVIOUS:
2968                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2970                 if (view->parent) {
2971                         int line;
2973                         view = view->parent;
2974                         line = view->lineno;
2975                         move_view(view, request);
2976                         if (view_is_displayed(view))
2977                                 update_view_title(view);
2978                         if (line != view->lineno)
2979                                 view_request(view, REQ_ENTER);
2980                 } else {
2981                         move_view(view, request);
2982                 }
2983                 break;
2985         case REQ_VIEW_NEXT:
2986         {
2987                 int nviews = displayed_views();
2988                 int next_view = (current_view + 1) % nviews;
2990                 if (next_view == current_view) {
2991                         report("Only one view is displayed");
2992                         break;
2993                 }
2995                 current_view = next_view;
2996                 /* Blur out the title of the previous view. */
2997                 update_view_title(view);
2998                 report("");
2999                 break;
3000         }
3001         case REQ_REFRESH:
3002                 report("Refreshing is not yet supported for the %s view", view->name);
3003                 break;
3005         case REQ_MAXIMIZE:
3006                 if (displayed_views() == 2)
3007                         maximize_view(view, TRUE);
3008                 break;
3010         case REQ_OPTIONS:
3011         case REQ_TOGGLE_LINENO:
3012         case REQ_TOGGLE_DATE:
3013         case REQ_TOGGLE_AUTHOR:
3014         case REQ_TOGGLE_GRAPHIC:
3015         case REQ_TOGGLE_REV_GRAPH:
3016         case REQ_TOGGLE_REFS:
3017                 toggle_option(request);
3018                 break;
3020         case REQ_TOGGLE_SORT_FIELD:
3021         case REQ_TOGGLE_SORT_ORDER:
3022                 report("Sorting is not yet supported for the %s view", view->name);
3023                 break;
3025         case REQ_SEARCH:
3026         case REQ_SEARCH_BACK:
3027                 search_view(view, request);
3028                 break;
3030         case REQ_FIND_NEXT:
3031         case REQ_FIND_PREV:
3032                 find_next(view, request);
3033                 break;
3035         case REQ_STOP_LOADING:
3036                 foreach_view(view, i) {
3037                         if (view->pipe)
3038                                 report("Stopped loading the %s view", view->name),
3039                         end_update(view, TRUE);
3040                 }
3041                 break;
3043         case REQ_SHOW_VERSION:
3044                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3045                 return TRUE;
3047         case REQ_SCREEN_REDRAW:
3048                 redraw_display(TRUE);
3049                 break;
3051         case REQ_EDIT:
3052                 report("Nothing to edit");
3053                 break;
3055         case REQ_ENTER:
3056                 report("Nothing to enter");
3057                 break;
3059         case REQ_VIEW_CLOSE:
3060                 /* XXX: Mark closed views by letting view->prev point to the
3061                  * view itself. Parents to closed view should never be
3062                  * followed. */
3063                 if (view->prev && view->prev != view) {
3064                         maximize_view(view->prev, TRUE);
3065                         view->prev = view;
3066                         break;
3067                 }
3068                 /* Fall-through */
3069         case REQ_QUIT:
3070                 return FALSE;
3072         default:
3073                 report("Unknown key, press %s for help",
3074                        get_key(view->keymap, REQ_VIEW_HELP));
3075                 return TRUE;
3076         }
3078         return TRUE;
3082 /*
3083  * View backend utilities
3084  */
3086 enum sort_field {
3087         ORDERBY_NAME,
3088         ORDERBY_DATE,
3089         ORDERBY_AUTHOR,
3090 };
3092 struct sort_state {
3093         const enum sort_field *fields;
3094         size_t size, current;
3095         bool reverse;
3096 };
3098 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3099 #define get_sort_field(state) ((state).fields[(state).current])
3100 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3102 static void
3103 sort_view(struct view *view, enum request request, struct sort_state *state,
3104           int (*compare)(const void *, const void *))
3106         switch (request) {
3107         case REQ_TOGGLE_SORT_FIELD:
3108                 state->current = (state->current + 1) % state->size;
3109                 break;
3111         case REQ_TOGGLE_SORT_ORDER:
3112                 state->reverse = !state->reverse;
3113                 break;
3114         default:
3115                 die("Not a sort request");
3116         }
3118         qsort(view->line, view->lines, sizeof(*view->line), compare);
3119         redraw_view(view);
3122 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3124 /* Small author cache to reduce memory consumption. It uses binary
3125  * search to lookup or find place to position new entries. No entries
3126  * are ever freed. */
3127 static const char *
3128 get_author(const char *name)
3130         static const char **authors;
3131         static size_t authors_size;
3132         int from = 0, to = authors_size - 1;
3134         while (from <= to) {
3135                 size_t pos = (to + from) / 2;
3136                 int cmp = strcmp(name, authors[pos]);
3138                 if (!cmp)
3139                         return authors[pos];
3141                 if (cmp < 0)
3142                         to = pos - 1;
3143                 else
3144                         from = pos + 1;
3145         }
3147         if (!realloc_authors(&authors, authors_size, 1))
3148                 return NULL;
3149         name = strdup(name);
3150         if (!name)
3151                 return NULL;
3153         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3154         authors[from] = name;
3155         authors_size++;
3157         return name;
3160 static void
3161 parse_timesec(struct time *time, const char *sec)
3163         time->sec = (time_t) atol(sec);
3166 static void
3167 parse_timezone(struct time *time, const char *zone)
3169         long tz;
3171         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3172         tz += ('0' - zone[2]) * 60 * 60;
3173         tz += ('0' - zone[3]) * 60 * 10;
3174         tz += ('0' - zone[4]) * 60;
3176         if (zone[0] == '-')
3177                 tz = -tz;
3179         time->tz = tz;
3180         time->sec -= tz;
3183 /* Parse author lines where the name may be empty:
3184  *      author  <email@address.tld> 1138474660 +0100
3185  */
3186 static void
3187 parse_author_line(char *ident, const char **author, struct time *time)
3189         char *nameend = strchr(ident, '<');
3190         char *emailend = strchr(ident, '>');
3192         if (nameend && emailend)
3193                 *nameend = *emailend = 0;
3194         ident = chomp_string(ident);
3195         if (!*ident) {
3196                 if (nameend)
3197                         ident = chomp_string(nameend + 1);
3198                 if (!*ident)
3199                         ident = "Unknown";
3200         }
3202         *author = get_author(ident);
3204         /* Parse epoch and timezone */
3205         if (emailend && emailend[1] == ' ') {
3206                 char *secs = emailend + 2;
3207                 char *zone = strchr(secs, ' ');
3209                 parse_timesec(time, secs);
3211                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3212                         parse_timezone(time, zone + 1);
3213         }
3216 /*
3217  * Pager backend
3218  */
3220 static bool
3221 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3223         if (opt_line_number && draw_lineno(view, lineno))
3224                 return TRUE;
3226         draw_text(view, line->type, line->data);
3227         return TRUE;
3230 static bool
3231 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3233         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3234         char ref[SIZEOF_STR];
3236         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3237                 return TRUE;
3239         /* This is the only fatal call, since it can "corrupt" the buffer. */
3240         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3241                 return FALSE;
3243         return TRUE;
3246 static void
3247 add_pager_refs(struct view *view, struct line *line)
3249         char buf[SIZEOF_STR];
3250         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3251         struct ref_list *list;
3252         size_t bufpos = 0, i;
3253         const char *sep = "Refs: ";
3254         bool is_tag = FALSE;
3256         assert(line->type == LINE_COMMIT);
3258         list = get_ref_list(commit_id);
3259         if (!list) {
3260                 if (view->type == VIEW_DIFF)
3261                         goto try_add_describe_ref;
3262                 return;
3263         }
3265         for (i = 0; i < list->size; i++) {
3266                 struct ref *ref = list->refs[i];
3267                 const char *fmt = ref->tag    ? "%s[%s]" :
3268                                   ref->remote ? "%s<%s>" : "%s%s";
3270                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3271                         return;
3272                 sep = ", ";
3273                 if (ref->tag)
3274                         is_tag = TRUE;
3275         }
3277         if (!is_tag && view->type == VIEW_DIFF) {
3278 try_add_describe_ref:
3279                 /* Add <tag>-g<commit_id> "fake" reference. */
3280                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3281                         return;
3282         }
3284         if (bufpos == 0)
3285                 return;
3287         add_line_text(view, buf, LINE_PP_REFS);
3290 static bool
3291 pager_read(struct view *view, char *data)
3293         struct line *line;
3295         if (!data)
3296                 return TRUE;
3298         line = add_line_text(view, data, get_line_type(data));
3299         if (!line)
3300                 return FALSE;
3302         if (line->type == LINE_COMMIT &&
3303             (view->type == VIEW_DIFF ||
3304              view->type == VIEW_LOG))
3305                 add_pager_refs(view, line);
3307         return TRUE;
3310 static enum request
3311 pager_request(struct view *view, enum request request, struct line *line)
3313         int split = 0;
3315         if (request != REQ_ENTER)
3316                 return request;
3318         if (line->type == LINE_COMMIT &&
3319            (view->type == VIEW_LOG ||
3320             view->type == VIEW_PAGER)) {
3321                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3322                 split = 1;
3323         }
3325         /* Always scroll the view even if it was split. That way
3326          * you can use Enter to scroll through the log view and
3327          * split open each commit diff. */
3328         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3330         /* FIXME: A minor workaround. Scrolling the view will call report("")
3331          * but if we are scrolling a non-current view this won't properly
3332          * update the view title. */
3333         if (split)
3334                 update_view_title(view);
3336         return REQ_NONE;
3339 static bool
3340 pager_grep(struct view *view, struct line *line)
3342         const char *text[] = { line->data, NULL };
3344         return grep_text(view, text);
3347 static void
3348 pager_select(struct view *view, struct line *line)
3350         if (line->type == LINE_COMMIT) {
3351                 char *text = (char *)line->data + STRING_SIZE("commit ");
3353                 if (view->type != VIEW_PAGER)
3354                         string_copy_rev(view->ref, text);
3355                 string_copy_rev(ref_commit, text);
3356         }
3359 static struct view_ops pager_ops = {
3360         "line",
3361         view_open,
3362         pager_read,
3363         pager_draw,
3364         pager_request,
3365         pager_grep,
3366         pager_select,
3367 };
3369 static bool
3370 log_open(struct view *view, enum open_flags flags)
3372         static const char *log_argv[] = {
3373                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3374         };
3376         return begin_update(view, NULL, log_argv, flags);
3379 static enum request
3380 log_request(struct view *view, enum request request, struct line *line)
3382         switch (request) {
3383         case REQ_REFRESH:
3384                 load_refs();
3385                 refresh_view(view);
3386                 return REQ_NONE;
3387         default:
3388                 return pager_request(view, request, line);
3389         }
3392 static struct view_ops log_ops = {
3393         "line",
3394         log_open,
3395         pager_read,
3396         pager_draw,
3397         log_request,
3398         pager_grep,
3399         pager_select,
3400 };
3402 static bool
3403 diff_open(struct view *view, enum open_flags flags)
3405         static const char *diff_argv[] = {
3406                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3407                         "--patch-with-stat", "--find-copies-harder", "-C",
3408                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3409         };
3411         return begin_update(view, NULL, diff_argv, flags);
3414 static bool
3415 diff_read(struct view *view, char *data)
3417         if (!data) {
3418                 /* Fall back to retry if no diff will be shown. */
3419                 if (view->lines == 0 && opt_file_argv) {
3420                         int pos = argv_size(view->argv)
3421                                 - argv_size(opt_file_argv) - 1;
3423                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3424                                 for (; view->argv[pos]; pos++) {
3425                                         free((void *) view->argv[pos]);
3426                                         view->argv[pos] = NULL;
3427                                 }
3429                                 if (view->pipe)
3430                                         io_done(view->pipe);
3431                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3432                                         return FALSE;
3433                         }
3434                 }
3435                 return TRUE;
3436         }
3438         return pager_read(view, data);
3441 static struct view_ops diff_ops = {
3442         "line",
3443         diff_open,
3444         diff_read,
3445         pager_draw,
3446         pager_request,
3447         pager_grep,
3448         pager_select,
3449 };
3451 /*
3452  * Help backend
3453  */
3455 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
3457 static bool
3458 help_open_keymap_title(struct view *view, enum keymap keymap)
3460         struct line *line;
3462         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3463                                help_keymap_hidden[keymap] ? '+' : '-',
3464                                enum_name(keymap_map[keymap]));
3465         if (line)
3466                 line->other = keymap;
3468         return help_keymap_hidden[keymap];
3471 static void
3472 help_open_keymap(struct view *view, enum keymap keymap)
3474         const char *group = NULL;
3475         char buf[SIZEOF_STR];
3476         size_t bufpos;
3477         bool add_title = TRUE;
3478         int i;
3480         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3481                 const char *key = NULL;
3483                 if (req_info[i].request == REQ_NONE)
3484                         continue;
3486                 if (!req_info[i].request) {
3487                         group = req_info[i].help;
3488                         continue;
3489                 }
3491                 key = get_keys(keymap, req_info[i].request, TRUE);
3492                 if (!key || !*key)
3493                         continue;
3495                 if (add_title && help_open_keymap_title(view, keymap))
3496                         return;
3497                 add_title = FALSE;
3499                 if (group) {
3500                         add_line_text(view, group, LINE_HELP_GROUP);
3501                         group = NULL;
3502                 }
3504                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3505                                 enum_name(req_info[i]), req_info[i].help);
3506         }
3508         group = "External commands:";
3510         for (i = 0; i < run_requests; i++) {
3511                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3512                 const char *key;
3513                 int argc;
3515                 if (!req || req->keymap != keymap)
3516                         continue;
3518                 key = get_key_name(req->key);
3519                 if (!*key)
3520                         key = "(no key defined)";
3522                 if (add_title && help_open_keymap_title(view, keymap))
3523                         return;
3524                 if (group) {
3525                         add_line_text(view, group, LINE_HELP_GROUP);
3526                         group = NULL;
3527                 }
3529                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3530                         if (!string_format_from(buf, &bufpos, "%s%s",
3531                                                 argc ? " " : "", req->argv[argc]))
3532                                 return;
3534                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3535         }
3538 static bool
3539 help_open(struct view *view, enum open_flags flags)
3541         enum keymap keymap;
3543         reset_view(view);
3544         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3545         add_line_text(view, "", LINE_DEFAULT);
3547         for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
3548                 help_open_keymap(view, keymap);
3550         return TRUE;
3553 static enum request
3554 help_request(struct view *view, enum request request, struct line *line)
3556         switch (request) {
3557         case REQ_ENTER:
3558                 if (line->type == LINE_HELP_KEYMAP) {
3559                         help_keymap_hidden[line->other] =
3560                                 !help_keymap_hidden[line->other];
3561                         refresh_view(view);
3562                 }
3564                 return REQ_NONE;
3565         default:
3566                 return pager_request(view, request, line);
3567         }
3570 static struct view_ops help_ops = {
3571         "line",
3572         help_open,
3573         NULL,
3574         pager_draw,
3575         help_request,
3576         pager_grep,
3577         pager_select,
3578 };
3581 /*
3582  * Tree backend
3583  */
3585 struct tree_stack_entry {
3586         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3587         unsigned long lineno;           /* Line number to restore */
3588         char *name;                     /* Position of name in opt_path */
3589 };
3591 /* The top of the path stack. */
3592 static struct tree_stack_entry *tree_stack = NULL;
3593 unsigned long tree_lineno = 0;
3595 static void
3596 pop_tree_stack_entry(void)
3598         struct tree_stack_entry *entry = tree_stack;
3600         tree_lineno = entry->lineno;
3601         entry->name[0] = 0;
3602         tree_stack = entry->prev;
3603         free(entry);
3606 static void
3607 push_tree_stack_entry(const char *name, unsigned long lineno)
3609         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3610         size_t pathlen = strlen(opt_path);
3612         if (!entry)
3613                 return;
3615         entry->prev = tree_stack;
3616         entry->name = opt_path + pathlen;
3617         tree_stack = entry;
3619         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3620                 pop_tree_stack_entry();
3621                 return;
3622         }
3624         /* Move the current line to the first tree entry. */
3625         tree_lineno = 1;
3626         entry->lineno = lineno;
3629 /* Parse output from git-ls-tree(1):
3630  *
3631  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3632  */
3634 #define SIZEOF_TREE_ATTR \
3635         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3637 #define SIZEOF_TREE_MODE \
3638         STRING_SIZE("100644 ")
3640 #define TREE_ID_OFFSET \
3641         STRING_SIZE("100644 blob ")
3643 struct tree_entry {
3644         char id[SIZEOF_REV];
3645         mode_t mode;
3646         struct time time;               /* Date from the author ident. */
3647         const char *author;             /* Author of the commit. */
3648         char name[1];
3649 };
3651 static const char *
3652 tree_path(const struct line *line)
3654         return ((struct tree_entry *) line->data)->name;
3657 static int
3658 tree_compare_entry(const struct line *line1, const struct line *line2)
3660         if (line1->type != line2->type)
3661                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3662         return strcmp(tree_path(line1), tree_path(line2));
3665 static const enum sort_field tree_sort_fields[] = {
3666         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3667 };
3668 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3670 static int
3671 tree_compare(const void *l1, const void *l2)
3673         const struct line *line1 = (const struct line *) l1;
3674         const struct line *line2 = (const struct line *) l2;
3675         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3676         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3678         if (line1->type == LINE_TREE_HEAD)
3679                 return -1;
3680         if (line2->type == LINE_TREE_HEAD)
3681                 return 1;
3683         switch (get_sort_field(tree_sort_state)) {
3684         case ORDERBY_DATE:
3685                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3687         case ORDERBY_AUTHOR:
3688                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3690         case ORDERBY_NAME:
3691         default:
3692                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3693         }
3697 static struct line *
3698 tree_entry(struct view *view, enum line_type type, const char *path,
3699            const char *mode, const char *id)
3701         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3702         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3704         if (!entry || !line) {
3705                 free(entry);
3706                 return NULL;
3707         }
3709         strncpy(entry->name, path, strlen(path));
3710         if (mode)
3711                 entry->mode = strtoul(mode, NULL, 8);
3712         if (id)
3713                 string_copy_rev(entry->id, id);
3715         return line;
3718 static bool
3719 tree_read_date(struct view *view, char *text, bool *read_date)
3721         static const char *author_name;
3722         static struct time author_time;
3724         if (!text && *read_date) {
3725                 *read_date = FALSE;
3726                 return TRUE;
3728         } else if (!text) {
3729                 /* Find next entry to process */
3730                 const char *log_file[] = {
3731                         "git", "log", "--no-color", "--pretty=raw",
3732                                 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3733                 };
3735                 if (!view->lines) {
3736                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3737                         report("Tree is empty");
3738                         return TRUE;
3739                 }
3741                 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3742                         report("Failed to load tree data");
3743                         return TRUE;
3744                 }
3746                 *read_date = TRUE;
3747                 return FALSE;
3749         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3750                 parse_author_line(text + STRING_SIZE("author "),
3751                                   &author_name, &author_time);
3753         } else if (*text == ':') {
3754                 char *pos;
3755                 size_t annotated = 1;
3756                 size_t i;
3758                 pos = strchr(text, '\t');
3759                 if (!pos)
3760                         return TRUE;
3761                 text = pos + 1;
3762                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3763                         text += strlen(opt_path);
3764                 pos = strchr(text, '/');
3765                 if (pos)
3766                         *pos = 0;
3768                 for (i = 1; i < view->lines; i++) {
3769                         struct line *line = &view->line[i];
3770                         struct tree_entry *entry = line->data;
3772                         annotated += !!entry->author;
3773                         if (entry->author || strcmp(entry->name, text))
3774                                 continue;
3776                         entry->author = author_name;
3777                         entry->time = author_time;
3778                         line->dirty = 1;
3779                         break;
3780                 }
3782                 if (annotated == view->lines)
3783                         io_kill(view->pipe);
3784         }
3785         return TRUE;
3788 static bool
3789 tree_read(struct view *view, char *text)
3791         static bool read_date = FALSE;
3792         struct tree_entry *data;
3793         struct line *entry, *line;
3794         enum line_type type;
3795         size_t textlen = text ? strlen(text) : 0;
3796         char *path = text + SIZEOF_TREE_ATTR;
3798         if (read_date || !text)
3799                 return tree_read_date(view, text, &read_date);
3801         if (textlen <= SIZEOF_TREE_ATTR)
3802                 return FALSE;
3803         if (view->lines == 0 &&
3804             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3805                 return FALSE;
3807         /* Strip the path part ... */
3808         if (*opt_path) {
3809                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3810                 size_t striplen = strlen(opt_path);
3812                 if (pathlen > striplen)
3813                         memmove(path, path + striplen,
3814                                 pathlen - striplen + 1);
3816                 /* Insert "link" to parent directory. */
3817                 if (view->lines == 1 &&
3818                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3819                         return FALSE;
3820         }
3822         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3823         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3824         if (!entry)
3825                 return FALSE;
3826         data = entry->data;
3828         /* Skip "Directory ..." and ".." line. */
3829         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3830                 if (tree_compare_entry(line, entry) <= 0)
3831                         continue;
3833                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3835                 line->data = data;
3836                 line->type = type;
3837                 for (; line <= entry; line++)
3838                         line->dirty = line->cleareol = 1;
3839                 return TRUE;
3840         }
3842         if (tree_lineno > view->lineno) {
3843                 view->lineno = tree_lineno;
3844                 tree_lineno = 0;
3845         }
3847         return TRUE;
3850 static bool
3851 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3853         struct tree_entry *entry = line->data;
3855         if (line->type == LINE_TREE_HEAD) {
3856                 if (draw_text(view, line->type, "Directory path /"))
3857                         return TRUE;
3858         } else {
3859                 if (draw_mode(view, entry->mode))
3860                         return TRUE;
3862                 if (draw_author(view, entry->author))
3863                         return TRUE;
3865                 if (draw_date(view, &entry->time))
3866                         return TRUE;
3867         }
3869         draw_text(view, line->type, entry->name);
3870         return TRUE;
3873 static void
3874 open_blob_editor(const char *id)
3876         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3877         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3878         int fd = mkstemp(file);
3880         if (fd == -1)
3881                 report("Failed to create temporary file");
3882         else if (!io_run_append(blob_argv, fd))
3883                 report("Failed to save blob data to file");
3884         else
3885                 open_editor(file);
3886         if (fd != -1)
3887                 unlink(file);
3890 static enum request
3891 tree_request(struct view *view, enum request request, struct line *line)
3893         enum open_flags flags;
3894         struct tree_entry *entry = line->data;
3896         switch (request) {
3897         case REQ_VIEW_BLAME:
3898                 if (line->type != LINE_TREE_FILE) {
3899                         report("Blame only supported for files");
3900                         return REQ_NONE;
3901                 }
3903                 string_copy(opt_ref, view->vid);
3904                 return request;
3906         case REQ_EDIT:
3907                 if (line->type != LINE_TREE_FILE) {
3908                         report("Edit only supported for files");
3909                 } else if (!is_head_commit(view->vid)) {
3910                         open_blob_editor(entry->id);
3911                 } else {
3912                         open_editor(opt_file);
3913                 }
3914                 return REQ_NONE;
3916         case REQ_TOGGLE_SORT_FIELD:
3917         case REQ_TOGGLE_SORT_ORDER:
3918                 sort_view(view, request, &tree_sort_state, tree_compare);
3919                 return REQ_NONE;
3921         case REQ_PARENT:
3922                 if (!*opt_path) {
3923                         /* quit view if at top of tree */
3924                         return REQ_VIEW_CLOSE;
3925                 }
3926                 /* fake 'cd  ..' */
3927                 line = &view->line[1];
3928                 break;
3930         case REQ_ENTER:
3931                 break;
3933         default:
3934                 return request;
3935         }
3937         /* Cleanup the stack if the tree view is at a different tree. */
3938         while (!*opt_path && tree_stack)
3939                 pop_tree_stack_entry();
3941         switch (line->type) {
3942         case LINE_TREE_DIR:
3943                 /* Depending on whether it is a subdirectory or parent link
3944                  * mangle the path buffer. */
3945                 if (line == &view->line[1] && *opt_path) {
3946                         pop_tree_stack_entry();
3948                 } else {
3949                         const char *basename = tree_path(line);
3951                         push_tree_stack_entry(basename, view->lineno);
3952                 }
3954                 /* Trees and subtrees share the same ID, so they are not not
3955                  * unique like blobs. */
3956                 flags = OPEN_RELOAD;
3957                 request = REQ_VIEW_TREE;
3958                 break;
3960         case LINE_TREE_FILE:
3961                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3962                 request = REQ_VIEW_BLOB;
3963                 break;
3965         default:
3966                 return REQ_NONE;
3967         }
3969         open_view(view, request, flags);
3970         if (request == REQ_VIEW_TREE)
3971                 view->lineno = tree_lineno;
3973         return REQ_NONE;
3976 static bool
3977 tree_grep(struct view *view, struct line *line)
3979         struct tree_entry *entry = line->data;
3980         const char *text[] = {
3981                 entry->name,
3982                 mkauthor(entry->author, opt_author_cols, opt_author),
3983                 mkdate(&entry->time, opt_date),
3984                 NULL
3985         };
3987         return grep_text(view, text);
3990 static void
3991 tree_select(struct view *view, struct line *line)
3993         struct tree_entry *entry = line->data;
3995         if (line->type == LINE_TREE_FILE) {
3996                 string_copy_rev(ref_blob, entry->id);
3997                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3999         } else if (line->type != LINE_TREE_DIR) {
4000                 return;
4001         }
4003         string_copy_rev(view->ref, entry->id);
4006 static bool
4007 tree_open(struct view *view, enum open_flags flags)
4009         static const char *tree_argv[] = {
4010                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4011         };
4013         if (view->lines == 0 && opt_prefix[0]) {
4014                 char *pos = opt_prefix;
4016                 while (pos && *pos) {
4017                         char *end = strchr(pos, '/');
4019                         if (end)
4020                                 *end = 0;
4021                         push_tree_stack_entry(pos, 0);
4022                         pos = end;
4023                         if (end) {
4024                                 *end = '/';
4025                                 pos++;
4026                         }
4027                 }
4029         } else if (strcmp(view->vid, view->id)) {
4030                 opt_path[0] = 0;
4031         }
4033         return begin_update(view, opt_cdup, tree_argv, flags);
4036 static struct view_ops tree_ops = {
4037         "file",
4038         tree_open,
4039         tree_read,
4040         tree_draw,
4041         tree_request,
4042         tree_grep,
4043         tree_select,
4044 };
4046 static bool
4047 blob_open(struct view *view, enum open_flags flags)
4049         static const char *blob_argv[] = {
4050                 "git", "cat-file", "blob", "%(blob)", NULL
4051         };
4053         return begin_update(view, NULL, blob_argv, flags);
4056 static bool
4057 blob_read(struct view *view, char *line)
4059         if (!line)
4060                 return TRUE;
4061         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4064 static enum request
4065 blob_request(struct view *view, enum request request, struct line *line)
4067         switch (request) {
4068         case REQ_EDIT:
4069                 open_blob_editor(view->vid);
4070                 return REQ_NONE;
4071         default:
4072                 return pager_request(view, request, line);
4073         }
4076 static struct view_ops blob_ops = {
4077         "line",
4078         blob_open,
4079         blob_read,
4080         pager_draw,
4081         blob_request,
4082         pager_grep,
4083         pager_select,
4084 };
4086 /*
4087  * Blame backend
4088  *
4089  * Loading the blame view is a two phase job:
4090  *
4091  *  1. File content is read either using opt_file from the
4092  *     filesystem or using git-cat-file.
4093  *  2. Then blame information is incrementally added by
4094  *     reading output from git-blame.
4095  */
4097 struct blame_commit {
4098         char id[SIZEOF_REV];            /* SHA1 ID. */
4099         char title[128];                /* First line of the commit message. */
4100         const char *author;             /* Author of the commit. */
4101         struct time time;               /* Date from the author ident. */
4102         char filename[128];             /* Name of file. */
4103         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4104         char parent_filename[128];      /* Parent/previous name of file. */
4105 };
4107 struct blame {
4108         struct blame_commit *commit;
4109         unsigned long lineno;
4110         char text[1];
4111 };
4113 static bool
4114 blame_open(struct view *view, enum open_flags flags)
4116         const char *file_argv[] = { opt_cdup, opt_file , NULL };
4117         char path[SIZEOF_STR];
4118         size_t i;
4120         if (!view->prev && *opt_prefix) {
4121                 string_copy(path, opt_file);
4122                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4123                         return FALSE;
4124         }
4126         if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4127                 const char *blame_cat_file_argv[] = {
4128                         "git", "cat-file", "blob", "%(ref):%(file)", NULL
4129                 };
4131                 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4132                         return FALSE;
4133         }
4135         /* First pass: remove multiple references to the same commit. */
4136         for (i = 0; i < view->lines; i++) {
4137                 struct blame *blame = view->line[i].data;
4139                 if (blame->commit && blame->commit->id[0])
4140                         blame->commit->id[0] = 0;
4141                 else
4142                         blame->commit = NULL;
4143         }
4145         /* Second pass: free existing references. */
4146         for (i = 0; i < view->lines; i++) {
4147                 struct blame *blame = view->line[i].data;
4149                 if (blame->commit)
4150                         free(blame->commit);
4151         }
4153         string_format(view->vid, "%s", opt_file);
4154         string_format(view->ref, "%s ...", opt_file);
4156         return TRUE;
4159 static struct blame_commit *
4160 get_blame_commit(struct view *view, const char *id)
4162         size_t i;
4164         for (i = 0; i < view->lines; i++) {
4165                 struct blame *blame = view->line[i].data;
4167                 if (!blame->commit)
4168                         continue;
4170                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4171                         return blame->commit;
4172         }
4174         {
4175                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4177                 if (commit)
4178                         string_ncopy(commit->id, id, SIZEOF_REV);
4179                 return commit;
4180         }
4183 static bool
4184 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4186         const char *pos = *posref;
4188         *posref = NULL;
4189         pos = strchr(pos + 1, ' ');
4190         if (!pos || !isdigit(pos[1]))
4191                 return FALSE;
4192         *number = atoi(pos + 1);
4193         if (*number < min || *number > max)
4194                 return FALSE;
4196         *posref = pos;
4197         return TRUE;
4200 static struct blame_commit *
4201 parse_blame_commit(struct view *view, const char *text, int *blamed)
4203         struct blame_commit *commit;
4204         struct blame *blame;
4205         const char *pos = text + SIZEOF_REV - 2;
4206         size_t orig_lineno = 0;
4207         size_t lineno;
4208         size_t group;
4210         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4211                 return NULL;
4213         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4214             !parse_number(&pos, &lineno, 1, view->lines) ||
4215             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4216                 return NULL;
4218         commit = get_blame_commit(view, text);
4219         if (!commit)
4220                 return NULL;
4222         *blamed += group;
4223         while (group--) {
4224                 struct line *line = &view->line[lineno + group - 1];
4226                 blame = line->data;
4227                 blame->commit = commit;
4228                 blame->lineno = orig_lineno + group - 1;
4229                 line->dirty = 1;
4230         }
4232         return commit;
4235 static bool
4236 blame_read_file(struct view *view, const char *line, bool *read_file)
4238         if (!line) {
4239                 const char *blame_argv[] = {
4240                         "git", "blame", "%(blameargs)", "--incremental",
4241                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4242                 };
4244                 if (view->lines == 0 && !view->prev)
4245                         die("No blame exist for %s", view->vid);
4247                 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4248                         report("Failed to load blame data");
4249                         return TRUE;
4250                 }
4252                 *read_file = FALSE;
4253                 return FALSE;
4255         } else {
4256                 size_t linelen = strlen(line);
4257                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4259                 if (!blame)
4260                         return FALSE;
4262                 blame->commit = NULL;
4263                 strncpy(blame->text, line, linelen);
4264                 blame->text[linelen] = 0;
4265                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4266         }
4269 static bool
4270 match_blame_header(const char *name, char **line)
4272         size_t namelen = strlen(name);
4273         bool matched = !strncmp(name, *line, namelen);
4275         if (matched)
4276                 *line += namelen;
4278         return matched;
4281 static bool
4282 blame_read(struct view *view, char *line)
4284         static struct blame_commit *commit = NULL;
4285         static int blamed = 0;
4286         static bool read_file = TRUE;
4288         if (read_file)
4289                 return blame_read_file(view, line, &read_file);
4291         if (!line) {
4292                 /* Reset all! */
4293                 commit = NULL;
4294                 blamed = 0;
4295                 read_file = TRUE;
4296                 string_format(view->ref, "%s", view->vid);
4297                 if (view_is_displayed(view)) {
4298                         update_view_title(view);
4299                         redraw_view_from(view, 0);
4300                 }
4301                 return TRUE;
4302         }
4304         if (!commit) {
4305                 commit = parse_blame_commit(view, line, &blamed);
4306                 string_format(view->ref, "%s %2d%%", view->vid,
4307                               view->lines ? blamed * 100 / view->lines : 0);
4309         } else if (match_blame_header("author ", &line)) {
4310                 commit->author = get_author(line);
4312         } else if (match_blame_header("author-time ", &line)) {
4313                 parse_timesec(&commit->time, line);
4315         } else if (match_blame_header("author-tz ", &line)) {
4316                 parse_timezone(&commit->time, line);
4318         } else if (match_blame_header("summary ", &line)) {
4319                 string_ncopy(commit->title, line, strlen(line));
4321         } else if (match_blame_header("previous ", &line)) {
4322                 if (strlen(line) <= SIZEOF_REV)
4323                         return FALSE;
4324                 string_copy_rev(commit->parent_id, line);
4325                 line += SIZEOF_REV;
4326                 string_ncopy(commit->parent_filename, line, strlen(line));
4328         } else if (match_blame_header("filename ", &line)) {
4329                 string_ncopy(commit->filename, line, strlen(line));
4330                 commit = NULL;
4331         }
4333         return TRUE;
4336 static bool
4337 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4339         struct blame *blame = line->data;
4340         struct time *time = NULL;
4341         const char *id = NULL, *author = NULL;
4343         if (blame->commit && *blame->commit->filename) {
4344                 id = blame->commit->id;
4345                 author = blame->commit->author;
4346                 time = &blame->commit->time;
4347         }
4349         if (draw_date(view, time))
4350                 return TRUE;
4352         if (draw_author(view, author))
4353                 return TRUE;
4355         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4356                 return TRUE;
4358         if (draw_lineno(view, lineno))
4359                 return TRUE;
4361         draw_text(view, LINE_DEFAULT, blame->text);
4362         return TRUE;
4365 static bool
4366 check_blame_commit(struct blame *blame, bool check_null_id)
4368         if (!blame->commit)
4369                 report("Commit data not loaded yet");
4370         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4371                 report("No commit exist for the selected line");
4372         else
4373                 return TRUE;
4374         return FALSE;
4377 static void
4378 setup_blame_parent_line(struct view *view, struct blame *blame)
4380         char from[SIZEOF_REF + SIZEOF_STR];
4381         char to[SIZEOF_REF + SIZEOF_STR];
4382         const char *diff_tree_argv[] = {
4383                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4384                         "-U0", from, to, "--", NULL
4385         };
4386         struct io io;
4387         int parent_lineno = -1;
4388         int blamed_lineno = -1;
4389         char *line;
4391         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4392             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4393             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4394                 return;
4396         while ((line = io_get(&io, '\n', TRUE))) {
4397                 if (*line == '@') {
4398                         char *pos = strchr(line, '+');
4400                         parent_lineno = atoi(line + 4);
4401                         if (pos)
4402                                 blamed_lineno = atoi(pos + 1);
4404                 } else if (*line == '+' && parent_lineno != -1) {
4405                         if (blame->lineno == blamed_lineno - 1 &&
4406                             !strcmp(blame->text, line + 1)) {
4407                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4408                                 break;
4409                         }
4410                         blamed_lineno++;
4411                 }
4412         }
4414         io_done(&io);
4417 static enum request
4418 blame_request(struct view *view, enum request request, struct line *line)
4420         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4421         struct blame *blame = line->data;
4423         switch (request) {
4424         case REQ_VIEW_BLAME:
4425                 if (check_blame_commit(blame, TRUE)) {
4426                         string_copy(opt_ref, blame->commit->id);
4427                         string_copy(opt_file, blame->commit->filename);
4428                         if (blame->lineno)
4429                                 view->lineno = blame->lineno;
4430                         reload_view(view);
4431                 }
4432                 break;
4434         case REQ_PARENT:
4435                 if (!check_blame_commit(blame, TRUE))
4436                         break;
4437                 if (!*blame->commit->parent_id) {
4438                         report("The selected commit has no parents");
4439                 } else {
4440                         string_copy_rev(opt_ref, blame->commit->parent_id);
4441                         string_copy(opt_file, blame->commit->parent_filename);
4442                         setup_blame_parent_line(view, blame);
4443                         reload_view(view);
4444                 }
4445                 break;
4447         case REQ_ENTER:
4448                 if (!check_blame_commit(blame, FALSE))
4449                         break;
4451                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4452                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4453                         break;
4455                 if (!strcmp(blame->commit->id, NULL_ID)) {
4456                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4457                         const char *diff_index_argv[] = {
4458                                 "git", "diff-index", "--root", "--patch-with-stat",
4459                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4460                         };
4462                         if (!*blame->commit->parent_id) {
4463                                 diff_index_argv[1] = "diff";
4464                                 diff_index_argv[2] = "--no-color";
4465                                 diff_index_argv[6] = "--";
4466                                 diff_index_argv[7] = "/dev/null";
4467                         }
4469                         open_argv(view, diff, diff_index_argv, NULL, flags);
4470                 } else {
4471                         open_view(view, REQ_VIEW_DIFF, flags);
4472                 }
4473                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4474                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4475                 break;
4477         default:
4478                 return request;
4479         }
4481         return REQ_NONE;
4484 static bool
4485 blame_grep(struct view *view, struct line *line)
4487         struct blame *blame = line->data;
4488         struct blame_commit *commit = blame->commit;
4489         const char *text[] = {
4490                 blame->text,
4491                 commit ? commit->title : "",
4492                 commit ? commit->id : "",
4493                 commit && opt_author ? commit->author : "",
4494                 commit ? mkdate(&commit->time, opt_date) : "",
4495                 NULL
4496         };
4498         return grep_text(view, text);
4501 static void
4502 blame_select(struct view *view, struct line *line)
4504         struct blame *blame = line->data;
4505         struct blame_commit *commit = blame->commit;
4507         if (!commit)
4508                 return;
4510         if (!strcmp(commit->id, NULL_ID))
4511                 string_ncopy(ref_commit, "HEAD", 4);
4512         else
4513                 string_copy_rev(ref_commit, commit->id);
4516 static struct view_ops blame_ops = {
4517         "line",
4518         blame_open,
4519         blame_read,
4520         blame_draw,
4521         blame_request,
4522         blame_grep,
4523         blame_select,
4524 };
4526 /*
4527  * Branch backend
4528  */
4530 struct branch {
4531         const char *author;             /* Author of the last commit. */
4532         struct time time;               /* Date of the last activity. */
4533         const struct ref *ref;          /* Name and commit ID information. */
4534 };
4536 static const struct ref branch_all;
4538 static const enum sort_field branch_sort_fields[] = {
4539         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4540 };
4541 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4543 static int
4544 branch_compare(const void *l1, const void *l2)
4546         const struct branch *branch1 = ((const struct line *) l1)->data;
4547         const struct branch *branch2 = ((const struct line *) l2)->data;
4549         switch (get_sort_field(branch_sort_state)) {
4550         case ORDERBY_DATE:
4551                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4553         case ORDERBY_AUTHOR:
4554                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4556         case ORDERBY_NAME:
4557         default:
4558                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4559         }
4562 static bool
4563 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4565         struct branch *branch = line->data;
4566         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4568         if (draw_date(view, &branch->time))
4569                 return TRUE;
4571         if (draw_author(view, branch->author))
4572                 return TRUE;
4574         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4575         return TRUE;
4578 static enum request
4579 branch_request(struct view *view, enum request request, struct line *line)
4581         struct branch *branch = line->data;
4583         switch (request) {
4584         case REQ_REFRESH:
4585                 load_refs();
4586                 refresh_view(view);
4587                 return REQ_NONE;
4589         case REQ_TOGGLE_SORT_FIELD:
4590         case REQ_TOGGLE_SORT_ORDER:
4591                 sort_view(view, request, &branch_sort_state, branch_compare);
4592                 return REQ_NONE;
4594         case REQ_ENTER:
4595         {
4596                 const struct ref *ref = branch->ref;
4597                 const char *all_branches_argv[] = {
4598                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4599                               "--topo-order",
4600                               ref == &branch_all ? "--all" : ref->name, NULL
4601                 };
4602                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4604                 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4605                 return REQ_NONE;
4606         }
4607         default:
4608                 return request;
4609         }
4612 static bool
4613 branch_read(struct view *view, char *line)
4615         static char id[SIZEOF_REV];
4616         struct branch *reference;
4617         size_t i;
4619         if (!line)
4620                 return TRUE;
4622         switch (get_line_type(line)) {
4623         case LINE_COMMIT:
4624                 string_copy_rev(id, line + STRING_SIZE("commit "));
4625                 return TRUE;
4627         case LINE_AUTHOR:
4628                 for (i = 0, reference = NULL; i < view->lines; i++) {
4629                         struct branch *branch = view->line[i].data;
4631                         if (strcmp(branch->ref->id, id))
4632                                 continue;
4634                         view->line[i].dirty = TRUE;
4635                         if (reference) {
4636                                 branch->author = reference->author;
4637                                 branch->time = reference->time;
4638                                 continue;
4639                         }
4641                         parse_author_line(line + STRING_SIZE("author "),
4642                                           &branch->author, &branch->time);
4643                         reference = branch;
4644                 }
4645                 return TRUE;
4647         default:
4648                 return TRUE;
4649         }
4653 static bool
4654 branch_open_visitor(void *data, const struct ref *ref)
4656         struct view *view = data;
4657         struct branch *branch;
4659         if (ref->tag || ref->ltag || ref->remote)
4660                 return TRUE;
4662         branch = calloc(1, sizeof(*branch));
4663         if (!branch)
4664                 return FALSE;
4666         branch->ref = ref;
4667         return !!add_line_data(view, branch, LINE_DEFAULT);
4670 static bool
4671 branch_open(struct view *view, enum open_flags flags)
4673         const char *branch_log[] = {
4674                 "git", "log", "--no-color", "--pretty=raw",
4675                         "--simplify-by-decoration", "--all", NULL
4676         };
4678         if (!begin_update(view, NULL, branch_log, flags)) {
4679                 report("Failed to load branch data");
4680                 return TRUE;
4681         }
4683         branch_open_visitor(view, &branch_all);
4684         foreach_ref(branch_open_visitor, view);
4685         view->p_restore = TRUE;
4687         return TRUE;
4690 static bool
4691 branch_grep(struct view *view, struct line *line)
4693         struct branch *branch = line->data;
4694         const char *text[] = {
4695                 branch->ref->name,
4696                 mkauthor(branch->author, opt_author_cols, opt_author),
4697                 NULL
4698         };
4700         return grep_text(view, text);
4703 static void
4704 branch_select(struct view *view, struct line *line)
4706         struct branch *branch = line->data;
4708         string_copy_rev(view->ref, branch->ref->id);
4709         string_copy_rev(ref_commit, branch->ref->id);
4710         string_copy_rev(ref_head, branch->ref->id);
4711         string_copy_rev(ref_branch, branch->ref->name);
4714 static struct view_ops branch_ops = {
4715         "branch",
4716         branch_open,
4717         branch_read,
4718         branch_draw,
4719         branch_request,
4720         branch_grep,
4721         branch_select,
4722 };
4724 /*
4725  * Status backend
4726  */
4728 struct status {
4729         char status;
4730         struct {
4731                 mode_t mode;
4732                 char rev[SIZEOF_REV];
4733                 char name[SIZEOF_STR];
4734         } old;
4735         struct {
4736                 mode_t mode;
4737                 char rev[SIZEOF_REV];
4738                 char name[SIZEOF_STR];
4739         } new;
4740 };
4742 static char status_onbranch[SIZEOF_STR];
4743 static struct status stage_status;
4744 static enum line_type stage_line_type;
4745 static size_t stage_chunks;
4746 static int *stage_chunk;
4748 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4750 /* This should work even for the "On branch" line. */
4751 static inline bool
4752 status_has_none(struct view *view, struct line *line)
4754         return line < view->line + view->lines && !line[1].data;
4757 /* Get fields from the diff line:
4758  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4759  */
4760 static inline bool
4761 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4763         const char *old_mode = buf +  1;
4764         const char *new_mode = buf +  8;
4765         const char *old_rev  = buf + 15;
4766         const char *new_rev  = buf + 56;
4767         const char *status   = buf + 97;
4769         if (bufsize < 98 ||
4770             old_mode[-1] != ':' ||
4771             new_mode[-1] != ' ' ||
4772             old_rev[-1]  != ' ' ||
4773             new_rev[-1]  != ' ' ||
4774             status[-1]   != ' ')
4775                 return FALSE;
4777         file->status = *status;
4779         string_copy_rev(file->old.rev, old_rev);
4780         string_copy_rev(file->new.rev, new_rev);
4782         file->old.mode = strtoul(old_mode, NULL, 8);
4783         file->new.mode = strtoul(new_mode, NULL, 8);
4785         file->old.name[0] = file->new.name[0] = 0;
4787         return TRUE;
4790 static bool
4791 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4793         struct status *unmerged = NULL;
4794         char *buf;
4795         struct io io;
4797         if (!io_run(&io, IO_RD, opt_cdup, argv))
4798                 return FALSE;
4800         add_line_data(view, NULL, type);
4802         while ((buf = io_get(&io, 0, TRUE))) {
4803                 struct status *file = unmerged;
4805                 if (!file) {
4806                         file = calloc(1, sizeof(*file));
4807                         if (!file || !add_line_data(view, file, type))
4808                                 goto error_out;
4809                 }
4811                 /* Parse diff info part. */
4812                 if (status) {
4813                         file->status = status;
4814                         if (status == 'A')
4815                                 string_copy(file->old.rev, NULL_ID);
4817                 } else if (!file->status || file == unmerged) {
4818                         if (!status_get_diff(file, buf, strlen(buf)))
4819                                 goto error_out;
4821                         buf = io_get(&io, 0, TRUE);
4822                         if (!buf)
4823                                 break;
4825                         /* Collapse all modified entries that follow an
4826                          * associated unmerged entry. */
4827                         if (unmerged == file) {
4828                                 unmerged->status = 'U';
4829                                 unmerged = NULL;
4830                         } else if (file->status == 'U') {
4831                                 unmerged = file;
4832                         }
4833                 }
4835                 /* Grab the old name for rename/copy. */
4836                 if (!*file->old.name &&
4837                     (file->status == 'R' || file->status == 'C')) {
4838                         string_ncopy(file->old.name, buf, strlen(buf));
4840                         buf = io_get(&io, 0, TRUE);
4841                         if (!buf)
4842                                 break;
4843                 }
4845                 /* git-ls-files just delivers a NUL separated list of
4846                  * file names similar to the second half of the
4847                  * git-diff-* output. */
4848                 string_ncopy(file->new.name, buf, strlen(buf));
4849                 if (!*file->old.name)
4850                         string_copy(file->old.name, file->new.name);
4851                 file = NULL;
4852         }
4854         if (io_error(&io)) {
4855 error_out:
4856                 io_done(&io);
4857                 return FALSE;
4858         }
4860         if (!view->line[view->lines - 1].data)
4861                 add_line_data(view, NULL, LINE_STAT_NONE);
4863         io_done(&io);
4864         return TRUE;
4867 /* Don't show unmerged entries in the staged section. */
4868 static const char *status_diff_index_argv[] = {
4869         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4870                              "--cached", "-M", "HEAD", NULL
4871 };
4873 static const char *status_diff_files_argv[] = {
4874         "git", "diff-files", "-z", NULL
4875 };
4877 static const char *status_list_other_argv[] = {
4878         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4879 };
4881 static const char *status_list_no_head_argv[] = {
4882         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4883 };
4885 static const char *update_index_argv[] = {
4886         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4887 };
4889 /* Restore the previous line number to stay in the context or select a
4890  * line with something that can be updated. */
4891 static void
4892 status_restore(struct view *view)
4894         if (view->p_lineno >= view->lines)
4895                 view->p_lineno = view->lines - 1;
4896         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4897                 view->p_lineno++;
4898         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4899                 view->p_lineno--;
4901         /* If the above fails, always skip the "On branch" line. */
4902         if (view->p_lineno < view->lines)
4903                 view->lineno = view->p_lineno;
4904         else
4905                 view->lineno = 1;
4907         if (view->lineno < view->offset)
4908                 view->offset = view->lineno;
4909         else if (view->offset + view->height <= view->lineno)
4910                 view->offset = view->lineno - view->height + 1;
4912         view->p_restore = FALSE;
4915 static void
4916 status_update_onbranch(void)
4918         static const char *paths[][2] = {
4919                 { "rebase-apply/rebasing",      "Rebasing" },
4920                 { "rebase-apply/applying",      "Applying mailbox" },
4921                 { "rebase-apply/",              "Rebasing mailbox" },
4922                 { "rebase-merge/interactive",   "Interactive rebase" },
4923                 { "rebase-merge/",              "Rebase merge" },
4924                 { "MERGE_HEAD",                 "Merging" },
4925                 { "BISECT_LOG",                 "Bisecting" },
4926                 { "HEAD",                       "On branch" },
4927         };
4928         char buf[SIZEOF_STR];
4929         struct stat stat;
4930         int i;
4932         if (is_initial_commit()) {
4933                 string_copy(status_onbranch, "Initial commit");
4934                 return;
4935         }
4937         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4938                 char *head = opt_head;
4940                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4941                     lstat(buf, &stat) < 0)
4942                         continue;
4944                 if (!*opt_head) {
4945                         struct io io;
4947                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4948                             io_read_buf(&io, buf, sizeof(buf))) {
4949                                 head = buf;
4950                                 if (!prefixcmp(head, "refs/heads/"))
4951                                         head += STRING_SIZE("refs/heads/");
4952                         }
4953                 }
4955                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4956                         string_copy(status_onbranch, opt_head);
4957                 return;
4958         }
4960         string_copy(status_onbranch, "Not currently on any branch");
4963 /* First parse staged info using git-diff-index(1), then parse unstaged
4964  * info using git-diff-files(1), and finally untracked files using
4965  * git-ls-files(1). */
4966 static bool
4967 status_open(struct view *view, enum open_flags flags)
4969         reset_view(view);
4971         add_line_data(view, NULL, LINE_STAT_HEAD);
4972         status_update_onbranch();
4974         io_run_bg(update_index_argv);
4976         if (is_initial_commit()) {
4977                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4978                         return FALSE;
4979         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4980                 return FALSE;
4981         }
4983         if (!opt_untracked_dirs_content)
4984                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4986         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4987             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4988                 return FALSE;
4990         /* Restore the exact position or use the specialized restore
4991          * mode? */
4992         if (!view->p_restore)
4993                 status_restore(view);
4994         return TRUE;
4997 static bool
4998 status_draw(struct view *view, struct line *line, unsigned int lineno)
5000         struct status *status = line->data;
5001         enum line_type type;
5002         const char *text;
5004         if (!status) {
5005                 switch (line->type) {
5006                 case LINE_STAT_STAGED:
5007                         type = LINE_STAT_SECTION;
5008                         text = "Changes to be committed:";
5009                         break;
5011                 case LINE_STAT_UNSTAGED:
5012                         type = LINE_STAT_SECTION;
5013                         text = "Changed but not updated:";
5014                         break;
5016                 case LINE_STAT_UNTRACKED:
5017                         type = LINE_STAT_SECTION;
5018                         text = "Untracked files:";
5019                         break;
5021                 case LINE_STAT_NONE:
5022                         type = LINE_DEFAULT;
5023                         text = "  (no files)";
5024                         break;
5026                 case LINE_STAT_HEAD:
5027                         type = LINE_STAT_HEAD;
5028                         text = status_onbranch;
5029                         break;
5031                 default:
5032                         return FALSE;
5033                 }
5034         } else {
5035                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5037                 buf[0] = status->status;
5038                 if (draw_text(view, line->type, buf))
5039                         return TRUE;
5040                 type = LINE_DEFAULT;
5041                 text = status->new.name;
5042         }
5044         draw_text(view, type, text);
5045         return TRUE;
5048 static enum request
5049 status_enter(struct view *view, struct line *line)
5051         struct status *status = line->data;
5052         const char *oldpath = status ? status->old.name : NULL;
5053         /* Diffs for unmerged entries are empty when passing the new
5054          * path, so leave it empty. */
5055         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5056         const char *info;
5057         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5058         struct view *stage = VIEW(REQ_VIEW_STAGE);
5060         if (line->type == LINE_STAT_NONE ||
5061             (!status && line[1].type == LINE_STAT_NONE)) {
5062                 report("No file to diff");
5063                 return REQ_NONE;
5064         }
5066         switch (line->type) {
5067         case LINE_STAT_STAGED:
5068                 if (is_initial_commit()) {
5069                         const char *no_head_diff_argv[] = {
5070                                 "git", "diff", "--no-color", "--patch-with-stat",
5071                                         "--", "/dev/null", newpath, NULL
5072                         };
5074                         open_argv(view, stage, no_head_diff_argv, opt_cdup, flags); 
5075                 } else {
5076                         const char *index_show_argv[] = {
5077                                 "git", "diff-index", "--root", "--patch-with-stat",
5078                                         "-C", "-M", "--cached", "HEAD", "--",
5079                                         oldpath, newpath, NULL
5080                         };
5082                         open_argv(view, stage, index_show_argv, opt_cdup, flags);
5083                 }
5085                 if (status)
5086                         info = "Staged changes to %s";
5087                 else
5088                         info = "Staged changes";
5089                 break;
5091         case LINE_STAT_UNSTAGED:
5092         {
5093                 const char *files_show_argv[] = {
5094                         "git", "diff-files", "--root", "--patch-with-stat",
5095                                 "-C", "-M", "--", oldpath, newpath, NULL
5096                 };
5098                 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5099                 if (status)
5100                         info = "Unstaged changes to %s";
5101                 else
5102                         info = "Unstaged changes";
5103                 break;
5104         }
5105         case LINE_STAT_UNTRACKED:
5106                 if (!newpath) {
5107                         report("No file to show");
5108                         return REQ_NONE;
5109                 }
5111                 if (!suffixcmp(status->new.name, -1, "/")) {
5112                         report("Cannot display a directory");
5113                         return REQ_NONE;
5114                 }
5116                 open_file(view, stage, newpath, flags);
5117                 info = "Untracked file %s";
5118                 break;
5120         case LINE_STAT_HEAD:
5121                 return REQ_NONE;
5123         default:
5124                 die("line type %d not handled in switch", line->type);
5125         }
5127         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5128                 if (status) {
5129                         stage_status = *status;
5130                 } else {
5131                         memset(&stage_status, 0, sizeof(stage_status));
5132                 }
5134                 stage_line_type = line->type;
5135                 stage_chunks = 0;
5136                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5137         }
5139         return REQ_NONE;
5142 static bool
5143 status_exists(struct status *status, enum line_type type)
5145         struct view *view = VIEW(REQ_VIEW_STATUS);
5146         unsigned long lineno;
5148         for (lineno = 0; lineno < view->lines; lineno++) {
5149                 struct line *line = &view->line[lineno];
5150                 struct status *pos = line->data;
5152                 if (line->type != type)
5153                         continue;
5154                 if (!pos && (!status || !status->status) && line[1].data) {
5155                         select_view_line(view, lineno);
5156                         return TRUE;
5157                 }
5158                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5159                         select_view_line(view, lineno);
5160                         return TRUE;
5161                 }
5162         }
5164         return FALSE;
5168 static bool
5169 status_update_prepare(struct io *io, enum line_type type)
5171         const char *staged_argv[] = {
5172                 "git", "update-index", "-z", "--index-info", NULL
5173         };
5174         const char *others_argv[] = {
5175                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5176         };
5178         switch (type) {
5179         case LINE_STAT_STAGED:
5180                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5182         case LINE_STAT_UNSTAGED:
5183         case LINE_STAT_UNTRACKED:
5184                 return io_run(io, IO_WR, opt_cdup, others_argv);
5186         default:
5187                 die("line type %d not handled in switch", type);
5188                 return FALSE;
5189         }
5192 static bool
5193 status_update_write(struct io *io, struct status *status, enum line_type type)
5195         char buf[SIZEOF_STR];
5196         size_t bufsize = 0;
5198         switch (type) {
5199         case LINE_STAT_STAGED:
5200                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5201                                         status->old.mode,
5202                                         status->old.rev,
5203                                         status->old.name, 0))
5204                         return FALSE;
5205                 break;
5207         case LINE_STAT_UNSTAGED:
5208         case LINE_STAT_UNTRACKED:
5209                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5210                         return FALSE;
5211                 break;
5213         default:
5214                 die("line type %d not handled in switch", type);
5215         }
5217         return io_write(io, buf, bufsize);
5220 static bool
5221 status_update_file(struct status *status, enum line_type type)
5223         struct io io;
5224         bool result;
5226         if (!status_update_prepare(&io, type))
5227                 return FALSE;
5229         result = status_update_write(&io, status, type);
5230         return io_done(&io) && result;
5233 static bool
5234 status_update_files(struct view *view, struct line *line)
5236         char buf[sizeof(view->ref)];
5237         struct io io;
5238         bool result = TRUE;
5239         struct line *pos = view->line + view->lines;
5240         int files = 0;
5241         int file, done;
5242         int cursor_y = -1, cursor_x = -1;
5244         if (!status_update_prepare(&io, line->type))
5245                 return FALSE;
5247         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5248                 files++;
5250         string_copy(buf, view->ref);
5251         getsyx(cursor_y, cursor_x);
5252         for (file = 0, done = 5; result && file < files; line++, file++) {
5253                 int almost_done = file * 100 / files;
5255                 if (almost_done > done) {
5256                         done = almost_done;
5257                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5258                                       file, files, done);
5259                         update_view_title(view);
5260                         setsyx(cursor_y, cursor_x);
5261                         doupdate();
5262                 }
5263                 result = status_update_write(&io, line->data, line->type);
5264         }
5265         string_copy(view->ref, buf);
5267         return io_done(&io) && result;
5270 static bool
5271 status_update(struct view *view)
5273         struct line *line = &view->line[view->lineno];
5275         assert(view->lines);
5277         if (!line->data) {
5278                 /* This should work even for the "On branch" line. */
5279                 if (line < view->line + view->lines && !line[1].data) {
5280                         report("Nothing to update");
5281                         return FALSE;
5282                 }
5284                 if (!status_update_files(view, line + 1)) {
5285                         report("Failed to update file status");
5286                         return FALSE;
5287                 }
5289         } else if (!status_update_file(line->data, line->type)) {
5290                 report("Failed to update file status");
5291                 return FALSE;
5292         }
5294         return TRUE;
5297 static bool
5298 status_revert(struct status *status, enum line_type type, bool has_none)
5300         if (!status || type != LINE_STAT_UNSTAGED) {
5301                 if (type == LINE_STAT_STAGED) {
5302                         report("Cannot revert changes to staged files");
5303                 } else if (type == LINE_STAT_UNTRACKED) {
5304                         report("Cannot revert changes to untracked files");
5305                 } else if (has_none) {
5306                         report("Nothing to revert");
5307                 } else {
5308                         report("Cannot revert changes to multiple files");
5309                 }
5311         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5312                 char mode[10] = "100644";
5313                 const char *reset_argv[] = {
5314                         "git", "update-index", "--cacheinfo", mode,
5315                                 status->old.rev, status->old.name, NULL
5316                 };
5317                 const char *checkout_argv[] = {
5318                         "git", "checkout", "--", status->old.name, NULL
5319                 };
5321                 if (status->status == 'U') {
5322                         string_format(mode, "%5o", status->old.mode);
5324                         if (status->old.mode == 0 && status->new.mode == 0) {
5325                                 reset_argv[2] = "--force-remove";
5326                                 reset_argv[3] = status->old.name;
5327                                 reset_argv[4] = NULL;
5328                         }
5330                         if (!io_run_fg(reset_argv, opt_cdup))
5331                                 return FALSE;
5332                         if (status->old.mode == 0 && status->new.mode == 0)
5333                                 return TRUE;
5334                 }
5336                 return io_run_fg(checkout_argv, opt_cdup);
5337         }
5339         return FALSE;
5342 static enum request
5343 status_request(struct view *view, enum request request, struct line *line)
5345         struct status *status = line->data;
5347         switch (request) {
5348         case REQ_STATUS_UPDATE:
5349                 if (!status_update(view))
5350                         return REQ_NONE;
5351                 break;
5353         case REQ_STATUS_REVERT:
5354                 if (!status_revert(status, line->type, status_has_none(view, line)))
5355                         return REQ_NONE;
5356                 break;
5358         case REQ_STATUS_MERGE:
5359                 if (!status || status->status != 'U') {
5360                         report("Merging only possible for files with unmerged status ('U').");
5361                         return REQ_NONE;
5362                 }
5363                 open_mergetool(status->new.name);
5364                 break;
5366         case REQ_EDIT:
5367                 if (!status)
5368                         return request;
5369                 if (status->status == 'D') {
5370                         report("File has been deleted.");
5371                         return REQ_NONE;
5372                 }
5374                 open_editor(status->new.name);
5375                 break;
5377         case REQ_VIEW_BLAME:
5378                 if (status)
5379                         opt_ref[0] = 0;
5380                 return request;
5382         case REQ_ENTER:
5383                 /* After returning the status view has been split to
5384                  * show the stage view. No further reloading is
5385                  * necessary. */
5386                 return status_enter(view, line);
5388         case REQ_REFRESH:
5389                 /* Simply reload the view. */
5390                 break;
5392         default:
5393                 return request;
5394         }
5396         refresh_view(view);
5398         return REQ_NONE;
5401 static void
5402 status_select(struct view *view, struct line *line)
5404         struct status *status = line->data;
5405         char file[SIZEOF_STR] = "all files";
5406         const char *text;
5407         const char *key;
5409         if (status && !string_format(file, "'%s'", status->new.name))
5410                 return;
5412         if (!status && line[1].type == LINE_STAT_NONE)
5413                 line++;
5415         switch (line->type) {
5416         case LINE_STAT_STAGED:
5417                 text = "Press %s to unstage %s for commit";
5418                 break;
5420         case LINE_STAT_UNSTAGED:
5421                 text = "Press %s to stage %s for commit";
5422                 break;
5424         case LINE_STAT_UNTRACKED:
5425                 text = "Press %s to stage %s for addition";
5426                 break;
5428         case LINE_STAT_HEAD:
5429         case LINE_STAT_NONE:
5430                 text = "Nothing to update";
5431                 break;
5433         default:
5434                 die("line type %d not handled in switch", line->type);
5435         }
5437         if (status && status->status == 'U') {
5438                 text = "Press %s to resolve conflict in %s";
5439                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5441         } else {
5442                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5443         }
5445         string_format(view->ref, text, key, file);
5446         if (status)
5447                 string_copy(opt_file, status->new.name);
5450 static bool
5451 status_grep(struct view *view, struct line *line)
5453         struct status *status = line->data;
5455         if (status) {
5456                 const char buf[2] = { status->status, 0 };
5457                 const char *text[] = { status->new.name, buf, NULL };
5459                 return grep_text(view, text);
5460         }
5462         return FALSE;
5465 static struct view_ops status_ops = {
5466         "file",
5467         status_open,
5468         NULL,
5469         status_draw,
5470         status_request,
5471         status_grep,
5472         status_select,
5473 };
5476 static bool
5477 stage_diff_write(struct io *io, struct line *line, struct line *end)
5479         while (line < end) {
5480                 if (!io_write(io, line->data, strlen(line->data)) ||
5481                     !io_write(io, "\n", 1))
5482                         return FALSE;
5483                 line++;
5484                 if (line->type == LINE_DIFF_CHUNK ||
5485                     line->type == LINE_DIFF_HEADER)
5486                         break;
5487         }
5489         return TRUE;
5492 static struct line *
5493 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5495         for (; view->line < line; line--)
5496                 if (line->type == type)
5497                         return line;
5499         return NULL;
5502 static bool
5503 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5505         const char *apply_argv[SIZEOF_ARG] = {
5506                 "git", "apply", "--whitespace=nowarn", NULL
5507         };
5508         struct line *diff_hdr;
5509         struct io io;
5510         int argc = 3;
5512         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5513         if (!diff_hdr)
5514                 return FALSE;
5516         if (!revert)
5517                 apply_argv[argc++] = "--cached";
5518         if (revert || stage_line_type == LINE_STAT_STAGED)
5519                 apply_argv[argc++] = "-R";
5520         apply_argv[argc++] = "-";
5521         apply_argv[argc++] = NULL;
5522         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5523                 return FALSE;
5525         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5526             !stage_diff_write(&io, chunk, view->line + view->lines))
5527                 chunk = NULL;
5529         io_done(&io);
5530         io_run_bg(update_index_argv);
5532         return chunk ? TRUE : FALSE;
5535 static bool
5536 stage_update(struct view *view, struct line *line)
5538         struct line *chunk = NULL;
5540         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5541                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5543         if (chunk) {
5544                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5545                         report("Failed to apply chunk");
5546                         return FALSE;
5547                 }
5549         } else if (!stage_status.status) {
5550                 view = VIEW(REQ_VIEW_STATUS);
5552                 for (line = view->line; line < view->line + view->lines; line++)
5553                         if (line->type == stage_line_type)
5554                                 break;
5556                 if (!status_update_files(view, line + 1)) {
5557                         report("Failed to update files");
5558                         return FALSE;
5559                 }
5561         } else if (!status_update_file(&stage_status, stage_line_type)) {
5562                 report("Failed to update file");
5563                 return FALSE;
5564         }
5566         return TRUE;
5569 static bool
5570 stage_revert(struct view *view, struct line *line)
5572         struct line *chunk = NULL;
5574         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5575                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5577         if (chunk) {
5578                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5579                         return FALSE;
5581                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5582                         report("Failed to revert chunk");
5583                         return FALSE;
5584                 }
5585                 return TRUE;
5587         } else {
5588                 return status_revert(stage_status.status ? &stage_status : NULL,
5589                                      stage_line_type, FALSE);
5590         }
5594 static void
5595 stage_next(struct view *view, struct line *line)
5597         int i;
5599         if (!stage_chunks) {
5600                 for (line = view->line; line < view->line + view->lines; line++) {
5601                         if (line->type != LINE_DIFF_CHUNK)
5602                                 continue;
5604                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5605                                 report("Allocation failure");
5606                                 return;
5607                         }
5609                         stage_chunk[stage_chunks++] = line - view->line;
5610                 }
5611         }
5613         for (i = 0; i < stage_chunks; i++) {
5614                 if (stage_chunk[i] > view->lineno) {
5615                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5616                         report("Chunk %d of %d", i + 1, stage_chunks);
5617                         return;
5618                 }
5619         }
5621         report("No next chunk found");
5624 static enum request
5625 stage_request(struct view *view, enum request request, struct line *line)
5627         switch (request) {
5628         case REQ_STATUS_UPDATE:
5629                 if (!stage_update(view, line))
5630                         return REQ_NONE;
5631                 break;
5633         case REQ_STATUS_REVERT:
5634                 if (!stage_revert(view, line))
5635                         return REQ_NONE;
5636                 break;
5638         case REQ_STAGE_NEXT:
5639                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5640                         report("File is untracked; press %s to add",
5641                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5642                         return REQ_NONE;
5643                 }
5644                 stage_next(view, line);
5645                 return REQ_NONE;
5647         case REQ_EDIT:
5648                 if (!stage_status.new.name[0])
5649                         return request;
5650                 if (stage_status.status == 'D') {
5651                         report("File has been deleted.");
5652                         return REQ_NONE;
5653                 }
5655                 open_editor(stage_status.new.name);
5656                 break;
5658         case REQ_REFRESH:
5659                 /* Reload everything ... */
5660                 break;
5662         case REQ_VIEW_BLAME:
5663                 if (stage_status.new.name[0]) {
5664                         string_copy(opt_file, stage_status.new.name);
5665                         opt_ref[0] = 0;
5666                 }
5667                 return request;
5669         case REQ_ENTER:
5670                 return pager_request(view, request, line);
5672         default:
5673                 return request;
5674         }
5676         refresh_view(view->parent);
5678         /* Check whether the staged entry still exists, and close the
5679          * stage view if it doesn't. */
5680         if (!status_exists(&stage_status, stage_line_type)) {
5681                 status_restore(VIEW(REQ_VIEW_STATUS));
5682                 return REQ_VIEW_CLOSE;
5683         }
5685         refresh_view(view);
5687         return REQ_NONE;
5690 static struct view_ops stage_ops = {
5691         "line",
5692         view_open,
5693         pager_read,
5694         pager_draw,
5695         stage_request,
5696         pager_grep,
5697         pager_select,
5698 };
5701 /*
5702  * Revision graph
5703  */
5705 static const enum line_type graph_colors[] = {
5706         LINE_GRAPH_LINE_0,
5707         LINE_GRAPH_LINE_1,
5708         LINE_GRAPH_LINE_2,
5709         LINE_GRAPH_LINE_3,
5710         LINE_GRAPH_LINE_4,
5711         LINE_GRAPH_LINE_5,
5712         LINE_GRAPH_LINE_6,
5713 };
5715 static enum line_type get_graph_color(struct graph_symbol *symbol)
5717         if (symbol->commit)
5718                 return LINE_GRAPH_COMMIT;
5719         assert(symbol->color < ARRAY_SIZE(graph_colors));
5720         return graph_colors[symbol->color];
5723 static bool
5724 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5726         const char *chars = graph_symbol_to_utf8(symbol);
5728         return draw_text(view, color, chars + !!first); 
5731 static bool
5732 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5734         const char *chars = graph_symbol_to_ascii(symbol);
5736         return draw_text(view, color, chars + !!first); 
5739 static bool
5740 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5742         const chtype *chars = graph_symbol_to_chtype(symbol);
5744         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5747 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5749 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5751         static const draw_graph_fn fns[] = {
5752                 draw_graph_ascii,
5753                 draw_graph_chtype,
5754                 draw_graph_utf8
5755         };
5756         draw_graph_fn fn = fns[opt_line_graphics];
5757         int i;
5759         for (i = 0; i < canvas->size; i++) {
5760                 struct graph_symbol *symbol = &canvas->symbols[i];
5761                 enum line_type color = get_graph_color(symbol);
5763                 if (fn(view, symbol, color, i == 0))
5764                         return TRUE;
5765         }
5767         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5770 /*
5771  * Main view backend
5772  */
5774 struct commit {
5775         char id[SIZEOF_REV];            /* SHA1 ID. */
5776         char title[128];                /* First line of the commit message. */
5777         const char *author;             /* Author of the commit. */
5778         struct time time;               /* Date from the author ident. */
5779         struct ref_list *refs;          /* Repository references. */
5780         struct graph_canvas graph;      /* Ancestry chain graphics. */
5781 };
5783 static bool
5784 main_open(struct view *view, enum open_flags flags)
5786         static const char *main_argv[] = {
5787                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5788                         "--topo-order", "%(diffargs)", "%(revargs)",
5789                         "--", "%(fileargs)", NULL
5790         };
5792         return begin_update(view, NULL, main_argv, flags);
5795 static bool
5796 main_draw(struct view *view, struct line *line, unsigned int lineno)
5798         struct commit *commit = line->data;
5800         if (!commit->author)
5801                 return FALSE;
5803         if (draw_date(view, &commit->time))
5804                 return TRUE;
5806         if (draw_author(view, commit->author))
5807                 return TRUE;
5809         if (opt_rev_graph && draw_graph(view, &commit->graph))
5810                 return TRUE;
5812         if (draw_refs(view, commit->refs))
5813                 return TRUE;
5815         draw_text(view, LINE_DEFAULT, commit->title);
5816         return TRUE;
5819 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5820 static bool
5821 main_read(struct view *view, char *line)
5823         static struct graph graph;
5824         enum line_type type;
5825         struct commit *commit;
5827         if (!line) {
5828                 if (!view->lines && !view->prev)
5829                         die("No revisions match the given arguments.");
5830                 if (view->lines > 0) {
5831                         commit = view->line[view->lines - 1].data;
5832                         view->line[view->lines - 1].dirty = 1;
5833                         if (!commit->author) {
5834                                 view->lines--;
5835                                 free(commit);
5836                         }
5837                 }
5839                 done_graph(&graph);
5840                 return TRUE;
5841         }
5843         type = get_line_type(line);
5844         if (type == LINE_COMMIT) {
5845                 bool is_boundary;
5847                 commit = calloc(1, sizeof(struct commit));
5848                 if (!commit)
5849                         return FALSE;
5851                 line += STRING_SIZE("commit ");
5852                 is_boundary = *line == '-';
5853                 if (is_boundary)
5854                         line++;
5856                 string_copy_rev(commit->id, line);
5857                 commit->refs = get_ref_list(commit->id);
5858                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5859                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5860                 return TRUE;
5861         }
5863         if (!view->lines)
5864                 return TRUE;
5865         commit = view->line[view->lines - 1].data;
5867         switch (type) {
5868         case LINE_PARENT:
5869                 if (!graph.has_parents)
5870                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5871                 break;
5873         case LINE_AUTHOR:
5874                 parse_author_line(line + STRING_SIZE("author "),
5875                                   &commit->author, &commit->time);
5876                 graph_render_parents(&graph);
5877                 break;
5879         default:
5880                 /* Fill in the commit title if it has not already been set. */
5881                 if (commit->title[0])
5882                         break;
5884                 /* Require titles to start with a non-space character at the
5885                  * offset used by git log. */
5886                 if (strncmp(line, "    ", 4))
5887                         break;
5888                 line += 4;
5889                 /* Well, if the title starts with a whitespace character,
5890                  * try to be forgiving.  Otherwise we end up with no title. */
5891                 while (isspace(*line))
5892                         line++;
5893                 if (*line == '\0')
5894                         break;
5895                 /* FIXME: More graceful handling of titles; append "..." to
5896                  * shortened titles, etc. */
5898                 string_expand(commit->title, sizeof(commit->title), line, 1);
5899                 view->line[view->lines - 1].dirty = 1;
5900         }
5902         return TRUE;
5905 static enum request
5906 main_request(struct view *view, enum request request, struct line *line)
5908         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5910         switch (request) {
5911         case REQ_ENTER:
5912                 if (view_is_displayed(view) && display[0] != view)
5913                         maximize_view(view, TRUE);
5914                 open_view(view, REQ_VIEW_DIFF, flags);
5915                 break;
5916         case REQ_REFRESH:
5917                 load_refs();
5918                 refresh_view(view);
5919                 break;
5920         default:
5921                 return request;
5922         }
5924         return REQ_NONE;
5927 static bool
5928 grep_refs(struct ref_list *list, regex_t *regex)
5930         regmatch_t pmatch;
5931         size_t i;
5933         if (!opt_show_refs || !list)
5934                 return FALSE;
5936         for (i = 0; i < list->size; i++) {
5937                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5938                         return TRUE;
5939         }
5941         return FALSE;
5944 static bool
5945 main_grep(struct view *view, struct line *line)
5947         struct commit *commit = line->data;
5948         const char *text[] = {
5949                 commit->title,
5950                 mkauthor(commit->author, opt_author_cols, opt_author),
5951                 mkdate(&commit->time, opt_date),
5952                 NULL
5953         };
5955         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5958 static void
5959 main_select(struct view *view, struct line *line)
5961         struct commit *commit = line->data;
5963         string_copy_rev(view->ref, commit->id);
5964         string_copy_rev(ref_commit, view->ref);
5967 static struct view_ops main_ops = {
5968         "commit",
5969         main_open,
5970         main_read,
5971         main_draw,
5972         main_request,
5973         main_grep,
5974         main_select,
5975 };
5978 /*
5979  * Status management
5980  */
5982 /* Whether or not the curses interface has been initialized. */
5983 static bool cursed = FALSE;
5985 /* Terminal hacks and workarounds. */
5986 static bool use_scroll_redrawwin;
5987 static bool use_scroll_status_wclear;
5989 /* The status window is used for polling keystrokes. */
5990 static WINDOW *status_win;
5992 /* Reading from the prompt? */
5993 static bool input_mode = FALSE;
5995 static bool status_empty = FALSE;
5997 /* Update status and title window. */
5998 static void
5999 report(const char *msg, ...)
6001         struct view *view = display[current_view];
6003         if (input_mode)
6004                 return;
6006         if (!view) {
6007                 char buf[SIZEOF_STR];
6008                 va_list args;
6010                 va_start(args, msg);
6011                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6012                         buf[sizeof(buf) - 1] = 0;
6013                         buf[sizeof(buf) - 2] = '.';
6014                         buf[sizeof(buf) - 3] = '.';
6015                         buf[sizeof(buf) - 4] = '.';
6016                 }
6017                 va_end(args);
6018                 die("%s", buf);
6019         }
6021         if (!status_empty || *msg) {
6022                 va_list args;
6024                 va_start(args, msg);
6026                 wmove(status_win, 0, 0);
6027                 if (view->has_scrolled && use_scroll_status_wclear)
6028                         wclear(status_win);
6029                 if (*msg) {
6030                         vwprintw(status_win, msg, args);
6031                         status_empty = FALSE;
6032                 } else {
6033                         status_empty = TRUE;
6034                 }
6035                 wclrtoeol(status_win);
6036                 wnoutrefresh(status_win);
6038                 va_end(args);
6039         }
6041         update_view_title(view);
6044 static void
6045 init_display(void)
6047         const char *term;
6048         int x, y;
6050         /* Initialize the curses library */
6051         if (isatty(STDIN_FILENO)) {
6052                 cursed = !!initscr();
6053                 opt_tty = stdin;
6054         } else {
6055                 /* Leave stdin and stdout alone when acting as a pager. */
6056                 opt_tty = fopen("/dev/tty", "r+");
6057                 if (!opt_tty)
6058                         die("Failed to open /dev/tty");
6059                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6060         }
6062         if (!cursed)
6063                 die("Failed to initialize curses");
6065         nonl();         /* Disable conversion and detect newlines from input. */
6066         cbreak();       /* Take input chars one at a time, no wait for \n */
6067         noecho();       /* Don't echo input */
6068         leaveok(stdscr, FALSE);
6070         if (has_colors())
6071                 init_colors();
6073         getmaxyx(stdscr, y, x);
6074         status_win = newwin(1, x, y - 1, 0);
6075         if (!status_win)
6076                 die("Failed to create status window");
6078         /* Enable keyboard mapping */
6079         keypad(status_win, TRUE);
6080         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6082 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6083         set_tabsize(opt_tab_size);
6084 #else
6085         TABSIZE = opt_tab_size;
6086 #endif
6088         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6089         if (term && !strcmp(term, "gnome-terminal")) {
6090                 /* In the gnome-terminal-emulator, the message from
6091                  * scrolling up one line when impossible followed by
6092                  * scrolling down one line causes corruption of the
6093                  * status line. This is fixed by calling wclear. */
6094                 use_scroll_status_wclear = TRUE;
6095                 use_scroll_redrawwin = FALSE;
6097         } else if (term && !strcmp(term, "xrvt-xpm")) {
6098                 /* No problems with full optimizations in xrvt-(unicode)
6099                  * and aterm. */
6100                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6102         } else {
6103                 /* When scrolling in (u)xterm the last line in the
6104                  * scrolling direction will update slowly. */
6105                 use_scroll_redrawwin = TRUE;
6106                 use_scroll_status_wclear = FALSE;
6107         }
6110 static int
6111 get_input(int prompt_position)
6113         struct view *view;
6114         int i, key, cursor_y, cursor_x;
6116         if (prompt_position)
6117                 input_mode = TRUE;
6119         while (TRUE) {
6120                 bool loading = FALSE;
6122                 foreach_view (view, i) {
6123                         update_view(view);
6124                         if (view_is_displayed(view) && view->has_scrolled &&
6125                             use_scroll_redrawwin)
6126                                 redrawwin(view->win);
6127                         view->has_scrolled = FALSE;
6128                         if (view->pipe)
6129                                 loading = TRUE;
6130                 }
6132                 /* Update the cursor position. */
6133                 if (prompt_position) {
6134                         getbegyx(status_win, cursor_y, cursor_x);
6135                         cursor_x = prompt_position;
6136                 } else {
6137                         view = display[current_view];
6138                         getbegyx(view->win, cursor_y, cursor_x);
6139                         cursor_x = view->width - 1;
6140                         cursor_y += view->lineno - view->offset;
6141                 }
6142                 setsyx(cursor_y, cursor_x);
6144                 /* Refresh, accept single keystroke of input */
6145                 doupdate();
6146                 nodelay(status_win, loading);
6147                 key = wgetch(status_win);
6149                 /* wgetch() with nodelay() enabled returns ERR when
6150                  * there's no input. */
6151                 if (key == ERR) {
6153                 } else if (key == KEY_RESIZE) {
6154                         int height, width;
6156                         getmaxyx(stdscr, height, width);
6158                         wresize(status_win, 1, width);
6159                         mvwin(status_win, height - 1, 0);
6160                         wnoutrefresh(status_win);
6161                         resize_display();
6162                         redraw_display(TRUE);
6164                 } else {
6165                         input_mode = FALSE;
6166                         return key;
6167                 }
6168         }
6171 static char *
6172 prompt_input(const char *prompt, input_handler handler, void *data)
6174         enum input_status status = INPUT_OK;
6175         static char buf[SIZEOF_STR];
6176         size_t pos = 0;
6178         buf[pos] = 0;
6180         while (status == INPUT_OK || status == INPUT_SKIP) {
6181                 int key;
6183                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6184                 wclrtoeol(status_win);
6186                 key = get_input(pos + 1);
6187                 switch (key) {
6188                 case KEY_RETURN:
6189                 case KEY_ENTER:
6190                 case '\n':
6191                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6192                         break;
6194                 case KEY_BACKSPACE:
6195                         if (pos > 0)
6196                                 buf[--pos] = 0;
6197                         else
6198                                 status = INPUT_CANCEL;
6199                         break;
6201                 case KEY_ESC:
6202                         status = INPUT_CANCEL;
6203                         break;
6205                 default:
6206                         if (pos >= sizeof(buf)) {
6207                                 report("Input string too long");
6208                                 return NULL;
6209                         }
6211                         status = handler(data, buf, key);
6212                         if (status == INPUT_OK)
6213                                 buf[pos++] = (char) key;
6214                 }
6215         }
6217         /* Clear the status window */
6218         status_empty = FALSE;
6219         report("");
6221         if (status == INPUT_CANCEL)
6222                 return NULL;
6224         buf[pos++] = 0;
6226         return buf;
6229 static enum input_status
6230 prompt_yesno_handler(void *data, char *buf, int c)
6232         if (c == 'y' || c == 'Y')
6233                 return INPUT_STOP;
6234         if (c == 'n' || c == 'N')
6235                 return INPUT_CANCEL;
6236         return INPUT_SKIP;
6239 static bool
6240 prompt_yesno(const char *prompt)
6242         char prompt2[SIZEOF_STR];
6244         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6245                 return FALSE;
6247         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6250 static enum input_status
6251 read_prompt_handler(void *data, char *buf, int c)
6253         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6256 static char *
6257 read_prompt(const char *prompt)
6259         return prompt_input(prompt, read_prompt_handler, NULL);
6262 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6264         enum input_status status = INPUT_OK;
6265         int size = 0;
6267         while (items[size].text)
6268                 size++;
6270         while (status == INPUT_OK) {
6271                 const struct menu_item *item = &items[*selected];
6272                 int key;
6273                 int i;
6275                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6276                           prompt, *selected + 1, size);
6277                 if (item->hotkey)
6278                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6279                 wprintw(status_win, "%s", item->text);
6280                 wclrtoeol(status_win);
6282                 key = get_input(COLS - 1);
6283                 switch (key) {
6284                 case KEY_RETURN:
6285                 case KEY_ENTER:
6286                 case '\n':
6287                         status = INPUT_STOP;
6288                         break;
6290                 case KEY_LEFT:
6291                 case KEY_UP:
6292                         *selected = *selected - 1;
6293                         if (*selected < 0)
6294                                 *selected = size - 1;
6295                         break;
6297                 case KEY_RIGHT:
6298                 case KEY_DOWN:
6299                         *selected = (*selected + 1) % size;
6300                         break;
6302                 case KEY_ESC:
6303                         status = INPUT_CANCEL;
6304                         break;
6306                 default:
6307                         for (i = 0; items[i].text; i++)
6308                                 if (items[i].hotkey == key) {
6309                                         *selected = i;
6310                                         status = INPUT_STOP;
6311                                         break;
6312                                 }
6313                 }
6314         }
6316         /* Clear the status window */
6317         status_empty = FALSE;
6318         report("");
6320         return status != INPUT_CANCEL;
6323 /*
6324  * Repository properties
6325  */
6327 static struct ref **refs = NULL;
6328 static size_t refs_size = 0;
6329 static struct ref *refs_head = NULL;
6331 static struct ref_list **ref_lists = NULL;
6332 static size_t ref_lists_size = 0;
6334 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6335 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6336 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6338 static int
6339 compare_refs(const void *ref1_, const void *ref2_)
6341         const struct ref *ref1 = *(const struct ref **)ref1_;
6342         const struct ref *ref2 = *(const struct ref **)ref2_;
6344         if (ref1->tag != ref2->tag)
6345                 return ref2->tag - ref1->tag;
6346         if (ref1->ltag != ref2->ltag)
6347                 return ref2->ltag - ref2->ltag;
6348         if (ref1->head != ref2->head)
6349                 return ref2->head - ref1->head;
6350         if (ref1->tracked != ref2->tracked)
6351                 return ref2->tracked - ref1->tracked;
6352         if (ref1->remote != ref2->remote)
6353                 return ref2->remote - ref1->remote;
6354         return strcmp(ref1->name, ref2->name);
6357 static void
6358 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6360         size_t i;
6362         for (i = 0; i < refs_size; i++)
6363                 if (!visitor(data, refs[i]))
6364                         break;
6367 static struct ref *
6368 get_ref_head()
6370         return refs_head;
6373 static struct ref_list *
6374 get_ref_list(const char *id)
6376         struct ref_list *list;
6377         size_t i;
6379         for (i = 0; i < ref_lists_size; i++)
6380                 if (!strcmp(id, ref_lists[i]->id))
6381                         return ref_lists[i];
6383         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6384                 return NULL;
6385         list = calloc(1, sizeof(*list));
6386         if (!list)
6387                 return NULL;
6389         for (i = 0; i < refs_size; i++) {
6390                 if (!strcmp(id, refs[i]->id) &&
6391                     realloc_refs_list(&list->refs, list->size, 1))
6392                         list->refs[list->size++] = refs[i];
6393         }
6395         if (!list->refs) {
6396                 free(list);
6397                 return NULL;
6398         }
6400         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6401         ref_lists[ref_lists_size++] = list;
6402         return list;
6405 static int
6406 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6408         struct ref *ref = NULL;
6409         bool tag = FALSE;
6410         bool ltag = FALSE;
6411         bool remote = FALSE;
6412         bool tracked = FALSE;
6413         bool head = FALSE;
6414         int from = 0, to = refs_size - 1;
6416         if (!prefixcmp(name, "refs/tags/")) {
6417                 if (!suffixcmp(name, namelen, "^{}")) {
6418                         namelen -= 3;
6419                         name[namelen] = 0;
6420                 } else {
6421                         ltag = TRUE;
6422                 }
6424                 tag = TRUE;
6425                 namelen -= STRING_SIZE("refs/tags/");
6426                 name    += STRING_SIZE("refs/tags/");
6428         } else if (!prefixcmp(name, "refs/remotes/")) {
6429                 remote = TRUE;
6430                 namelen -= STRING_SIZE("refs/remotes/");
6431                 name    += STRING_SIZE("refs/remotes/");
6432                 tracked  = !strcmp(opt_remote, name);
6434         } else if (!prefixcmp(name, "refs/heads/")) {
6435                 namelen -= STRING_SIZE("refs/heads/");
6436                 name    += STRING_SIZE("refs/heads/");
6437                 if (!strncmp(opt_head, name, namelen))
6438                         return OK;
6440         } else if (!strcmp(name, "HEAD")) {
6441                 head     = TRUE;
6442                 if (*opt_head) {
6443                         namelen  = strlen(opt_head);
6444                         name     = opt_head;
6445                 }
6446         }
6448         /* If we are reloading or it's an annotated tag, replace the
6449          * previous SHA1 with the resolved commit id; relies on the fact
6450          * git-ls-remote lists the commit id of an annotated tag right
6451          * before the commit id it points to. */
6452         while (from <= to) {
6453                 size_t pos = (to + from) / 2;
6454                 int cmp = strcmp(name, refs[pos]->name);
6456                 if (!cmp) {
6457                         ref = refs[pos];
6458                         break;
6459                 }
6461                 if (cmp < 0)
6462                         to = pos - 1;
6463                 else
6464                         from = pos + 1;
6465         }
6467         if (!ref) {
6468                 if (!realloc_refs(&refs, refs_size, 1))
6469                         return ERR;
6470                 ref = calloc(1, sizeof(*ref) + namelen);
6471                 if (!ref)
6472                         return ERR;
6473                 memmove(refs + from + 1, refs + from,
6474                         (refs_size - from) * sizeof(*refs));
6475                 refs[from] = ref;
6476                 strncpy(ref->name, name, namelen);
6477                 refs_size++;
6478         }
6480         ref->head = head;
6481         ref->tag = tag;
6482         ref->ltag = ltag;
6483         ref->remote = remote;
6484         ref->tracked = tracked;
6485         string_copy_rev(ref->id, id);
6487         if (head)
6488                 refs_head = ref;
6489         return OK;
6492 static int
6493 load_refs(void)
6495         const char *head_argv[] = {
6496                 "git", "symbolic-ref", "HEAD", NULL
6497         };
6498         static const char *ls_remote_argv[SIZEOF_ARG] = {
6499                 "git", "ls-remote", opt_git_dir, NULL
6500         };
6501         static bool init = FALSE;
6502         size_t i;
6504         if (!init) {
6505                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6506                         die("TIG_LS_REMOTE contains too many arguments");
6507                 init = TRUE;
6508         }
6510         if (!*opt_git_dir)
6511                 return OK;
6513         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6514             !prefixcmp(opt_head, "refs/heads/")) {
6515                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6517                 memmove(opt_head, offset, strlen(offset) + 1);
6518         }
6520         refs_head = NULL;
6521         for (i = 0; i < refs_size; i++)
6522                 refs[i]->id[0] = 0;
6524         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6525                 return ERR;
6527         /* Update the ref lists to reflect changes. */
6528         for (i = 0; i < ref_lists_size; i++) {
6529                 struct ref_list *list = ref_lists[i];
6530                 size_t old, new;
6532                 for (old = new = 0; old < list->size; old++)
6533                         if (!strcmp(list->id, list->refs[old]->id))
6534                                 list->refs[new++] = list->refs[old];
6535                 list->size = new;
6536         }
6538         return OK;
6541 static void
6542 set_remote_branch(const char *name, const char *value, size_t valuelen)
6544         if (!strcmp(name, ".remote")) {
6545                 string_ncopy(opt_remote, value, valuelen);
6547         } else if (*opt_remote && !strcmp(name, ".merge")) {
6548                 size_t from = strlen(opt_remote);
6550                 if (!prefixcmp(value, "refs/heads/"))
6551                         value += STRING_SIZE("refs/heads/");
6553                 if (!string_format_from(opt_remote, &from, "/%s", value))
6554                         opt_remote[0] = 0;
6555         }
6558 static void
6559 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6561         const char *argv[SIZEOF_ARG] = { name, "=" };
6562         int argc = 1 + (cmd == option_set_command);
6563         enum option_code error;
6565         if (!argv_from_string(argv, &argc, value))
6566                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6567         else
6568                 error = cmd(argc, argv);
6570         if (error != OPT_OK)
6571                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6574 static bool
6575 set_environment_variable(const char *name, const char *value)
6577         size_t len = strlen(name) + 1 + strlen(value) + 1;
6578         char *env = malloc(len);
6580         if (env &&
6581             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6582             putenv(env) == 0)
6583                 return TRUE;
6584         free(env);
6585         return FALSE;
6588 static void
6589 set_work_tree(const char *value)
6591         char cwd[SIZEOF_STR];
6593         if (!getcwd(cwd, sizeof(cwd)))
6594                 die("Failed to get cwd path: %s", strerror(errno));
6595         if (chdir(opt_git_dir) < 0)
6596                 die("Failed to chdir(%s): %s", strerror(errno));
6597         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6598                 die("Failed to get git path: %s", strerror(errno));
6599         if (chdir(cwd) < 0)
6600                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6601         if (chdir(value) < 0)
6602                 die("Failed to chdir(%s): %s", value, strerror(errno));
6603         if (!getcwd(cwd, sizeof(cwd)))
6604                 die("Failed to get cwd path: %s", strerror(errno));
6605         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6606                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6607         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6608                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6609         opt_is_inside_work_tree = TRUE;
6612 static int
6613 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6615         if (!strcmp(name, "i18n.commitencoding"))
6616                 string_ncopy(opt_encoding, value, valuelen);
6618         else if (!strcmp(name, "core.editor"))
6619                 string_ncopy(opt_editor, value, valuelen);
6621         else if (!strcmp(name, "core.worktree"))
6622                 set_work_tree(value);
6624         else if (!prefixcmp(name, "tig.color."))
6625                 set_repo_config_option(name + 10, value, option_color_command);
6627         else if (!prefixcmp(name, "tig.bind."))
6628                 set_repo_config_option(name + 9, value, option_bind_command);
6630         else if (!prefixcmp(name, "tig."))
6631                 set_repo_config_option(name + 4, value, option_set_command);
6633         else if (*opt_head && !prefixcmp(name, "branch.") &&
6634                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6635                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6637         return OK;
6640 static int
6641 load_git_config(void)
6643         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6645         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6648 static int
6649 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6651         if (!opt_git_dir[0]) {
6652                 string_ncopy(opt_git_dir, name, namelen);
6654         } else if (opt_is_inside_work_tree == -1) {
6655                 /* This can be 3 different values depending on the
6656                  * version of git being used. If git-rev-parse does not
6657                  * understand --is-inside-work-tree it will simply echo
6658                  * the option else either "true" or "false" is printed.
6659                  * Default to true for the unknown case. */
6660                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6662         } else if (*name == '.') {
6663                 string_ncopy(opt_cdup, name, namelen);
6665         } else {
6666                 string_ncopy(opt_prefix, name, namelen);
6667         }
6669         return OK;
6672 static int
6673 load_repo_info(void)
6675         const char *rev_parse_argv[] = {
6676                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6677                         "--show-cdup", "--show-prefix", NULL
6678         };
6680         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6684 /*
6685  * Main
6686  */
6688 static const char usage[] =
6689 "tig " TIG_VERSION " (" __DATE__ ")\n"
6690 "\n"
6691 "Usage: tig        [options] [revs] [--] [paths]\n"
6692 "   or: tig show   [options] [revs] [--] [paths]\n"
6693 "   or: tig blame  [options] [rev] [--] path\n"
6694 "   or: tig status\n"
6695 "   or: tig <      [git command output]\n"
6696 "\n"
6697 "Options:\n"
6698 "  -v, --version   Show version and exit\n"
6699 "  -h, --help      Show help message and exit";
6701 static void __NORETURN
6702 quit(int sig)
6704         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6705         if (cursed)
6706                 endwin();
6707         exit(0);
6710 static void __NORETURN
6711 die(const char *err, ...)
6713         va_list args;
6715         endwin();
6717         va_start(args, err);
6718         fputs("tig: ", stderr);
6719         vfprintf(stderr, err, args);
6720         fputs("\n", stderr);
6721         va_end(args);
6723         exit(1);
6726 static void
6727 warn(const char *msg, ...)
6729         va_list args;
6731         va_start(args, msg);
6732         fputs("tig warning: ", stderr);
6733         vfprintf(stderr, msg, args);
6734         fputs("\n", stderr);
6735         va_end(args);
6738 static int
6739 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6741         const char ***filter_args = data;
6743         return argv_append(filter_args, name) ? OK : ERR;
6746 static void
6747 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6749         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6750         const char **all_argv = NULL;
6752         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6753             !argv_append_array(&all_argv, argv) ||
6754             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6755                 die("Failed to split arguments");
6756         argv_free(all_argv);
6757         free(all_argv);
6760 static void
6761 filter_options(const char *argv[])
6763         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6764         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6765         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6768 static enum request
6769 parse_options(int argc, const char *argv[])
6771         enum request request = REQ_VIEW_MAIN;
6772         const char *subcommand;
6773         bool seen_dashdash = FALSE;
6774         const char **filter_argv = NULL;
6775         int i;
6777         if (!isatty(STDIN_FILENO))
6778                 return REQ_VIEW_PAGER;
6780         if (argc <= 1)
6781                 return REQ_VIEW_MAIN;
6783         subcommand = argv[1];
6784         if (!strcmp(subcommand, "status")) {
6785                 if (argc > 2)
6786                         warn("ignoring arguments after `%s'", subcommand);
6787                 return REQ_VIEW_STATUS;
6789         } else if (!strcmp(subcommand, "blame")) {
6790                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6791                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6792                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6794                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6795                         die("invalid number of options to blame\n\n%s", usage);
6797                 if (opt_rev_argv) {
6798                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6799                 }
6801                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6802                 return REQ_VIEW_BLAME;
6804         } else if (!strcmp(subcommand, "show")) {
6805                 request = REQ_VIEW_DIFF;
6807         } else {
6808                 subcommand = NULL;
6809         }
6811         for (i = 1 + !!subcommand; i < argc; i++) {
6812                 const char *opt = argv[i];
6814                 if (seen_dashdash) {
6815                         argv_append(&opt_file_argv, opt);
6816                         continue;
6818                 } else if (!strcmp(opt, "--")) {
6819                         seen_dashdash = TRUE;
6820                         continue;
6822                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6823                         printf("tig version %s\n", TIG_VERSION);
6824                         quit(0);
6826                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6827                         printf("%s\n", usage);
6828                         quit(0);
6830                 } else if (!strcmp(opt, "--all")) {
6831                         argv_append(&opt_rev_argv, opt);
6832                         continue;
6833                 }
6835                 if (!argv_append(&filter_argv, opt))
6836                         die("command too long");
6837         }
6839         if (filter_argv)
6840                 filter_options(filter_argv);
6842         return request;
6845 int
6846 main(int argc, const char *argv[])
6848         const char *codeset = "UTF-8";
6849         enum request request = parse_options(argc, argv);
6850         struct view *view;
6852         signal(SIGINT, quit);
6853         signal(SIGPIPE, SIG_IGN);
6855         if (setlocale(LC_ALL, "")) {
6856                 codeset = nl_langinfo(CODESET);
6857         }
6859         if (load_repo_info() == ERR)
6860                 die("Failed to load repo info.");
6862         if (load_options() == ERR)
6863                 die("Failed to load user config.");
6865         if (load_git_config() == ERR)
6866                 die("Failed to load repo config.");
6868         /* Require a git repository unless when running in pager mode. */
6869         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6870                 die("Not a git repository");
6872         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6873                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6874                 if (opt_iconv_in == ICONV_NONE)
6875                         die("Failed to initialize character set conversion");
6876         }
6878         if (codeset && strcmp(codeset, "UTF-8")) {
6879                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6880                 if (opt_iconv_out == ICONV_NONE)
6881                         die("Failed to initialize character set conversion");
6882         }
6884         if (load_refs() == ERR)
6885                 die("Failed to load refs.");
6887         init_display();
6889         while (view_driver(display[current_view], request)) {
6890                 int key = get_input(0);
6892                 view = display[current_view];
6893                 request = get_keybinding(view->keymap, key);
6895                 /* Some low-level request handling. This keeps access to
6896                  * status_win restricted. */
6897                 switch (request) {
6898                 case REQ_NONE:
6899                         report("Unknown key, press %s for help",
6900                                get_key(view->keymap, REQ_VIEW_HELP));
6901                         break;
6902                 case REQ_PROMPT:
6903                 {
6904                         char *cmd = read_prompt(":");
6906                         if (cmd && isdigit(*cmd)) {
6907                                 int lineno = view->lineno + 1;
6909                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6910                                         select_view_line(view, lineno - 1);
6911                                         report("");
6912                                 } else {
6913                                         report("Unable to parse '%s' as a line number", cmd);
6914                                 }
6916                         } else if (cmd) {
6917                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6918                                 const char *argv[SIZEOF_ARG] = { "git" };
6919                                 int argc = 1;
6921                                 /* When running random commands, initially show the
6922                                  * command in the title. However, it maybe later be
6923                                  * overwritten if a commit line is selected. */
6924                                 string_ncopy(next->ref, cmd, strlen(cmd));
6926                                 if (!argv_from_string(argv, &argc, cmd)) {
6927                                         report("Too many arguments");
6928                                 } else {
6929                                         open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6930                                 }
6931                         }
6933                         request = REQ_NONE;
6934                         break;
6935                 }
6936                 case REQ_SEARCH:
6937                 case REQ_SEARCH_BACK:
6938                 {
6939                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6940                         char *search = read_prompt(prompt);
6942                         if (search)
6943                                 string_ncopy(opt_search, search, strlen(search));
6944                         else if (*opt_search)
6945                                 request = request == REQ_SEARCH ?
6946                                         REQ_FIND_NEXT :
6947                                         REQ_FIND_PREV;
6948                         else
6949                                 request = REQ_NONE;
6950                         break;
6951                 }
6952                 default:
6953                         break;
6954                 }
6955         }
6957         quit(0);
6959         return 0;