Code

get_author_initials: various fixes
[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 (author < end && is_initial_sep(*author))
162                         author++;
164                 bytes = utf8_char_length(author, end);
165                 if (bytes >= sizeof(initials) - 1 - pos)
166                         break;
167                 while (bytes--) {
168                         initials[pos++] = *author++;
169                 }
171                 i = pos;
172                 while (author < end && !is_initial_sep(*author)) {
173                         bytes = utf8_char_length(author, end);
174                         if (bytes >= sizeof(initials) - 1 - i) {
175                                 while (author < end && !is_initial_sep(*author))
176                                         author++;
177                                 break;
178                         }
179                         while (bytes--) {
180                                 initials[i++] = *author++;
181                         }
182                 }
184                 initials[i++] = 0;
185         }
187         return initials;
190 #define author_trim(cols) (cols == 0 || cols > 5)
192 static const char *
193 mkauthor(const char *text, int cols, enum author author)
195         bool trim = author_trim(cols);
196         bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
198         if (author == AUTHOR_NO)
199                 return "";
200         if (abbreviate && text)
201                 return get_author_initials(text);
202         return text;
205 static const char *
206 mkmode(mode_t mode)
208         if (S_ISDIR(mode))
209                 return "drwxr-xr-x";
210         else if (S_ISLNK(mode))
211                 return "lrwxrwxrwx";
212         else if (S_ISGITLINK(mode))
213                 return "m---------";
214         else if (S_ISREG(mode) && mode & S_IXUSR)
215                 return "-rwxr-xr-x";
216         else if (S_ISREG(mode))
217                 return "-rw-r--r--";
218         else
219                 return "----------";
223 /*
224  * User requests
225  */
227 #define REQ_INFO \
228         /* XXX: Keep the view request first and in sync with views[]. */ \
229         REQ_GROUP("View switching") \
230         REQ_(VIEW_MAIN,         "Show main view"), \
231         REQ_(VIEW_DIFF,         "Show diff view"), \
232         REQ_(VIEW_LOG,          "Show log view"), \
233         REQ_(VIEW_TREE,         "Show tree view"), \
234         REQ_(VIEW_BLOB,         "Show blob view"), \
235         REQ_(VIEW_BLAME,        "Show blame view"), \
236         REQ_(VIEW_BRANCH,       "Show branch view"), \
237         REQ_(VIEW_HELP,         "Show help page"), \
238         REQ_(VIEW_PAGER,        "Show pager view"), \
239         REQ_(VIEW_STATUS,       "Show status view"), \
240         REQ_(VIEW_STAGE,        "Show stage view"), \
241         \
242         REQ_GROUP("View manipulation") \
243         REQ_(ENTER,             "Enter current line and scroll"), \
244         REQ_(NEXT,              "Move to next"), \
245         REQ_(PREVIOUS,          "Move to previous"), \
246         REQ_(PARENT,            "Move to parent"), \
247         REQ_(VIEW_NEXT,         "Move focus to next view"), \
248         REQ_(REFRESH,           "Reload and refresh"), \
249         REQ_(MAXIMIZE,          "Maximize the current view"), \
250         REQ_(VIEW_CLOSE,        "Close the current view"), \
251         REQ_(QUIT,              "Close all views and quit"), \
252         \
253         REQ_GROUP("View specific requests") \
254         REQ_(STATUS_UPDATE,     "Update file status"), \
255         REQ_(STATUS_REVERT,     "Revert file changes"), \
256         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
257         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
258         \
259         REQ_GROUP("Cursor navigation") \
260         REQ_(MOVE_UP,           "Move cursor one line up"), \
261         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
262         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
263         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
264         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
265         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
266         \
267         REQ_GROUP("Scrolling") \
268         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
269         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
270         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
271         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
272         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
273         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
274         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
275         \
276         REQ_GROUP("Searching") \
277         REQ_(SEARCH,            "Search the view"), \
278         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
279         REQ_(FIND_NEXT,         "Find next search match"), \
280         REQ_(FIND_PREV,         "Find previous search match"), \
281         \
282         REQ_GROUP("Option manipulation") \
283         REQ_(OPTIONS,           "Open option menu"), \
284         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
285         REQ_(TOGGLE_DATE,       "Toggle date display"), \
286         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
287         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
288         REQ_(TOGGLE_GRAPHIC,    "Toggle (line) graphics mode"), \
289         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
290         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
291         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
292         \
293         REQ_GROUP("Misc") \
294         REQ_(PROMPT,            "Bring up the prompt"), \
295         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
296         REQ_(SHOW_VERSION,      "Show version information"), \
297         REQ_(STOP_LOADING,      "Stop all loading views"), \
298         REQ_(EDIT,              "Open in editor"), \
299         REQ_(NONE,              "Do nothing")
302 /* User action requests. */
303 enum request {
304 #define REQ_GROUP(help)
305 #define REQ_(req, help) REQ_##req
307         /* Offset all requests to avoid conflicts with ncurses getch values. */
308         REQ_UNKNOWN = KEY_MAX + 1,
309         REQ_OFFSET,
310         REQ_INFO
312 #undef  REQ_GROUP
313 #undef  REQ_
314 };
316 struct request_info {
317         enum request request;
318         const char *name;
319         int namelen;
320         const char *help;
321 };
323 static const struct request_info req_info[] = {
324 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
325 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
326         REQ_INFO
327 #undef  REQ_GROUP
328 #undef  REQ_
329 };
331 static enum request
332 get_request(const char *name)
334         int namelen = strlen(name);
335         int i;
337         for (i = 0; i < ARRAY_SIZE(req_info); i++)
338                 if (enum_equals(req_info[i], name, namelen))
339                         return req_info[i].request;
341         return REQ_UNKNOWN;
345 /*
346  * Options
347  */
349 /* Option and state variables. */
350 static enum graphic opt_line_graphics   = GRAPHIC_DEFAULT;
351 static enum date opt_date               = DATE_DEFAULT;
352 static enum author opt_author           = AUTHOR_FULL;
353 static bool opt_rev_graph               = TRUE;
354 static bool opt_line_number             = FALSE;
355 static bool opt_show_refs               = TRUE;
356 static bool opt_untracked_dirs_content  = TRUE;
357 static int opt_num_interval             = 5;
358 static double opt_hscroll               = 0.50;
359 static double opt_scale_split_view      = 2.0 / 3.0;
360 static int opt_tab_size                 = 8;
361 static int opt_author_cols              = AUTHOR_COLS;
362 static char opt_path[SIZEOF_STR]        = "";
363 static char opt_file[SIZEOF_STR]        = "";
364 static char opt_ref[SIZEOF_REF]         = "";
365 static char opt_head[SIZEOF_REF]        = "";
366 static char opt_remote[SIZEOF_REF]      = "";
367 static char opt_encoding[20]            = "UTF-8";
368 static iconv_t opt_iconv_in             = ICONV_NONE;
369 static iconv_t opt_iconv_out            = ICONV_NONE;
370 static char opt_search[SIZEOF_STR]      = "";
371 static char opt_cdup[SIZEOF_STR]        = "";
372 static char opt_prefix[SIZEOF_STR]      = "";
373 static char opt_git_dir[SIZEOF_STR]     = "";
374 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
375 static char opt_editor[SIZEOF_STR]      = "";
376 static FILE *opt_tty                    = NULL;
377 static const char **opt_diff_argv       = NULL;
378 static const char **opt_rev_argv        = NULL;
379 static const char **opt_file_argv       = NULL;
380 static const char **opt_blame_argv      = NULL;
382 #define is_initial_commit()     (!get_ref_head())
383 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
386 /*
387  * Line-oriented content detection.
388  */
390 #define LINE_INFO \
391 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
392 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
393 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
394 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
395 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
396 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
397 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
398 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
399 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
400 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
401 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
402 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
403 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
404 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
405 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
406 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
407 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
408 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
409 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
410 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
411 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
412 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
413 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
414 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
415 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
416 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
417 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
418 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
419 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
420 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
421 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
422 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
423 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
424 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
425 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
426 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
427 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
428 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
429 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
430 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
431 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
432 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
433 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
434 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
435 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
436 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
437 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
438 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
439 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
440 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
441 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
442 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
443 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
444 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
445 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
446 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
447 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
448 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
449 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
450 LINE(GRAPH_LINE_0, "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
451 LINE(GRAPH_LINE_1, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
452 LINE(GRAPH_LINE_2, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
453 LINE(GRAPH_LINE_3, "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
454 LINE(GRAPH_LINE_4, "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
455 LINE(GRAPH_LINE_5, "",                  COLOR_WHITE,    COLOR_DEFAULT,  0), \
456 LINE(GRAPH_LINE_6, "",                  COLOR_RED,      COLOR_DEFAULT,  0), \
457 LINE(GRAPH_COMMIT, "",                  COLOR_BLUE,     COLOR_DEFAULT,  0)
459 enum line_type {
460 #define LINE(type, line, fg, bg, attr) \
461         LINE_##type
462         LINE_INFO,
463         LINE_NONE
464 #undef  LINE
465 };
467 struct line_info {
468         const char *name;       /* Option name. */
469         int namelen;            /* Size of option name. */
470         const char *line;       /* The start of line to match. */
471         int linelen;            /* Size of string to match. */
472         int fg, bg, attr;       /* Color and text attributes for the lines. */
473 };
475 static struct line_info line_info[] = {
476 #define LINE(type, line, fg, bg, attr) \
477         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
478         LINE_INFO
479 #undef  LINE
480 };
482 static enum line_type
483 get_line_type(const char *line)
485         int linelen = strlen(line);
486         enum line_type type;
488         for (type = 0; type < ARRAY_SIZE(line_info); type++)
489                 /* Case insensitive search matches Signed-off-by lines better. */
490                 if (linelen >= line_info[type].linelen &&
491                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
492                         return type;
494         return LINE_DEFAULT;
497 static inline int
498 get_line_attr(enum line_type type)
500         assert(type < ARRAY_SIZE(line_info));
501         return COLOR_PAIR(type) | line_info[type].attr;
504 static struct line_info *
505 get_line_info(const char *name)
507         size_t namelen = strlen(name);
508         enum line_type type;
510         for (type = 0; type < ARRAY_SIZE(line_info); type++)
511                 if (enum_equals(line_info[type], name, namelen))
512                         return &line_info[type];
514         return NULL;
517 static void
518 init_colors(void)
520         int default_bg = line_info[LINE_DEFAULT].bg;
521         int default_fg = line_info[LINE_DEFAULT].fg;
522         enum line_type type;
524         start_color();
526         if (assume_default_colors(default_fg, default_bg) == ERR) {
527                 default_bg = COLOR_BLACK;
528                 default_fg = COLOR_WHITE;
529         }
531         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
532                 struct line_info *info = &line_info[type];
533                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
534                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
536                 init_pair(type, fg, bg);
537         }
540 struct line {
541         enum line_type type;
543         /* State flags */
544         unsigned int selected:1;
545         unsigned int dirty:1;
546         unsigned int cleareol:1;
547         unsigned int other:16;
549         void *data;             /* User data */
550 };
553 /*
554  * Keys
555  */
557 struct keybinding {
558         int alias;
559         enum request request;
560 };
562 static struct keybinding default_keybindings[] = {
563         /* View switching */
564         { 'm',          REQ_VIEW_MAIN },
565         { 'd',          REQ_VIEW_DIFF },
566         { 'l',          REQ_VIEW_LOG },
567         { 't',          REQ_VIEW_TREE },
568         { 'f',          REQ_VIEW_BLOB },
569         { 'B',          REQ_VIEW_BLAME },
570         { 'H',          REQ_VIEW_BRANCH },
571         { 'p',          REQ_VIEW_PAGER },
572         { 'h',          REQ_VIEW_HELP },
573         { 'S',          REQ_VIEW_STATUS },
574         { 'c',          REQ_VIEW_STAGE },
576         /* View manipulation */
577         { 'q',          REQ_VIEW_CLOSE },
578         { KEY_TAB,      REQ_VIEW_NEXT },
579         { KEY_RETURN,   REQ_ENTER },
580         { KEY_UP,       REQ_PREVIOUS },
581         { KEY_CTL('P'), REQ_PREVIOUS },
582         { KEY_DOWN,     REQ_NEXT },
583         { KEY_CTL('N'), REQ_NEXT },
584         { 'R',          REQ_REFRESH },
585         { KEY_F(5),     REQ_REFRESH },
586         { 'O',          REQ_MAXIMIZE },
588         /* Cursor navigation */
589         { 'k',          REQ_MOVE_UP },
590         { 'j',          REQ_MOVE_DOWN },
591         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
592         { KEY_END,      REQ_MOVE_LAST_LINE },
593         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
594         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
595         { ' ',          REQ_MOVE_PAGE_DOWN },
596         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
597         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
598         { 'b',          REQ_MOVE_PAGE_UP },
599         { '-',          REQ_MOVE_PAGE_UP },
601         /* Scrolling */
602         { '|',          REQ_SCROLL_FIRST_COL },
603         { KEY_LEFT,     REQ_SCROLL_LEFT },
604         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
605         { KEY_IC,       REQ_SCROLL_LINE_UP },
606         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
607         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
608         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
609         { 'w',          REQ_SCROLL_PAGE_UP },
610         { 's',          REQ_SCROLL_PAGE_DOWN },
612         /* Searching */
613         { '/',          REQ_SEARCH },
614         { '?',          REQ_SEARCH_BACK },
615         { 'n',          REQ_FIND_NEXT },
616         { 'N',          REQ_FIND_PREV },
618         /* Misc */
619         { 'Q',          REQ_QUIT },
620         { 'z',          REQ_STOP_LOADING },
621         { 'v',          REQ_SHOW_VERSION },
622         { 'r',          REQ_SCREEN_REDRAW },
623         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
624         { 'o',          REQ_OPTIONS },
625         { '.',          REQ_TOGGLE_LINENO },
626         { 'D',          REQ_TOGGLE_DATE },
627         { 'A',          REQ_TOGGLE_AUTHOR },
628         { 'g',          REQ_TOGGLE_REV_GRAPH },
629         { '~',          REQ_TOGGLE_GRAPHIC },
630         { 'F',          REQ_TOGGLE_REFS },
631         { 'I',          REQ_TOGGLE_SORT_ORDER },
632         { 'i',          REQ_TOGGLE_SORT_FIELD },
633         { ':',          REQ_PROMPT },
634         { 'u',          REQ_STATUS_UPDATE },
635         { '!',          REQ_STATUS_REVERT },
636         { 'M',          REQ_STATUS_MERGE },
637         { '@',          REQ_STAGE_NEXT },
638         { ',',          REQ_PARENT },
639         { 'e',          REQ_EDIT },
640 };
642 #define KEYMAP_ENUM(_) \
643         _(KEYMAP, GENERIC), \
644         _(KEYMAP, MAIN), \
645         _(KEYMAP, DIFF), \
646         _(KEYMAP, LOG), \
647         _(KEYMAP, TREE), \
648         _(KEYMAP, BLOB), \
649         _(KEYMAP, BLAME), \
650         _(KEYMAP, BRANCH), \
651         _(KEYMAP, PAGER), \
652         _(KEYMAP, HELP), \
653         _(KEYMAP, STATUS), \
654         _(KEYMAP, STAGE)
656 DEFINE_ENUM(keymap, KEYMAP_ENUM);
658 #define set_keymap(map, name) map_enum(map, keymap_map, name)
660 struct keybinding_table {
661         struct keybinding *data;
662         size_t size;
663 };
665 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
667 static void
668 add_keybinding(enum keymap keymap, enum request request, int key)
670         struct keybinding_table *table = &keybindings[keymap];
671         size_t i;
673         for (i = 0; i < keybindings[keymap].size; i++) {
674                 if (keybindings[keymap].data[i].alias == key) {
675                         keybindings[keymap].data[i].request = request;
676                         return;
677                 }
678         }
680         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
681         if (!table->data)
682                 die("Failed to allocate keybinding");
683         table->data[table->size].alias = key;
684         table->data[table->size++].request = request;
686         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
687                 int i;
689                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
690                         if (default_keybindings[i].alias == key)
691                                 default_keybindings[i].request = REQ_NONE;
692         }
695 /* Looks for a key binding first in the given map, then in the generic map, and
696  * lastly in the default keybindings. */
697 static enum request
698 get_keybinding(enum keymap keymap, int key)
700         size_t i;
702         for (i = 0; i < keybindings[keymap].size; i++)
703                 if (keybindings[keymap].data[i].alias == key)
704                         return keybindings[keymap].data[i].request;
706         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
707                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
708                         return keybindings[KEYMAP_GENERIC].data[i].request;
710         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
711                 if (default_keybindings[i].alias == key)
712                         return default_keybindings[i].request;
714         return (enum request) key;
718 struct key {
719         const char *name;
720         int value;
721 };
723 static const struct key key_table[] = {
724         { "Enter",      KEY_RETURN },
725         { "Space",      ' ' },
726         { "Backspace",  KEY_BACKSPACE },
727         { "Tab",        KEY_TAB },
728         { "Escape",     KEY_ESC },
729         { "Left",       KEY_LEFT },
730         { "Right",      KEY_RIGHT },
731         { "Up",         KEY_UP },
732         { "Down",       KEY_DOWN },
733         { "Insert",     KEY_IC },
734         { "Delete",     KEY_DC },
735         { "Hash",       '#' },
736         { "Home",       KEY_HOME },
737         { "End",        KEY_END },
738         { "PageUp",     KEY_PPAGE },
739         { "PageDown",   KEY_NPAGE },
740         { "F1",         KEY_F(1) },
741         { "F2",         KEY_F(2) },
742         { "F3",         KEY_F(3) },
743         { "F4",         KEY_F(4) },
744         { "F5",         KEY_F(5) },
745         { "F6",         KEY_F(6) },
746         { "F7",         KEY_F(7) },
747         { "F8",         KEY_F(8) },
748         { "F9",         KEY_F(9) },
749         { "F10",        KEY_F(10) },
750         { "F11",        KEY_F(11) },
751         { "F12",        KEY_F(12) },
752 };
754 static int
755 get_key_value(const char *name)
757         int i;
759         for (i = 0; i < ARRAY_SIZE(key_table); i++)
760                 if (!strcasecmp(key_table[i].name, name))
761                         return key_table[i].value;
763         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
764                 return (int)name[1] & 0x1f;
765         if (strlen(name) == 1 && isprint(*name))
766                 return (int) *name;
767         return ERR;
770 static const char *
771 get_key_name(int key_value)
773         static char key_char[] = "'X'\0";
774         const char *seq = NULL;
775         int key;
777         for (key = 0; key < ARRAY_SIZE(key_table); key++)
778                 if (key_table[key].value == key_value)
779                         seq = key_table[key].name;
781         if (seq == NULL && key_value < 0x7f) {
782                 char *s = key_char + 1;
784                 if (key_value >= 0x20) {
785                         *s++ = key_value;
786                 } else {
787                         *s++ = '^';
788                         *s++ = 0x40 | (key_value & 0x1f);
789                 }
790                 *s++ = '\'';
791                 *s++ = '\0';
792                 seq = key_char;
793         }
795         return seq ? seq : "(no key)";
798 static bool
799 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
801         const char *sep = *pos > 0 ? ", " : "";
802         const char *keyname = get_key_name(keybinding->alias);
804         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
807 static bool
808 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
809                            enum keymap keymap, bool all)
811         int i;
813         for (i = 0; i < keybindings[keymap].size; i++) {
814                 if (keybindings[keymap].data[i].request == request) {
815                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
816                                 return FALSE;
817                         if (!all)
818                                 break;
819                 }
820         }
822         return TRUE;
825 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
827 static const char *
828 get_keys(enum keymap keymap, enum request request, bool all)
830         static char buf[BUFSIZ];
831         size_t pos = 0;
832         int i;
834         buf[pos] = 0;
836         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
837                 return "Too many keybindings!";
838         if (pos > 0 && !all)
839                 return buf;
841         if (keymap != KEYMAP_GENERIC) {
842                 /* Only the generic keymap includes the default keybindings when
843                  * listing all keys. */
844                 if (all)
845                         return buf;
847                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
848                         return "Too many keybindings!";
849                 if (pos)
850                         return buf;
851         }
853         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
854                 if (default_keybindings[i].request == request) {
855                         if (!append_key(buf, &pos, &default_keybindings[i]))
856                                 return "Too many keybindings!";
857                         if (!all)
858                                 return buf;
859                 }
860         }
862         return buf;
865 struct run_request {
866         enum keymap keymap;
867         int key;
868         const char **argv;
869 };
871 static struct run_request *run_request;
872 static size_t run_requests;
874 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
876 static enum request
877 add_run_request(enum keymap keymap, int key, const char **argv)
879         struct run_request *req;
881         if (!realloc_run_requests(&run_request, run_requests, 1))
882                 return REQ_NONE;
884         req = &run_request[run_requests];
885         req->keymap = keymap;
886         req->key = key;
887         req->argv = NULL;
889         if (!argv_copy(&req->argv, argv))
890                 return REQ_NONE;
892         return REQ_NONE + ++run_requests;
895 static struct run_request *
896 get_run_request(enum request request)
898         if (request <= REQ_NONE)
899                 return NULL;
900         return &run_request[request - REQ_NONE - 1];
903 static void
904 add_builtin_run_requests(void)
906         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
907         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
908         const char *commit[] = { "git", "commit", NULL };
909         const char *gc[] = { "git", "gc", NULL };
910         struct run_request reqs[] = {
911                 { KEYMAP_MAIN,    'C', cherry_pick },
912                 { KEYMAP_STATUS,  'C', commit },
913                 { KEYMAP_BRANCH,  'C', checkout },
914                 { KEYMAP_GENERIC, 'G', gc },
915         };
916         int i;
918         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
919                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
921                 if (req != reqs[i].key)
922                         continue;
923                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
924                 if (req != REQ_NONE)
925                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
926         }
929 /*
930  * User config file handling.
931  */
933 #define OPT_ERR_INFO \
934         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
935         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
936         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
937         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
938         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
939         OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
940         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
941         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
942         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
943         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
944         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
945         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
946         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
947         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
948         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
949         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
950         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
952 enum option_code {
953 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
954         OPT_ERR_INFO
955 #undef  OPT_ERR_
956         OPT_OK
957 };
959 static const char *option_errors[] = {
960 #define OPT_ERR_(name, msg) msg
961         OPT_ERR_INFO
962 #undef  OPT_ERR_
963 };
965 static const struct enum_map color_map[] = {
966 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
967         COLOR_MAP(DEFAULT),
968         COLOR_MAP(BLACK),
969         COLOR_MAP(BLUE),
970         COLOR_MAP(CYAN),
971         COLOR_MAP(GREEN),
972         COLOR_MAP(MAGENTA),
973         COLOR_MAP(RED),
974         COLOR_MAP(WHITE),
975         COLOR_MAP(YELLOW),
976 };
978 static const struct enum_map attr_map[] = {
979 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
980         ATTR_MAP(NORMAL),
981         ATTR_MAP(BLINK),
982         ATTR_MAP(BOLD),
983         ATTR_MAP(DIM),
984         ATTR_MAP(REVERSE),
985         ATTR_MAP(STANDOUT),
986         ATTR_MAP(UNDERLINE),
987 };
989 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
991 static enum option_code
992 parse_step(double *opt, const char *arg)
994         *opt = atoi(arg);
995         if (!strchr(arg, '%'))
996                 return OPT_OK;
998         /* "Shift down" so 100% and 1 does not conflict. */
999         *opt = (*opt - 1) / 100;
1000         if (*opt >= 1.0) {
1001                 *opt = 0.99;
1002                 return OPT_ERR_INVALID_STEP_VALUE;
1003         }
1004         if (*opt < 0.0) {
1005                 *opt = 1;
1006                 return OPT_ERR_INVALID_STEP_VALUE;
1007         }
1008         return OPT_OK;
1011 static enum option_code
1012 parse_int(int *opt, const char *arg, int min, int max)
1014         int value = atoi(arg);
1016         if (min <= value && value <= max) {
1017                 *opt = value;
1018                 return OPT_OK;
1019         }
1021         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1024 static bool
1025 set_color(int *color, const char *name)
1027         if (map_enum(color, color_map, name))
1028                 return TRUE;
1029         if (!prefixcmp(name, "color"))
1030                 return parse_int(color, name + 5, 0, 255) == OK;
1031         return FALSE;
1034 /* Wants: object fgcolor bgcolor [attribute] */
1035 static enum option_code
1036 option_color_command(int argc, const char *argv[])
1038         struct line_info *info;
1040         if (argc < 3)
1041                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1043         info = get_line_info(argv[0]);
1044         if (!info) {
1045                 static const struct enum_map obsolete[] = {
1046                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1047                         ENUM_MAP("main-date",   LINE_DATE),
1048                         ENUM_MAP("main-author", LINE_AUTHOR),
1049                 };
1050                 int index;
1052                 if (!map_enum(&index, obsolete, argv[0]))
1053                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1054                 info = &line_info[index];
1055         }
1057         if (!set_color(&info->fg, argv[1]) ||
1058             !set_color(&info->bg, argv[2]))
1059                 return OPT_ERR_UNKNOWN_COLOR;
1061         info->attr = 0;
1062         while (argc-- > 3) {
1063                 int attr;
1065                 if (!set_attribute(&attr, argv[argc]))
1066                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1067                 info->attr |= attr;
1068         }
1070         return OPT_OK;
1073 static enum option_code
1074 parse_bool(bool *opt, const char *arg)
1076         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1077                 ? TRUE : FALSE;
1078         return OPT_OK;
1081 static enum option_code
1082 parse_enum_do(unsigned int *opt, const char *arg,
1083               const struct enum_map *map, size_t map_size)
1085         bool is_true;
1087         assert(map_size > 1);
1089         if (map_enum_do(map, map_size, (int *) opt, arg))
1090                 return OPT_OK;
1092         parse_bool(&is_true, arg);
1093         *opt = is_true ? map[1].value : map[0].value;
1094         return OPT_OK;
1097 #define parse_enum(opt, arg, map) \
1098         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1100 static enum option_code
1101 parse_string(char *opt, const char *arg, size_t optsize)
1103         int arglen = strlen(arg);
1105         switch (arg[0]) {
1106         case '\"':
1107         case '\'':
1108                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1109                         return OPT_ERR_UNMATCHED_QUOTATION;
1110                 arg += 1; arglen -= 2;
1111         default:
1112                 string_ncopy_do(opt, optsize, arg, arglen);
1113                 return OPT_OK;
1114         }
1117 static enum option_code
1118 parse_args(const char ***args, const char *argv[])
1120         if (*args == NULL && !argv_copy(args, argv))
1121                 return OPT_ERR_OUT_OF_MEMORY;
1122         return OPT_OK;
1125 /* Wants: name = value */
1126 static enum option_code
1127 option_set_command(int argc, const char *argv[])
1129         if (argc < 3)
1130                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1132         if (strcmp(argv[1], "="))
1133                 return OPT_ERR_NO_VALUE_ASSIGNED;
1135         if (!strcmp(argv[0], "blame-options"))
1136                 return parse_args(&opt_blame_argv, argv + 2);
1138         if (argc != 3)
1139                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1141         if (!strcmp(argv[0], "show-author"))
1142                 return parse_enum(&opt_author, argv[2], author_map);
1144         if (!strcmp(argv[0], "show-date"))
1145                 return parse_enum(&opt_date, argv[2], date_map);
1147         if (!strcmp(argv[0], "show-rev-graph"))
1148                 return parse_bool(&opt_rev_graph, argv[2]);
1150         if (!strcmp(argv[0], "show-refs"))
1151                 return parse_bool(&opt_show_refs, argv[2]);
1153         if (!strcmp(argv[0], "show-line-numbers"))
1154                 return parse_bool(&opt_line_number, argv[2]);
1156         if (!strcmp(argv[0], "line-graphics"))
1157                 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1159         if (!strcmp(argv[0], "line-number-interval"))
1160                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1162         if (!strcmp(argv[0], "author-width"))
1163                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1165         if (!strcmp(argv[0], "horizontal-scroll"))
1166                 return parse_step(&opt_hscroll, argv[2]);
1168         if (!strcmp(argv[0], "split-view-height"))
1169                 return parse_step(&opt_scale_split_view, argv[2]);
1171         if (!strcmp(argv[0], "tab-size"))
1172                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1174         if (!strcmp(argv[0], "commit-encoding"))
1175                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1177         if (!strcmp(argv[0], "status-untracked-dirs"))
1178                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1180         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1183 /* Wants: mode request key */
1184 static enum option_code
1185 option_bind_command(int argc, const char *argv[])
1187         enum request request;
1188         int keymap = -1;
1189         int key;
1191         if (argc < 3)
1192                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1194         if (!set_keymap(&keymap, argv[0]))
1195                 return OPT_ERR_UNKNOWN_KEY_MAP;
1197         key = get_key_value(argv[1]);
1198         if (key == ERR)
1199                 return OPT_ERR_UNKNOWN_KEY;
1201         request = get_request(argv[2]);
1202         if (request == REQ_UNKNOWN) {
1203                 static const struct enum_map obsolete[] = {
1204                         ENUM_MAP("cherry-pick",         REQ_NONE),
1205                         ENUM_MAP("screen-resize",       REQ_NONE),
1206                         ENUM_MAP("tree-parent",         REQ_PARENT),
1207                 };
1208                 int alias;
1210                 if (map_enum(&alias, obsolete, argv[2])) {
1211                         if (alias != REQ_NONE)
1212                                 add_keybinding(keymap, alias, key);
1213                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1214                 }
1215         }
1216         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1217                 request = add_run_request(keymap, key, argv + 2);
1218         if (request == REQ_UNKNOWN)
1219                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1221         add_keybinding(keymap, request, key);
1223         return OPT_OK;
1226 static enum option_code
1227 set_option(const char *opt, char *value)
1229         const char *argv[SIZEOF_ARG];
1230         int argc = 0;
1232         if (!argv_from_string(argv, &argc, value))
1233                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1235         if (!strcmp(opt, "color"))
1236                 return option_color_command(argc, argv);
1238         if (!strcmp(opt, "set"))
1239                 return option_set_command(argc, argv);
1241         if (!strcmp(opt, "bind"))
1242                 return option_bind_command(argc, argv);
1244         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1247 struct config_state {
1248         int lineno;
1249         bool errors;
1250 };
1252 static int
1253 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1255         struct config_state *config = data;
1256         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1258         config->lineno++;
1260         /* Check for comment markers, since read_properties() will
1261          * only ensure opt and value are split at first " \t". */
1262         optlen = strcspn(opt, "#");
1263         if (optlen == 0)
1264                 return OK;
1266         if (opt[optlen] == 0) {
1267                 /* Look for comment endings in the value. */
1268                 size_t len = strcspn(value, "#");
1270                 if (len < valuelen) {
1271                         valuelen = len;
1272                         value[valuelen] = 0;
1273                 }
1275                 status = set_option(opt, value);
1276         }
1278         if (status != OPT_OK) {
1279                 warn("Error on line %d, near '%.*s': %s",
1280                      config->lineno, (int) optlen, opt, option_errors[status]);
1281                 config->errors = TRUE;
1282         }
1284         /* Always keep going if errors are encountered. */
1285         return OK;
1288 static void
1289 load_option_file(const char *path)
1291         struct config_state config = { 0, FALSE };
1292         struct io io;
1294         /* It's OK that the file doesn't exist. */
1295         if (!io_open(&io, "%s", path))
1296                 return;
1298         if (io_load(&io, " \t", read_option, &config) == ERR ||
1299             config.errors == TRUE)
1300                 warn("Errors while loading %s.", path);
1303 static int
1304 load_options(void)
1306         const char *home = getenv("HOME");
1307         const char *tigrc_user = getenv("TIGRC_USER");
1308         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1309         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1310         char buf[SIZEOF_STR];
1312         if (!tigrc_system)
1313                 tigrc_system = SYSCONFDIR "/tigrc";
1314         load_option_file(tigrc_system);
1316         if (!tigrc_user) {
1317                 if (!home || !string_format(buf, "%s/.tigrc", home))
1318                         return ERR;
1319                 tigrc_user = buf;
1320         }
1321         load_option_file(tigrc_user);
1323         /* Add _after_ loading config files to avoid adding run requests
1324          * that conflict with keybindings. */
1325         add_builtin_run_requests();
1327         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1328                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1329                 int argc = 0;
1331                 if (!string_format(buf, "%s", tig_diff_opts) ||
1332                     !argv_from_string(diff_opts, &argc, buf))
1333                         die("TIG_DIFF_OPTS contains too many arguments");
1334                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1335                         die("Failed to format TIG_DIFF_OPTS arguments");
1336         }
1338         return OK;
1342 /*
1343  * The viewer
1344  */
1346 struct view;
1347 struct view_ops;
1349 /* The display array of active views and the index of the current view. */
1350 static struct view *display[2];
1351 static WINDOW *display_win[2];
1352 static WINDOW *display_title[2];
1353 static unsigned int current_view;
1355 #define foreach_displayed_view(view, i) \
1356         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1358 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1360 /* Current head and commit ID */
1361 static char ref_blob[SIZEOF_REF]        = "";
1362 static char ref_commit[SIZEOF_REF]      = "HEAD";
1363 static char ref_head[SIZEOF_REF]        = "HEAD";
1364 static char ref_branch[SIZEOF_REF]      = "";
1366 enum view_type {
1367         VIEW_MAIN,
1368         VIEW_DIFF,
1369         VIEW_LOG,
1370         VIEW_TREE,
1371         VIEW_BLOB,
1372         VIEW_BLAME,
1373         VIEW_BRANCH,
1374         VIEW_HELP,
1375         VIEW_PAGER,
1376         VIEW_STATUS,
1377         VIEW_STAGE,
1378 };
1380 struct view {
1381         enum view_type type;    /* View type */
1382         const char *name;       /* View name */
1383         const char *id;         /* Points to either of ref_{head,commit,blob} */
1385         struct view_ops *ops;   /* View operations */
1387         enum keymap keymap;     /* What keymap does this view have */
1388         bool git_dir;           /* Whether the view requires a git directory. */
1390         char ref[SIZEOF_REF];   /* Hovered commit reference */
1391         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1393         int height, width;      /* The width and height of the main window */
1394         WINDOW *win;            /* The main window */
1396         /* Navigation */
1397         unsigned long offset;   /* Offset of the window top */
1398         unsigned long yoffset;  /* Offset from the window side. */
1399         unsigned long lineno;   /* Current line number */
1400         unsigned long p_offset; /* Previous offset of the window top */
1401         unsigned long p_yoffset;/* Previous offset from the window side */
1402         unsigned long p_lineno; /* Previous current line number */
1403         bool p_restore;         /* Should the previous position be restored. */
1405         /* Searching */
1406         char grep[SIZEOF_STR];  /* Search string */
1407         regex_t *regex;         /* Pre-compiled regexp */
1409         /* If non-NULL, points to the view that opened this view. If this view
1410          * is closed tig will switch back to the parent view. */
1411         struct view *parent;
1412         struct view *prev;
1414         /* Buffering */
1415         size_t lines;           /* Total number of lines */
1416         struct line *line;      /* Line index */
1417         unsigned int digits;    /* Number of digits in the lines member. */
1419         /* Drawing */
1420         struct line *curline;   /* Line currently being drawn. */
1421         enum line_type curtype; /* Attribute currently used for drawing. */
1422         unsigned long col;      /* Column when drawing. */
1423         bool has_scrolled;      /* View was scrolled. */
1425         /* Loading */
1426         const char **argv;      /* Shell command arguments. */
1427         const char *dir;        /* Directory from which to execute. */
1428         struct io io;
1429         struct io *pipe;
1430         time_t start_time;
1431         time_t update_secs;
1432 };
1434 enum open_flags {
1435         OPEN_DEFAULT = 0,       /* Use default view switching. */
1436         OPEN_SPLIT = 1,         /* Split current view. */
1437         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1438         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
1439         OPEN_PREPARED = 32,     /* Open already prepared command. */
1440         OPEN_EXTRA = 64,        /* Open extra data from command. */
1441 };
1443 struct view_ops {
1444         /* What type of content being displayed. Used in the title bar. */
1445         const char *type;
1446         /* Open and reads in all view content. */
1447         bool (*open)(struct view *view, enum open_flags flags);
1448         /* Read one line; updates view->line. */
1449         bool (*read)(struct view *view, char *data);
1450         /* Draw one line; @lineno must be < view->height. */
1451         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1452         /* Depending on view handle a special requests. */
1453         enum request (*request)(struct view *view, enum request request, struct line *line);
1454         /* Search for regexp in a line. */
1455         bool (*grep)(struct view *view, struct line *line);
1456         /* Select line */
1457         void (*select)(struct view *view, struct line *line);
1458 };
1460 static struct view_ops blame_ops;
1461 static struct view_ops blob_ops;
1462 static struct view_ops diff_ops;
1463 static struct view_ops help_ops;
1464 static struct view_ops log_ops;
1465 static struct view_ops main_ops;
1466 static struct view_ops pager_ops;
1467 static struct view_ops stage_ops;
1468 static struct view_ops status_ops;
1469 static struct view_ops tree_ops;
1470 static struct view_ops branch_ops;
1472 #define VIEW_STR(type, name, ref, ops, map, git) \
1473         { type, name, ref, ops, map, git }
1475 #define VIEW_(id, name, ops, git, ref) \
1476         VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1478 static struct view views[] = {
1479         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1480         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1481         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1482         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1483         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1484         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1485         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1486         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1487         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1488         VIEW_(STATUS, "status", &status_ops, TRUE,  "status"),
1489         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1490 };
1492 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1494 #define foreach_view(view, i) \
1495         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1497 #define view_is_displayed(view) \
1498         (view == display[0] || view == display[1])
1500 static enum request
1501 view_request(struct view *view, enum request request)
1503         if (!view || !view->lines)
1504                 return request;
1505         return view->ops->request(view, request, &view->line[view->lineno]);
1509 /*
1510  * View drawing.
1511  */
1513 static inline void
1514 set_view_attr(struct view *view, enum line_type type)
1516         if (!view->curline->selected && view->curtype != type) {
1517                 (void) wattrset(view->win, get_line_attr(type));
1518                 wchgat(view->win, -1, 0, type, NULL);
1519                 view->curtype = type;
1520         }
1523 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1525 static bool
1526 draw_chars(struct view *view, enum line_type type, const char *string,
1527            int max_len, bool use_tilde)
1529         static char out_buffer[BUFSIZ * 2];
1530         int len = 0;
1531         int col = 0;
1532         int trimmed = FALSE;
1533         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1535         if (max_len <= 0)
1536                 return VIEW_MAX_LEN(view) <= 0;
1538         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1540         set_view_attr(view, type);
1541         if (len > 0) {
1542                 if (opt_iconv_out != ICONV_NONE) {
1543                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1544                         size_t inlen = len + 1;
1546                         char *outbuf = out_buffer;
1547                         size_t outlen = sizeof(out_buffer);
1549                         size_t ret;
1551                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1552                         if (ret != (size_t) -1) {
1553                                 string = out_buffer;
1554                                 len = sizeof(out_buffer) - outlen;
1555                         }
1556                 }
1558                 waddnstr(view->win, string, len);
1560                 if (trimmed && use_tilde) {
1561                         set_view_attr(view, LINE_DELIMITER);
1562                         waddch(view->win, '~');
1563                         col++;
1564                 }
1565         }
1567         view->col += col;
1568         return VIEW_MAX_LEN(view) <= 0;
1571 static bool
1572 draw_space(struct view *view, enum line_type type, int max, int spaces)
1574         static char space[] = "                    ";
1576         spaces = MIN(max, spaces);
1578         while (spaces > 0) {
1579                 int len = MIN(spaces, sizeof(space) - 1);
1581                 if (draw_chars(view, type, space, len, FALSE))
1582                         return TRUE;
1583                 spaces -= len;
1584         }
1586         return VIEW_MAX_LEN(view) <= 0;
1589 static bool
1590 draw_text(struct view *view, enum line_type type, const char *string)
1592         char text[SIZEOF_STR];
1594         do {
1595                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1597                 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1598                         return TRUE;
1599                 string += pos;
1600         } while (*string);
1602         return VIEW_MAX_LEN(view) <= 0;
1605 static bool
1606 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1608         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1609         int max = VIEW_MAX_LEN(view);
1610         int i;
1612         if (max < size)
1613                 size = max;
1615         set_view_attr(view, type);
1616         /* Using waddch() instead of waddnstr() ensures that
1617          * they'll be rendered correctly for the cursor line. */
1618         for (i = skip; i < size; i++)
1619                 waddch(view->win, graphic[i]);
1621         view->col += size;
1622         if (separator) {
1623                 if (size < max && skip <= size)
1624                         waddch(view->win, ' ');
1625                 view->col++;
1626         }
1628         return VIEW_MAX_LEN(view) <= 0;
1631 static bool
1632 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1634         int max = MIN(VIEW_MAX_LEN(view), len);
1635         int col = view->col;
1637         if (!text) 
1638                 return draw_space(view, type, max, max);
1640         return draw_chars(view, type, text, max - 1, trim)
1641             || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1644 static bool
1645 draw_date(struct view *view, struct time *time)
1647         const char *date = mkdate(time, opt_date);
1648         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1650         if (opt_date == DATE_NO)
1651                 return FALSE;
1653         return draw_field(view, LINE_DATE, date, cols, FALSE);
1656 static bool
1657 draw_author(struct view *view, const char *author)
1659         bool trim = author_trim(opt_author_cols);
1660         const char *text = mkauthor(author, opt_author_cols, opt_author);
1662         if (opt_author == AUTHOR_NO)
1663                 return FALSE;
1665         return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1668 static bool
1669 draw_mode(struct view *view, mode_t mode)
1671         const char *str = mkmode(mode);
1673         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1676 static bool
1677 draw_lineno(struct view *view, unsigned int lineno)
1679         char number[10];
1680         int digits3 = view->digits < 3 ? 3 : view->digits;
1681         int max = MIN(VIEW_MAX_LEN(view), digits3);
1682         char *text = NULL;
1683         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1685         lineno += view->offset + 1;
1686         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1687                 static char fmt[] = "%1ld";
1689                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1690                 if (string_format(number, fmt, lineno))
1691                         text = number;
1692         }
1693         if (text)
1694                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1695         else
1696                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1697         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1700 static bool
1701 draw_refs(struct view *view, struct ref_list *refs)
1703         size_t i;
1705         if (!opt_show_refs || !refs)
1706                 return FALSE;
1708         for (i = 0; i < refs->size; i++) {
1709                 struct ref *ref = refs->refs[i];
1710                 enum line_type type;
1712                 if (ref->head)
1713                         type = LINE_MAIN_HEAD;
1714                 else if (ref->ltag)
1715                         type = LINE_MAIN_LOCAL_TAG;
1716                 else if (ref->tag)
1717                         type = LINE_MAIN_TAG;
1718                 else if (ref->tracked)
1719                         type = LINE_MAIN_TRACKED;
1720                 else if (ref->remote)
1721                         type = LINE_MAIN_REMOTE;
1722                 else
1723                         type = LINE_MAIN_REF;
1725                 if (draw_text(view, type, "[") ||
1726                     draw_text(view, type, ref->name) ||
1727                     draw_text(view, type, "]"))
1728                         return TRUE;
1730                 if (draw_text(view, LINE_DEFAULT, " "))
1731                         return TRUE;
1732         }
1734         return FALSE;
1737 static bool
1738 draw_view_line(struct view *view, unsigned int lineno)
1740         struct line *line;
1741         bool selected = (view->offset + lineno == view->lineno);
1743         assert(view_is_displayed(view));
1745         if (view->offset + lineno >= view->lines)
1746                 return FALSE;
1748         line = &view->line[view->offset + lineno];
1750         wmove(view->win, lineno, 0);
1751         if (line->cleareol)
1752                 wclrtoeol(view->win);
1753         view->col = 0;
1754         view->curline = line;
1755         view->curtype = LINE_NONE;
1756         line->selected = FALSE;
1757         line->dirty = line->cleareol = 0;
1759         if (selected) {
1760                 set_view_attr(view, LINE_CURSOR);
1761                 line->selected = TRUE;
1762                 view->ops->select(view, line);
1763         }
1765         return view->ops->draw(view, line, lineno);
1768 static void
1769 redraw_view_dirty(struct view *view)
1771         bool dirty = FALSE;
1772         int lineno;
1774         for (lineno = 0; lineno < view->height; lineno++) {
1775                 if (view->offset + lineno >= view->lines)
1776                         break;
1777                 if (!view->line[view->offset + lineno].dirty)
1778                         continue;
1779                 dirty = TRUE;
1780                 if (!draw_view_line(view, lineno))
1781                         break;
1782         }
1784         if (!dirty)
1785                 return;
1786         wnoutrefresh(view->win);
1789 static void
1790 redraw_view_from(struct view *view, int lineno)
1792         assert(0 <= lineno && lineno < view->height);
1794         for (; lineno < view->height; lineno++) {
1795                 if (!draw_view_line(view, lineno))
1796                         break;
1797         }
1799         wnoutrefresh(view->win);
1802 static void
1803 redraw_view(struct view *view)
1805         werase(view->win);
1806         redraw_view_from(view, 0);
1810 static void
1811 update_view_title(struct view *view)
1813         char buf[SIZEOF_STR];
1814         char state[SIZEOF_STR];
1815         size_t bufpos = 0, statelen = 0;
1816         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1818         assert(view_is_displayed(view));
1820         if (view->type != VIEW_STATUS && view->lines) {
1821                 unsigned int view_lines = view->offset + view->height;
1822                 unsigned int lines = view->lines
1823                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1824                                    : 0;
1826                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1827                                    view->ops->type,
1828                                    view->lineno + 1,
1829                                    view->lines,
1830                                    lines);
1832         }
1834         if (view->pipe) {
1835                 time_t secs = time(NULL) - view->start_time;
1837                 /* Three git seconds are a long time ... */
1838                 if (secs > 2)
1839                         string_format_from(state, &statelen, " loading %lds", secs);
1840         }
1842         string_format_from(buf, &bufpos, "[%s]", view->name);
1843         if (*view->ref && bufpos < view->width) {
1844                 size_t refsize = strlen(view->ref);
1845                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1847                 if (minsize < view->width)
1848                         refsize = view->width - minsize + 7;
1849                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1850         }
1852         if (statelen && bufpos < view->width) {
1853                 string_format_from(buf, &bufpos, "%s", state);
1854         }
1856         if (view == display[current_view])
1857                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1858         else
1859                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1861         mvwaddnstr(window, 0, 0, buf, bufpos);
1862         wclrtoeol(window);
1863         wnoutrefresh(window);
1866 static int
1867 apply_step(double step, int value)
1869         if (step >= 1)
1870                 return (int) step;
1871         value *= step + 0.01;
1872         return value ? value : 1;
1875 static void
1876 resize_display(void)
1878         int offset, i;
1879         struct view *base = display[0];
1880         struct view *view = display[1] ? display[1] : display[0];
1882         /* Setup window dimensions */
1884         getmaxyx(stdscr, base->height, base->width);
1886         /* Make room for the status window. */
1887         base->height -= 1;
1889         if (view != base) {
1890                 /* Horizontal split. */
1891                 view->width   = base->width;
1892                 view->height  = apply_step(opt_scale_split_view, base->height);
1893                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1894                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1895                 base->height -= view->height;
1897                 /* Make room for the title bar. */
1898                 view->height -= 1;
1899         }
1901         /* Make room for the title bar. */
1902         base->height -= 1;
1904         offset = 0;
1906         foreach_displayed_view (view, i) {
1907                 if (!display_win[i]) {
1908                         display_win[i] = newwin(view->height, view->width, offset, 0);
1909                         if (!display_win[i])
1910                                 die("Failed to create %s view", view->name);
1912                         scrollok(display_win[i], FALSE);
1914                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1915                         if (!display_title[i])
1916                                 die("Failed to create title window");
1918                 } else {
1919                         wresize(display_win[i], view->height, view->width);
1920                         mvwin(display_win[i],   offset, 0);
1921                         mvwin(display_title[i], offset + view->height, 0);
1922                 }
1924                 view->win = display_win[i];
1926                 offset += view->height + 1;
1927         }
1930 static void
1931 redraw_display(bool clear)
1933         struct view *view;
1934         int i;
1936         foreach_displayed_view (view, i) {
1937                 if (clear)
1938                         wclear(view->win);
1939                 redraw_view(view);
1940                 update_view_title(view);
1941         }
1945 /*
1946  * Option management
1947  */
1949 #define TOGGLE_MENU \
1950         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1951         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1952         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1953         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1954         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1955         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1957 static void
1958 toggle_option(enum request request)
1960         const struct {
1961                 enum request request;
1962                 const struct enum_map *map;
1963                 size_t map_size;
1964         } data[] = {            
1965 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1966                 TOGGLE_MENU
1967 #undef  TOGGLE_
1968         };
1969         const struct menu_item menu[] = {
1970 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1971                 TOGGLE_MENU
1972 #undef  TOGGLE_
1973                 { 0 }
1974         };
1975         int i = 0;
1977         if (request == REQ_OPTIONS) {
1978                 if (!prompt_menu("Toggle option", menu, &i))
1979                         return;
1980         } else {
1981                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1982                         i++;
1983                 if (i >= ARRAY_SIZE(data))
1984                         die("Invalid request (%d)", request);
1985         }
1987         if (data[i].map != NULL) {
1988                 unsigned int *opt = menu[i].data;
1990                 *opt = (*opt + 1) % data[i].map_size;
1991                 redraw_display(FALSE);
1992                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1994         } else {
1995                 bool *option = menu[i].data;
1997                 *option = !*option;
1998                 redraw_display(FALSE);
1999                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2000         }
2003 static void
2004 maximize_view(struct view *view, bool redraw)
2006         memset(display, 0, sizeof(display));
2007         current_view = 0;
2008         display[current_view] = view;
2009         resize_display();
2010         if (redraw) {
2011                 redraw_display(FALSE);
2012                 report("");
2013         }
2017 /*
2018  * Navigation
2019  */
2021 static bool
2022 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2024         if (lineno >= view->lines)
2025                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2027         if (offset > lineno || offset + view->height <= lineno) {
2028                 unsigned long half = view->height / 2;
2030                 if (lineno > half)
2031                         offset = lineno - half;
2032                 else
2033                         offset = 0;
2034         }
2036         if (offset != view->offset || lineno != view->lineno) {
2037                 view->offset = offset;
2038                 view->lineno = lineno;
2039                 return TRUE;
2040         }
2042         return FALSE;
2045 /* Scrolling backend */
2046 static void
2047 do_scroll_view(struct view *view, int lines)
2049         bool redraw_current_line = FALSE;
2051         /* The rendering expects the new offset. */
2052         view->offset += lines;
2054         assert(0 <= view->offset && view->offset < view->lines);
2055         assert(lines);
2057         /* Move current line into the view. */
2058         if (view->lineno < view->offset) {
2059                 view->lineno = view->offset;
2060                 redraw_current_line = TRUE;
2061         } else if (view->lineno >= view->offset + view->height) {
2062                 view->lineno = view->offset + view->height - 1;
2063                 redraw_current_line = TRUE;
2064         }
2066         assert(view->offset <= view->lineno && view->lineno < view->lines);
2068         /* Redraw the whole screen if scrolling is pointless. */
2069         if (view->height < ABS(lines)) {
2070                 redraw_view(view);
2072         } else {
2073                 int line = lines > 0 ? view->height - lines : 0;
2074                 int end = line + ABS(lines);
2076                 scrollok(view->win, TRUE);
2077                 wscrl(view->win, lines);
2078                 scrollok(view->win, FALSE);
2080                 while (line < end && draw_view_line(view, line))
2081                         line++;
2083                 if (redraw_current_line)
2084                         draw_view_line(view, view->lineno - view->offset);
2085                 wnoutrefresh(view->win);
2086         }
2088         view->has_scrolled = TRUE;
2089         report("");
2092 /* Scroll frontend */
2093 static void
2094 scroll_view(struct view *view, enum request request)
2096         int lines = 1;
2098         assert(view_is_displayed(view));
2100         switch (request) {
2101         case REQ_SCROLL_FIRST_COL:
2102                 view->yoffset = 0;
2103                 redraw_view_from(view, 0);
2104                 report("");
2105                 return;
2106         case REQ_SCROLL_LEFT:
2107                 if (view->yoffset == 0) {
2108                         report("Cannot scroll beyond the first column");
2109                         return;
2110                 }
2111                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2112                         view->yoffset = 0;
2113                 else
2114                         view->yoffset -= apply_step(opt_hscroll, view->width);
2115                 redraw_view_from(view, 0);
2116                 report("");
2117                 return;
2118         case REQ_SCROLL_RIGHT:
2119                 view->yoffset += apply_step(opt_hscroll, view->width);
2120                 redraw_view(view);
2121                 report("");
2122                 return;
2123         case REQ_SCROLL_PAGE_DOWN:
2124                 lines = view->height;
2125         case REQ_SCROLL_LINE_DOWN:
2126                 if (view->offset + lines > view->lines)
2127                         lines = view->lines - view->offset;
2129                 if (lines == 0 || view->offset + view->height >= view->lines) {
2130                         report("Cannot scroll beyond the last line");
2131                         return;
2132                 }
2133                 break;
2135         case REQ_SCROLL_PAGE_UP:
2136                 lines = view->height;
2137         case REQ_SCROLL_LINE_UP:
2138                 if (lines > view->offset)
2139                         lines = view->offset;
2141                 if (lines == 0) {
2142                         report("Cannot scroll beyond the first line");
2143                         return;
2144                 }
2146                 lines = -lines;
2147                 break;
2149         default:
2150                 die("request %d not handled in switch", request);
2151         }
2153         do_scroll_view(view, lines);
2156 /* Cursor moving */
2157 static void
2158 move_view(struct view *view, enum request request)
2160         int scroll_steps = 0;
2161         int steps;
2163         switch (request) {
2164         case REQ_MOVE_FIRST_LINE:
2165                 steps = -view->lineno;
2166                 break;
2168         case REQ_MOVE_LAST_LINE:
2169                 steps = view->lines - view->lineno - 1;
2170                 break;
2172         case REQ_MOVE_PAGE_UP:
2173                 steps = view->height > view->lineno
2174                       ? -view->lineno : -view->height;
2175                 break;
2177         case REQ_MOVE_PAGE_DOWN:
2178                 steps = view->lineno + view->height >= view->lines
2179                       ? view->lines - view->lineno - 1 : view->height;
2180                 break;
2182         case REQ_MOVE_UP:
2183                 steps = -1;
2184                 break;
2186         case REQ_MOVE_DOWN:
2187                 steps = 1;
2188                 break;
2190         default:
2191                 die("request %d not handled in switch", request);
2192         }
2194         if (steps <= 0 && view->lineno == 0) {
2195                 report("Cannot move beyond the first line");
2196                 return;
2198         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2199                 report("Cannot move beyond the last line");
2200                 return;
2201         }
2203         /* Move the current line */
2204         view->lineno += steps;
2205         assert(0 <= view->lineno && view->lineno < view->lines);
2207         /* Check whether the view needs to be scrolled */
2208         if (view->lineno < view->offset ||
2209             view->lineno >= view->offset + view->height) {
2210                 scroll_steps = steps;
2211                 if (steps < 0 && -steps > view->offset) {
2212                         scroll_steps = -view->offset;
2214                 } else if (steps > 0) {
2215                         if (view->lineno == view->lines - 1 &&
2216                             view->lines > view->height) {
2217                                 scroll_steps = view->lines - view->offset - 1;
2218                                 if (scroll_steps >= view->height)
2219                                         scroll_steps -= view->height - 1;
2220                         }
2221                 }
2222         }
2224         if (!view_is_displayed(view)) {
2225                 view->offset += scroll_steps;
2226                 assert(0 <= view->offset && view->offset < view->lines);
2227                 view->ops->select(view, &view->line[view->lineno]);
2228                 return;
2229         }
2231         /* Repaint the old "current" line if we be scrolling */
2232         if (ABS(steps) < view->height)
2233                 draw_view_line(view, view->lineno - steps - view->offset);
2235         if (scroll_steps) {
2236                 do_scroll_view(view, scroll_steps);
2237                 return;
2238         }
2240         /* Draw the current line */
2241         draw_view_line(view, view->lineno - view->offset);
2243         wnoutrefresh(view->win);
2244         report("");
2248 /*
2249  * Searching
2250  */
2252 static void search_view(struct view *view, enum request request);
2254 static bool
2255 grep_text(struct view *view, const char *text[])
2257         regmatch_t pmatch;
2258         size_t i;
2260         for (i = 0; text[i]; i++)
2261                 if (*text[i] &&
2262                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2263                         return TRUE;
2264         return FALSE;
2267 static void
2268 select_view_line(struct view *view, unsigned long lineno)
2270         unsigned long old_lineno = view->lineno;
2271         unsigned long old_offset = view->offset;
2273         if (goto_view_line(view, view->offset, lineno)) {
2274                 if (view_is_displayed(view)) {
2275                         if (old_offset != view->offset) {
2276                                 redraw_view(view);
2277                         } else {
2278                                 draw_view_line(view, old_lineno - view->offset);
2279                                 draw_view_line(view, view->lineno - view->offset);
2280                                 wnoutrefresh(view->win);
2281                         }
2282                 } else {
2283                         view->ops->select(view, &view->line[view->lineno]);
2284                 }
2285         }
2288 static void
2289 find_next(struct view *view, enum request request)
2291         unsigned long lineno = view->lineno;
2292         int direction;
2294         if (!*view->grep) {
2295                 if (!*opt_search)
2296                         report("No previous search");
2297                 else
2298                         search_view(view, request);
2299                 return;
2300         }
2302         switch (request) {
2303         case REQ_SEARCH:
2304         case REQ_FIND_NEXT:
2305                 direction = 1;
2306                 break;
2308         case REQ_SEARCH_BACK:
2309         case REQ_FIND_PREV:
2310                 direction = -1;
2311                 break;
2313         default:
2314                 return;
2315         }
2317         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2318                 lineno += direction;
2320         /* Note, lineno is unsigned long so will wrap around in which case it
2321          * will become bigger than view->lines. */
2322         for (; lineno < view->lines; lineno += direction) {
2323                 if (view->ops->grep(view, &view->line[lineno])) {
2324                         select_view_line(view, lineno);
2325                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2326                         return;
2327                 }
2328         }
2330         report("No match found for '%s'", view->grep);
2333 static void
2334 search_view(struct view *view, enum request request)
2336         int regex_err;
2338         if (view->regex) {
2339                 regfree(view->regex);
2340                 *view->grep = 0;
2341         } else {
2342                 view->regex = calloc(1, sizeof(*view->regex));
2343                 if (!view->regex)
2344                         return;
2345         }
2347         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2348         if (regex_err != 0) {
2349                 char buf[SIZEOF_STR] = "unknown error";
2351                 regerror(regex_err, view->regex, buf, sizeof(buf));
2352                 report("Search failed: %s", buf);
2353                 return;
2354         }
2356         string_copy(view->grep, opt_search);
2358         find_next(view, request);
2361 /*
2362  * Incremental updating
2363  */
2365 static void
2366 reset_view(struct view *view)
2368         int i;
2370         for (i = 0; i < view->lines; i++)
2371                 free(view->line[i].data);
2372         free(view->line);
2374         view->p_offset = view->offset;
2375         view->p_yoffset = view->yoffset;
2376         view->p_lineno = view->lineno;
2378         view->line = NULL;
2379         view->offset = 0;
2380         view->yoffset = 0;
2381         view->lines  = 0;
2382         view->lineno = 0;
2383         view->vid[0] = 0;
2384         view->update_secs = 0;
2387 static const char *
2388 format_arg(const char *name)
2390         static struct {
2391                 const char *name;
2392                 size_t namelen;
2393                 const char *value;
2394                 const char *value_if_empty;
2395         } vars[] = {
2396 #define FORMAT_VAR(name, value, value_if_empty) \
2397         { name, STRING_SIZE(name), value, value_if_empty }
2398                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2399                 FORMAT_VAR("%(file)",           opt_file,       ""),
2400                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2401                 FORMAT_VAR("%(head)",           ref_head,       ""),
2402                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2403                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2404                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2405         };
2406         int i;
2408         for (i = 0; i < ARRAY_SIZE(vars); i++)
2409                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2410                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2412         report("Unknown replacement: `%s`", name);
2413         return NULL;
2416 static bool
2417 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2419         char buf[SIZEOF_STR];
2420         int argc;
2422         argv_free(*dst_argv);
2424         for (argc = 0; src_argv[argc]; argc++) {
2425                 const char *arg = src_argv[argc];
2426                 size_t bufpos = 0;
2428                 if (!strcmp(arg, "%(fileargs)")) {
2429                         if (!argv_append_array(dst_argv, opt_file_argv))
2430                                 break;
2431                         continue;
2433                 } else if (!strcmp(arg, "%(diffargs)")) {
2434                         if (!argv_append_array(dst_argv, opt_diff_argv))
2435                                 break;
2436                         continue;
2438                 } else if (!strcmp(arg, "%(blameargs)")) {
2439                         if (!argv_append_array(dst_argv, opt_blame_argv))
2440                                 break;
2441                         continue;
2443                 } else if (!strcmp(arg, "%(revargs)") ||
2444                            (first && !strcmp(arg, "%(commit)"))) {
2445                         if (!argv_append_array(dst_argv, opt_rev_argv))
2446                                 break;
2447                         continue;
2448                 }
2450                 while (arg) {
2451                         char *next = strstr(arg, "%(");
2452                         int len = next - arg;
2453                         const char *value;
2455                         if (!next) {
2456                                 len = strlen(arg);
2457                                 value = "";
2459                         } else {
2460                                 value = format_arg(next);
2462                                 if (!value) {
2463                                         return FALSE;
2464                                 }
2465                         }
2467                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2468                                 return FALSE;
2470                         arg = next ? strchr(next, ')') + 1 : NULL;
2471                 }
2473                 if (!argv_append(dst_argv, buf))
2474                         break;
2475         }
2477         return src_argv[argc] == NULL;
2480 static bool
2481 restore_view_position(struct view *view)
2483         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2484                 return FALSE;
2486         /* Changing the view position cancels the restoring. */
2487         /* FIXME: Changing back to the first line is not detected. */
2488         if (view->offset != 0 || view->lineno != 0) {
2489                 view->p_restore = FALSE;
2490                 return FALSE;
2491         }
2493         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2494             view_is_displayed(view))
2495                 werase(view->win);
2497         view->yoffset = view->p_yoffset;
2498         view->p_restore = FALSE;
2500         return TRUE;
2503 static void
2504 end_update(struct view *view, bool force)
2506         if (!view->pipe)
2507                 return;
2508         while (!view->ops->read(view, NULL))
2509                 if (!force)
2510                         return;
2511         if (force)
2512                 io_kill(view->pipe);
2513         io_done(view->pipe);
2514         view->pipe = NULL;
2517 static void
2518 setup_update(struct view *view, const char *vid)
2520         reset_view(view);
2521         string_copy_rev(view->vid, vid);
2522         view->pipe = &view->io;
2523         view->start_time = time(NULL);
2526 static bool
2527 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2529         bool extra = !!(flags & (OPEN_EXTRA));
2530         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2531         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2533         if (!reload && !strcmp(view->vid, view->id))
2534                 return TRUE;
2536         if (view->pipe) {
2537                 if (extra)
2538                         io_done(view->pipe);
2539                 else
2540                         end_update(view, TRUE);
2541         }
2543         if (!refresh) {
2544                 view->dir = dir;
2545                 if (!format_argv(&view->argv, argv, !view->prev))
2546                         return FALSE;
2548                 /* Put the current ref_* value to the view title ref
2549                  * member. This is needed by the blob view. Most other
2550                  * views sets it automatically after loading because the
2551                  * first line is a commit line. */
2552                 string_copy_rev(view->ref, view->id);
2553         }
2555         if (view->argv && view->argv[0] &&
2556             !io_run(&view->io, IO_RD, view->dir, view->argv))
2557                 return FALSE;
2559         if (!extra)
2560                 setup_update(view, view->id);
2562         return TRUE;
2565 static bool
2566 view_open(struct view *view, enum open_flags flags)
2568         return begin_update(view, NULL, NULL, flags);
2571 static bool
2572 update_view(struct view *view)
2574         char out_buffer[BUFSIZ * 2];
2575         char *line;
2576         /* Clear the view and redraw everything since the tree sorting
2577          * might have rearranged things. */
2578         bool redraw = view->lines == 0;
2579         bool can_read = TRUE;
2581         if (!view->pipe)
2582                 return TRUE;
2584         if (!io_can_read(view->pipe, FALSE)) {
2585                 if (view->lines == 0 && view_is_displayed(view)) {
2586                         time_t secs = time(NULL) - view->start_time;
2588                         if (secs > 1 && secs > view->update_secs) {
2589                                 if (view->update_secs == 0)
2590                                         redraw_view(view);
2591                                 update_view_title(view);
2592                                 view->update_secs = secs;
2593                         }
2594                 }
2595                 return TRUE;
2596         }
2598         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2599                 if (opt_iconv_in != ICONV_NONE) {
2600                         ICONV_CONST char *inbuf = line;
2601                         size_t inlen = strlen(line) + 1;
2603                         char *outbuf = out_buffer;
2604                         size_t outlen = sizeof(out_buffer);
2606                         size_t ret;
2608                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2609                         if (ret != (size_t) -1)
2610                                 line = out_buffer;
2611                 }
2613                 if (!view->ops->read(view, line)) {
2614                         report("Allocation failure");
2615                         end_update(view, TRUE);
2616                         return FALSE;
2617                 }
2618         }
2620         {
2621                 unsigned long lines = view->lines;
2622                 int digits;
2624                 for (digits = 0; lines; digits++)
2625                         lines /= 10;
2627                 /* Keep the displayed view in sync with line number scaling. */
2628                 if (digits != view->digits) {
2629                         view->digits = digits;
2630                         if (opt_line_number || view->type == VIEW_BLAME)
2631                                 redraw = TRUE;
2632                 }
2633         }
2635         if (io_error(view->pipe)) {
2636                 report("Failed to read: %s", io_strerror(view->pipe));
2637                 end_update(view, TRUE);
2639         } else if (io_eof(view->pipe)) {
2640                 if (view_is_displayed(view))
2641                         report("");
2642                 end_update(view, FALSE);
2643         }
2645         if (restore_view_position(view))
2646                 redraw = TRUE;
2648         if (!view_is_displayed(view))
2649                 return TRUE;
2651         if (redraw)
2652                 redraw_view_from(view, 0);
2653         else
2654                 redraw_view_dirty(view);
2656         /* Update the title _after_ the redraw so that if the redraw picks up a
2657          * commit reference in view->ref it'll be available here. */
2658         update_view_title(view);
2659         return TRUE;
2662 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2664 static struct line *
2665 add_line_data(struct view *view, void *data, enum line_type type)
2667         struct line *line;
2669         if (!realloc_lines(&view->line, view->lines, 1))
2670                 return NULL;
2672         line = &view->line[view->lines++];
2673         memset(line, 0, sizeof(*line));
2674         line->type = type;
2675         line->data = data;
2676         line->dirty = 1;
2678         return line;
2681 static struct line *
2682 add_line_text(struct view *view, const char *text, enum line_type type)
2684         char *data = text ? strdup(text) : NULL;
2686         return data ? add_line_data(view, data, type) : NULL;
2689 static struct line *
2690 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2692         char buf[SIZEOF_STR];
2693         va_list args;
2695         va_start(args, fmt);
2696         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2697                 buf[0] = 0;
2698         va_end(args);
2700         return buf[0] ? add_line_text(view, buf, type) : NULL;
2703 /*
2704  * View opening
2705  */
2707 static void
2708 load_view(struct view *view, enum open_flags flags)
2710         if (view->pipe)
2711                 end_update(view, TRUE);
2712         if (!view->ops->open(view, flags)) {
2713                 report("Failed to load %s view", view->name);
2714                 return;
2715         }
2716         restore_view_position(view);
2718         if (view->pipe && view->lines == 0) {
2719                 /* Clear the old view and let the incremental updating refill
2720                  * the screen. */
2721                 werase(view->win);
2722                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2723                 report("");
2724         } else if (view_is_displayed(view)) {
2725                 redraw_view(view);
2726                 report("");
2727         }
2730 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2731 #define reload_view(view) load_view(view, OPEN_RELOAD)
2733 static void
2734 split_view(struct view *prev, struct view *view)
2736         display[1] = view;
2737         current_view = 1;
2738         view->parent = prev;
2739         resize_display();
2741         if (prev->lineno - prev->offset >= prev->height) {
2742                 /* Take the title line into account. */
2743                 int lines = prev->lineno - prev->offset - prev->height + 1;
2745                 /* Scroll the view that was split if the current line is
2746                  * outside the new limited view. */
2747                 do_scroll_view(prev, lines);
2748         }
2750         if (view != prev && view_is_displayed(prev)) {
2751                 /* "Blur" the previous view. */
2752                 update_view_title(prev);
2753         }
2756 static void
2757 open_view(struct view *prev, enum request request, enum open_flags flags)
2759         bool split = !!(flags & OPEN_SPLIT);
2760         bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2761         struct view *view = VIEW(request);
2762         int nviews = displayed_views();
2764         assert(flags ^ OPEN_REFRESH);
2766         if (view == prev && nviews == 1 && !reload) {
2767                 report("Already in %s view", view->name);
2768                 return;
2769         }
2771         if (view->git_dir && !opt_git_dir[0]) {
2772                 report("The %s view is disabled in pager view", view->name);
2773                 return;
2774         }
2776         if (split) {
2777                 split_view(prev, view);
2778         } else {
2779                 maximize_view(view, FALSE);
2780         }
2782         /* No prev signals that this is the first loaded view. */
2783         if (prev && view != prev) {
2784                 view->prev = prev;
2785         }
2787         load_view(view, flags);
2790 static void
2791 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2793         enum request request = view - views + REQ_OFFSET + 1;
2795         if (view->pipe)
2796                 end_update(view, TRUE);
2797         view->dir = dir;
2798         
2799         if (!argv_copy(&view->argv, argv)) {
2800                 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2801         } else {
2802                 open_view(prev, request, flags | OPEN_PREPARED);
2803         }
2806 static void
2807 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2809         const char *file_argv[] = { opt_cdup, file , NULL };
2811         open_argv(prev, view, file_argv, opt_cdup, flags); 
2814 static void
2815 open_external_viewer(const char *argv[], const char *dir)
2817         def_prog_mode();           /* save current tty modes */
2818         endwin();                  /* restore original tty modes */
2819         io_run_fg(argv, dir);
2820         fprintf(stderr, "Press Enter to continue");
2821         getc(opt_tty);
2822         reset_prog_mode();
2823         redraw_display(TRUE);
2826 static void
2827 open_mergetool(const char *file)
2829         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2831         open_external_viewer(mergetool_argv, opt_cdup);
2834 static void
2835 open_editor(const char *file)
2837         const char *editor_argv[] = { "vi", file, NULL };
2838         const char *editor;
2840         editor = getenv("GIT_EDITOR");
2841         if (!editor && *opt_editor)
2842                 editor = opt_editor;
2843         if (!editor)
2844                 editor = getenv("VISUAL");
2845         if (!editor)
2846                 editor = getenv("EDITOR");
2847         if (!editor)
2848                 editor = "vi";
2850         editor_argv[0] = editor;
2851         open_external_viewer(editor_argv, opt_cdup);
2854 static void
2855 open_run_request(enum request request)
2857         struct run_request *req = get_run_request(request);
2858         const char **argv = NULL;
2860         if (!req) {
2861                 report("Unknown run request");
2862                 return;
2863         }
2865         if (format_argv(&argv, req->argv, FALSE))
2866                 open_external_viewer(argv, NULL);
2867         if (argv)
2868                 argv_free(argv);
2869         free(argv);
2872 /*
2873  * User request switch noodle
2874  */
2876 static int
2877 view_driver(struct view *view, enum request request)
2879         int i;
2881         if (request == REQ_NONE)
2882                 return TRUE;
2884         if (request > REQ_NONE) {
2885                 open_run_request(request);
2886                 view_request(view, REQ_REFRESH);
2887                 return TRUE;
2888         }
2890         request = view_request(view, request);
2891         if (request == REQ_NONE)
2892                 return TRUE;
2894         switch (request) {
2895         case REQ_MOVE_UP:
2896         case REQ_MOVE_DOWN:
2897         case REQ_MOVE_PAGE_UP:
2898         case REQ_MOVE_PAGE_DOWN:
2899         case REQ_MOVE_FIRST_LINE:
2900         case REQ_MOVE_LAST_LINE:
2901                 move_view(view, request);
2902                 break;
2904         case REQ_SCROLL_FIRST_COL:
2905         case REQ_SCROLL_LEFT:
2906         case REQ_SCROLL_RIGHT:
2907         case REQ_SCROLL_LINE_DOWN:
2908         case REQ_SCROLL_LINE_UP:
2909         case REQ_SCROLL_PAGE_DOWN:
2910         case REQ_SCROLL_PAGE_UP:
2911                 scroll_view(view, request);
2912                 break;
2914         case REQ_VIEW_BLAME:
2915                 if (!opt_file[0]) {
2916                         report("No file chosen, press %s to open tree view",
2917                                get_key(view->keymap, REQ_VIEW_TREE));
2918                         break;
2919                 }
2920                 open_view(view, request, OPEN_DEFAULT);
2921                 break;
2923         case REQ_VIEW_BLOB:
2924                 if (!ref_blob[0]) {
2925                         report("No file chosen, press %s to open tree view",
2926                                get_key(view->keymap, REQ_VIEW_TREE));
2927                         break;
2928                 }
2929                 open_view(view, request, OPEN_DEFAULT);
2930                 break;
2932         case REQ_VIEW_PAGER:
2933                 if (view == NULL) {
2934                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2935                                 die("Failed to open stdin");
2936                         open_view(view, request, OPEN_PREPARED);
2937                         break;
2938                 }
2940                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2941                         report("No pager content, press %s to run command from prompt",
2942                                get_key(view->keymap, REQ_PROMPT));
2943                         break;
2944                 }
2945                 open_view(view, request, OPEN_DEFAULT);
2946                 break;
2948         case REQ_VIEW_STAGE:
2949                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2950                         report("No stage content, press %s to open the status view and choose file",
2951                                get_key(view->keymap, REQ_VIEW_STATUS));
2952                         break;
2953                 }
2954                 open_view(view, request, OPEN_DEFAULT);
2955                 break;
2957         case REQ_VIEW_STATUS:
2958                 if (opt_is_inside_work_tree == FALSE) {
2959                         report("The status view requires a working tree");
2960                         break;
2961                 }
2962                 open_view(view, request, OPEN_DEFAULT);
2963                 break;
2965         case REQ_VIEW_MAIN:
2966         case REQ_VIEW_DIFF:
2967         case REQ_VIEW_LOG:
2968         case REQ_VIEW_TREE:
2969         case REQ_VIEW_HELP:
2970         case REQ_VIEW_BRANCH:
2971                 open_view(view, request, OPEN_DEFAULT);
2972                 break;
2974         case REQ_NEXT:
2975         case REQ_PREVIOUS:
2976                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2978                 if (view->parent) {
2979                         int line;
2981                         view = view->parent;
2982                         line = view->lineno;
2983                         move_view(view, request);
2984                         if (view_is_displayed(view))
2985                                 update_view_title(view);
2986                         if (line != view->lineno)
2987                                 view_request(view, REQ_ENTER);
2988                 } else {
2989                         move_view(view, request);
2990                 }
2991                 break;
2993         case REQ_VIEW_NEXT:
2994         {
2995                 int nviews = displayed_views();
2996                 int next_view = (current_view + 1) % nviews;
2998                 if (next_view == current_view) {
2999                         report("Only one view is displayed");
3000                         break;
3001                 }
3003                 current_view = next_view;
3004                 /* Blur out the title of the previous view. */
3005                 update_view_title(view);
3006                 report("");
3007                 break;
3008         }
3009         case REQ_REFRESH:
3010                 report("Refreshing is not yet supported for the %s view", view->name);
3011                 break;
3013         case REQ_MAXIMIZE:
3014                 if (displayed_views() == 2)
3015                         maximize_view(view, TRUE);
3016                 break;
3018         case REQ_OPTIONS:
3019         case REQ_TOGGLE_LINENO:
3020         case REQ_TOGGLE_DATE:
3021         case REQ_TOGGLE_AUTHOR:
3022         case REQ_TOGGLE_GRAPHIC:
3023         case REQ_TOGGLE_REV_GRAPH:
3024         case REQ_TOGGLE_REFS:
3025                 toggle_option(request);
3026                 break;
3028         case REQ_TOGGLE_SORT_FIELD:
3029         case REQ_TOGGLE_SORT_ORDER:
3030                 report("Sorting is not yet supported for the %s view", view->name);
3031                 break;
3033         case REQ_SEARCH:
3034         case REQ_SEARCH_BACK:
3035                 search_view(view, request);
3036                 break;
3038         case REQ_FIND_NEXT:
3039         case REQ_FIND_PREV:
3040                 find_next(view, request);
3041                 break;
3043         case REQ_STOP_LOADING:
3044                 foreach_view(view, i) {
3045                         if (view->pipe)
3046                                 report("Stopped loading the %s view", view->name),
3047                         end_update(view, TRUE);
3048                 }
3049                 break;
3051         case REQ_SHOW_VERSION:
3052                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3053                 return TRUE;
3055         case REQ_SCREEN_REDRAW:
3056                 redraw_display(TRUE);
3057                 break;
3059         case REQ_EDIT:
3060                 report("Nothing to edit");
3061                 break;
3063         case REQ_ENTER:
3064                 report("Nothing to enter");
3065                 break;
3067         case REQ_VIEW_CLOSE:
3068                 /* XXX: Mark closed views by letting view->prev point to the
3069                  * view itself. Parents to closed view should never be
3070                  * followed. */
3071                 if (view->prev && view->prev != view) {
3072                         maximize_view(view->prev, TRUE);
3073                         view->prev = view;
3074                         break;
3075                 }
3076                 /* Fall-through */
3077         case REQ_QUIT:
3078                 return FALSE;
3080         default:
3081                 report("Unknown key, press %s for help",
3082                        get_key(view->keymap, REQ_VIEW_HELP));
3083                 return TRUE;
3084         }
3086         return TRUE;
3090 /*
3091  * View backend utilities
3092  */
3094 enum sort_field {
3095         ORDERBY_NAME,
3096         ORDERBY_DATE,
3097         ORDERBY_AUTHOR,
3098 };
3100 struct sort_state {
3101         const enum sort_field *fields;
3102         size_t size, current;
3103         bool reverse;
3104 };
3106 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3107 #define get_sort_field(state) ((state).fields[(state).current])
3108 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3110 static void
3111 sort_view(struct view *view, enum request request, struct sort_state *state,
3112           int (*compare)(const void *, const void *))
3114         switch (request) {
3115         case REQ_TOGGLE_SORT_FIELD:
3116                 state->current = (state->current + 1) % state->size;
3117                 break;
3119         case REQ_TOGGLE_SORT_ORDER:
3120                 state->reverse = !state->reverse;
3121                 break;
3122         default:
3123                 die("Not a sort request");
3124         }
3126         qsort(view->line, view->lines, sizeof(*view->line), compare);
3127         redraw_view(view);
3130 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3132 /* Small author cache to reduce memory consumption. It uses binary
3133  * search to lookup or find place to position new entries. No entries
3134  * are ever freed. */
3135 static const char *
3136 get_author(const char *name)
3138         static const char **authors;
3139         static size_t authors_size;
3140         int from = 0, to = authors_size - 1;
3142         while (from <= to) {
3143                 size_t pos = (to + from) / 2;
3144                 int cmp = strcmp(name, authors[pos]);
3146                 if (!cmp)
3147                         return authors[pos];
3149                 if (cmp < 0)
3150                         to = pos - 1;
3151                 else
3152                         from = pos + 1;
3153         }
3155         if (!realloc_authors(&authors, authors_size, 1))
3156                 return NULL;
3157         name = strdup(name);
3158         if (!name)
3159                 return NULL;
3161         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3162         authors[from] = name;
3163         authors_size++;
3165         return name;
3168 static void
3169 parse_timesec(struct time *time, const char *sec)
3171         time->sec = (time_t) atol(sec);
3174 static void
3175 parse_timezone(struct time *time, const char *zone)
3177         long tz;
3179         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3180         tz += ('0' - zone[2]) * 60 * 60;
3181         tz += ('0' - zone[3]) * 60 * 10;
3182         tz += ('0' - zone[4]) * 60;
3184         if (zone[0] == '-')
3185                 tz = -tz;
3187         time->tz = tz;
3188         time->sec -= tz;
3191 /* Parse author lines where the name may be empty:
3192  *      author  <email@address.tld> 1138474660 +0100
3193  */
3194 static void
3195 parse_author_line(char *ident, const char **author, struct time *time)
3197         char *nameend = strchr(ident, '<');
3198         char *emailend = strchr(ident, '>');
3200         if (nameend && emailend)
3201                 *nameend = *emailend = 0;
3202         ident = chomp_string(ident);
3203         if (!*ident) {
3204                 if (nameend)
3205                         ident = chomp_string(nameend + 1);
3206                 if (!*ident)
3207                         ident = "Unknown";
3208         }
3210         *author = get_author(ident);
3212         /* Parse epoch and timezone */
3213         if (emailend && emailend[1] == ' ') {
3214                 char *secs = emailend + 2;
3215                 char *zone = strchr(secs, ' ');
3217                 parse_timesec(time, secs);
3219                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3220                         parse_timezone(time, zone + 1);
3221         }
3224 /*
3225  * Pager backend
3226  */
3228 static bool
3229 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3231         if (opt_line_number && draw_lineno(view, lineno))
3232                 return TRUE;
3234         draw_text(view, line->type, line->data);
3235         return TRUE;
3238 static bool
3239 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3241         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3242         char ref[SIZEOF_STR];
3244         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3245                 return TRUE;
3247         /* This is the only fatal call, since it can "corrupt" the buffer. */
3248         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3249                 return FALSE;
3251         return TRUE;
3254 static void
3255 add_pager_refs(struct view *view, struct line *line)
3257         char buf[SIZEOF_STR];
3258         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3259         struct ref_list *list;
3260         size_t bufpos = 0, i;
3261         const char *sep = "Refs: ";
3262         bool is_tag = FALSE;
3264         assert(line->type == LINE_COMMIT);
3266         list = get_ref_list(commit_id);
3267         if (!list) {
3268                 if (view->type == VIEW_DIFF)
3269                         goto try_add_describe_ref;
3270                 return;
3271         }
3273         for (i = 0; i < list->size; i++) {
3274                 struct ref *ref = list->refs[i];
3275                 const char *fmt = ref->tag    ? "%s[%s]" :
3276                                   ref->remote ? "%s<%s>" : "%s%s";
3278                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3279                         return;
3280                 sep = ", ";
3281                 if (ref->tag)
3282                         is_tag = TRUE;
3283         }
3285         if (!is_tag && view->type == VIEW_DIFF) {
3286 try_add_describe_ref:
3287                 /* Add <tag>-g<commit_id> "fake" reference. */
3288                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3289                         return;
3290         }
3292         if (bufpos == 0)
3293                 return;
3295         add_line_text(view, buf, LINE_PP_REFS);
3298 static bool
3299 pager_read(struct view *view, char *data)
3301         struct line *line;
3303         if (!data)
3304                 return TRUE;
3306         line = add_line_text(view, data, get_line_type(data));
3307         if (!line)
3308                 return FALSE;
3310         if (line->type == LINE_COMMIT &&
3311             (view->type == VIEW_DIFF ||
3312              view->type == VIEW_LOG))
3313                 add_pager_refs(view, line);
3315         return TRUE;
3318 static enum request
3319 pager_request(struct view *view, enum request request, struct line *line)
3321         int split = 0;
3323         if (request != REQ_ENTER)
3324                 return request;
3326         if (line->type == LINE_COMMIT &&
3327            (view->type == VIEW_LOG ||
3328             view->type == VIEW_PAGER)) {
3329                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3330                 split = 1;
3331         }
3333         /* Always scroll the view even if it was split. That way
3334          * you can use Enter to scroll through the log view and
3335          * split open each commit diff. */
3336         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3338         /* FIXME: A minor workaround. Scrolling the view will call report("")
3339          * but if we are scrolling a non-current view this won't properly
3340          * update the view title. */
3341         if (split)
3342                 update_view_title(view);
3344         return REQ_NONE;
3347 static bool
3348 pager_grep(struct view *view, struct line *line)
3350         const char *text[] = { line->data, NULL };
3352         return grep_text(view, text);
3355 static void
3356 pager_select(struct view *view, struct line *line)
3358         if (line->type == LINE_COMMIT) {
3359                 char *text = (char *)line->data + STRING_SIZE("commit ");
3361                 if (view->type != VIEW_PAGER)
3362                         string_copy_rev(view->ref, text);
3363                 string_copy_rev(ref_commit, text);
3364         }
3367 static struct view_ops pager_ops = {
3368         "line",
3369         view_open,
3370         pager_read,
3371         pager_draw,
3372         pager_request,
3373         pager_grep,
3374         pager_select,
3375 };
3377 static bool
3378 log_open(struct view *view, enum open_flags flags)
3380         static const char *log_argv[] = {
3381                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3382         };
3384         return begin_update(view, NULL, log_argv, flags);
3387 static enum request
3388 log_request(struct view *view, enum request request, struct line *line)
3390         switch (request) {
3391         case REQ_REFRESH:
3392                 load_refs();
3393                 refresh_view(view);
3394                 return REQ_NONE;
3395         default:
3396                 return pager_request(view, request, line);
3397         }
3400 static struct view_ops log_ops = {
3401         "line",
3402         log_open,
3403         pager_read,
3404         pager_draw,
3405         log_request,
3406         pager_grep,
3407         pager_select,
3408 };
3410 static bool
3411 diff_open(struct view *view, enum open_flags flags)
3413         static const char *diff_argv[] = {
3414                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3415                         "--patch-with-stat", "--find-copies-harder", "-C",
3416                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3417         };
3419         return begin_update(view, NULL, diff_argv, flags);
3422 static bool
3423 diff_read(struct view *view, char *data)
3425         if (!data) {
3426                 /* Fall back to retry if no diff will be shown. */
3427                 if (view->lines == 0 && opt_file_argv) {
3428                         int pos = argv_size(view->argv)
3429                                 - argv_size(opt_file_argv) - 1;
3431                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3432                                 for (; view->argv[pos]; pos++) {
3433                                         free((void *) view->argv[pos]);
3434                                         view->argv[pos] = NULL;
3435                                 }
3437                                 if (view->pipe)
3438                                         io_done(view->pipe);
3439                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3440                                         return FALSE;
3441                         }
3442                 }
3443                 return TRUE;
3444         }
3446         return pager_read(view, data);
3449 static struct view_ops diff_ops = {
3450         "line",
3451         diff_open,
3452         diff_read,
3453         pager_draw,
3454         pager_request,
3455         pager_grep,
3456         pager_select,
3457 };
3459 /*
3460  * Help backend
3461  */
3463 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
3465 static bool
3466 help_open_keymap_title(struct view *view, enum keymap keymap)
3468         struct line *line;
3470         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3471                                help_keymap_hidden[keymap] ? '+' : '-',
3472                                enum_name(keymap_map[keymap]));
3473         if (line)
3474                 line->other = keymap;
3476         return help_keymap_hidden[keymap];
3479 static void
3480 help_open_keymap(struct view *view, enum keymap keymap)
3482         const char *group = NULL;
3483         char buf[SIZEOF_STR];
3484         size_t bufpos;
3485         bool add_title = TRUE;
3486         int i;
3488         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3489                 const char *key = NULL;
3491                 if (req_info[i].request == REQ_NONE)
3492                         continue;
3494                 if (!req_info[i].request) {
3495                         group = req_info[i].help;
3496                         continue;
3497                 }
3499                 key = get_keys(keymap, req_info[i].request, TRUE);
3500                 if (!key || !*key)
3501                         continue;
3503                 if (add_title && help_open_keymap_title(view, keymap))
3504                         return;
3505                 add_title = FALSE;
3507                 if (group) {
3508                         add_line_text(view, group, LINE_HELP_GROUP);
3509                         group = NULL;
3510                 }
3512                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3513                                 enum_name(req_info[i]), req_info[i].help);
3514         }
3516         group = "External commands:";
3518         for (i = 0; i < run_requests; i++) {
3519                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3520                 const char *key;
3521                 int argc;
3523                 if (!req || req->keymap != keymap)
3524                         continue;
3526                 key = get_key_name(req->key);
3527                 if (!*key)
3528                         key = "(no key defined)";
3530                 if (add_title && help_open_keymap_title(view, keymap))
3531                         return;
3532                 if (group) {
3533                         add_line_text(view, group, LINE_HELP_GROUP);
3534                         group = NULL;
3535                 }
3537                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3538                         if (!string_format_from(buf, &bufpos, "%s%s",
3539                                                 argc ? " " : "", req->argv[argc]))
3540                                 return;
3542                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3543         }
3546 static bool
3547 help_open(struct view *view, enum open_flags flags)
3549         enum keymap keymap;
3551         reset_view(view);
3552         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3553         add_line_text(view, "", LINE_DEFAULT);
3555         for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
3556                 help_open_keymap(view, keymap);
3558         return TRUE;
3561 static enum request
3562 help_request(struct view *view, enum request request, struct line *line)
3564         switch (request) {
3565         case REQ_ENTER:
3566                 if (line->type == LINE_HELP_KEYMAP) {
3567                         help_keymap_hidden[line->other] =
3568                                 !help_keymap_hidden[line->other];
3569                         refresh_view(view);
3570                 }
3572                 return REQ_NONE;
3573         default:
3574                 return pager_request(view, request, line);
3575         }
3578 static struct view_ops help_ops = {
3579         "line",
3580         help_open,
3581         NULL,
3582         pager_draw,
3583         help_request,
3584         pager_grep,
3585         pager_select,
3586 };
3589 /*
3590  * Tree backend
3591  */
3593 struct tree_stack_entry {
3594         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3595         unsigned long lineno;           /* Line number to restore */
3596         char *name;                     /* Position of name in opt_path */
3597 };
3599 /* The top of the path stack. */
3600 static struct tree_stack_entry *tree_stack = NULL;
3601 unsigned long tree_lineno = 0;
3603 static void
3604 pop_tree_stack_entry(void)
3606         struct tree_stack_entry *entry = tree_stack;
3608         tree_lineno = entry->lineno;
3609         entry->name[0] = 0;
3610         tree_stack = entry->prev;
3611         free(entry);
3614 static void
3615 push_tree_stack_entry(const char *name, unsigned long lineno)
3617         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3618         size_t pathlen = strlen(opt_path);
3620         if (!entry)
3621                 return;
3623         entry->prev = tree_stack;
3624         entry->name = opt_path + pathlen;
3625         tree_stack = entry;
3627         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3628                 pop_tree_stack_entry();
3629                 return;
3630         }
3632         /* Move the current line to the first tree entry. */
3633         tree_lineno = 1;
3634         entry->lineno = lineno;
3637 /* Parse output from git-ls-tree(1):
3638  *
3639  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3640  */
3642 #define SIZEOF_TREE_ATTR \
3643         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3645 #define SIZEOF_TREE_MODE \
3646         STRING_SIZE("100644 ")
3648 #define TREE_ID_OFFSET \
3649         STRING_SIZE("100644 blob ")
3651 struct tree_entry {
3652         char id[SIZEOF_REV];
3653         mode_t mode;
3654         struct time time;               /* Date from the author ident. */
3655         const char *author;             /* Author of the commit. */
3656         char name[1];
3657 };
3659 static const char *
3660 tree_path(const struct line *line)
3662         return ((struct tree_entry *) line->data)->name;
3665 static int
3666 tree_compare_entry(const struct line *line1, const struct line *line2)
3668         if (line1->type != line2->type)
3669                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3670         return strcmp(tree_path(line1), tree_path(line2));
3673 static const enum sort_field tree_sort_fields[] = {
3674         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3675 };
3676 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3678 static int
3679 tree_compare(const void *l1, const void *l2)
3681         const struct line *line1 = (const struct line *) l1;
3682         const struct line *line2 = (const struct line *) l2;
3683         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3684         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3686         if (line1->type == LINE_TREE_HEAD)
3687                 return -1;
3688         if (line2->type == LINE_TREE_HEAD)
3689                 return 1;
3691         switch (get_sort_field(tree_sort_state)) {
3692         case ORDERBY_DATE:
3693                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3695         case ORDERBY_AUTHOR:
3696                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3698         case ORDERBY_NAME:
3699         default:
3700                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3701         }
3705 static struct line *
3706 tree_entry(struct view *view, enum line_type type, const char *path,
3707            const char *mode, const char *id)
3709         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3710         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3712         if (!entry || !line) {
3713                 free(entry);
3714                 return NULL;
3715         }
3717         strncpy(entry->name, path, strlen(path));
3718         if (mode)
3719                 entry->mode = strtoul(mode, NULL, 8);
3720         if (id)
3721                 string_copy_rev(entry->id, id);
3723         return line;
3726 static bool
3727 tree_read_date(struct view *view, char *text, bool *read_date)
3729         static const char *author_name;
3730         static struct time author_time;
3732         if (!text && *read_date) {
3733                 *read_date = FALSE;
3734                 return TRUE;
3736         } else if (!text) {
3737                 /* Find next entry to process */
3738                 const char *log_file[] = {
3739                         "git", "log", "--no-color", "--pretty=raw",
3740                                 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3741                 };
3743                 if (!view->lines) {
3744                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3745                         report("Tree is empty");
3746                         return TRUE;
3747                 }
3749                 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3750                         report("Failed to load tree data");
3751                         return TRUE;
3752                 }
3754                 *read_date = TRUE;
3755                 return FALSE;
3757         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3758                 parse_author_line(text + STRING_SIZE("author "),
3759                                   &author_name, &author_time);
3761         } else if (*text == ':') {
3762                 char *pos;
3763                 size_t annotated = 1;
3764                 size_t i;
3766                 pos = strchr(text, '\t');
3767                 if (!pos)
3768                         return TRUE;
3769                 text = pos + 1;
3770                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3771                         text += strlen(opt_path);
3772                 pos = strchr(text, '/');
3773                 if (pos)
3774                         *pos = 0;
3776                 for (i = 1; i < view->lines; i++) {
3777                         struct line *line = &view->line[i];
3778                         struct tree_entry *entry = line->data;
3780                         annotated += !!entry->author;
3781                         if (entry->author || strcmp(entry->name, text))
3782                                 continue;
3784                         entry->author = author_name;
3785                         entry->time = author_time;
3786                         line->dirty = 1;
3787                         break;
3788                 }
3790                 if (annotated == view->lines)
3791                         io_kill(view->pipe);
3792         }
3793         return TRUE;
3796 static bool
3797 tree_read(struct view *view, char *text)
3799         static bool read_date = FALSE;
3800         struct tree_entry *data;
3801         struct line *entry, *line;
3802         enum line_type type;
3803         size_t textlen = text ? strlen(text) : 0;
3804         char *path = text + SIZEOF_TREE_ATTR;
3806         if (read_date || !text)
3807                 return tree_read_date(view, text, &read_date);
3809         if (textlen <= SIZEOF_TREE_ATTR)
3810                 return FALSE;
3811         if (view->lines == 0 &&
3812             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3813                 return FALSE;
3815         /* Strip the path part ... */
3816         if (*opt_path) {
3817                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3818                 size_t striplen = strlen(opt_path);
3820                 if (pathlen > striplen)
3821                         memmove(path, path + striplen,
3822                                 pathlen - striplen + 1);
3824                 /* Insert "link" to parent directory. */
3825                 if (view->lines == 1 &&
3826                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3827                         return FALSE;
3828         }
3830         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3831         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3832         if (!entry)
3833                 return FALSE;
3834         data = entry->data;
3836         /* Skip "Directory ..." and ".." line. */
3837         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3838                 if (tree_compare_entry(line, entry) <= 0)
3839                         continue;
3841                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3843                 line->data = data;
3844                 line->type = type;
3845                 for (; line <= entry; line++)
3846                         line->dirty = line->cleareol = 1;
3847                 return TRUE;
3848         }
3850         if (tree_lineno > view->lineno) {
3851                 view->lineno = tree_lineno;
3852                 tree_lineno = 0;
3853         }
3855         return TRUE;
3858 static bool
3859 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3861         struct tree_entry *entry = line->data;
3863         if (line->type == LINE_TREE_HEAD) {
3864                 if (draw_text(view, line->type, "Directory path /"))
3865                         return TRUE;
3866         } else {
3867                 if (draw_mode(view, entry->mode))
3868                         return TRUE;
3870                 if (draw_author(view, entry->author))
3871                         return TRUE;
3873                 if (draw_date(view, &entry->time))
3874                         return TRUE;
3875         }
3877         draw_text(view, line->type, entry->name);
3878         return TRUE;
3881 static void
3882 open_blob_editor(const char *id)
3884         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3885         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3886         int fd = mkstemp(file);
3888         if (fd == -1)
3889                 report("Failed to create temporary file");
3890         else if (!io_run_append(blob_argv, fd))
3891                 report("Failed to save blob data to file");
3892         else
3893                 open_editor(file);
3894         if (fd != -1)
3895                 unlink(file);
3898 static enum request
3899 tree_request(struct view *view, enum request request, struct line *line)
3901         enum open_flags flags;
3902         struct tree_entry *entry = line->data;
3904         switch (request) {
3905         case REQ_VIEW_BLAME:
3906                 if (line->type != LINE_TREE_FILE) {
3907                         report("Blame only supported for files");
3908                         return REQ_NONE;
3909                 }
3911                 string_copy(opt_ref, view->vid);
3912                 return request;
3914         case REQ_EDIT:
3915                 if (line->type != LINE_TREE_FILE) {
3916                         report("Edit only supported for files");
3917                 } else if (!is_head_commit(view->vid)) {
3918                         open_blob_editor(entry->id);
3919                 } else {
3920                         open_editor(opt_file);
3921                 }
3922                 return REQ_NONE;
3924         case REQ_TOGGLE_SORT_FIELD:
3925         case REQ_TOGGLE_SORT_ORDER:
3926                 sort_view(view, request, &tree_sort_state, tree_compare);
3927                 return REQ_NONE;
3929         case REQ_PARENT:
3930                 if (!*opt_path) {
3931                         /* quit view if at top of tree */
3932                         return REQ_VIEW_CLOSE;
3933                 }
3934                 /* fake 'cd  ..' */
3935                 line = &view->line[1];
3936                 break;
3938         case REQ_ENTER:
3939                 break;
3941         default:
3942                 return request;
3943         }
3945         /* Cleanup the stack if the tree view is at a different tree. */
3946         while (!*opt_path && tree_stack)
3947                 pop_tree_stack_entry();
3949         switch (line->type) {
3950         case LINE_TREE_DIR:
3951                 /* Depending on whether it is a subdirectory or parent link
3952                  * mangle the path buffer. */
3953                 if (line == &view->line[1] && *opt_path) {
3954                         pop_tree_stack_entry();
3956                 } else {
3957                         const char *basename = tree_path(line);
3959                         push_tree_stack_entry(basename, view->lineno);
3960                 }
3962                 /* Trees and subtrees share the same ID, so they are not not
3963                  * unique like blobs. */
3964                 flags = OPEN_RELOAD;
3965                 request = REQ_VIEW_TREE;
3966                 break;
3968         case LINE_TREE_FILE:
3969                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3970                 request = REQ_VIEW_BLOB;
3971                 break;
3973         default:
3974                 return REQ_NONE;
3975         }
3977         open_view(view, request, flags);
3978         if (request == REQ_VIEW_TREE)
3979                 view->lineno = tree_lineno;
3981         return REQ_NONE;
3984 static bool
3985 tree_grep(struct view *view, struct line *line)
3987         struct tree_entry *entry = line->data;
3988         const char *text[] = {
3989                 entry->name,
3990                 mkauthor(entry->author, opt_author_cols, opt_author),
3991                 mkdate(&entry->time, opt_date),
3992                 NULL
3993         };
3995         return grep_text(view, text);
3998 static void
3999 tree_select(struct view *view, struct line *line)
4001         struct tree_entry *entry = line->data;
4003         if (line->type == LINE_TREE_FILE) {
4004                 string_copy_rev(ref_blob, entry->id);
4005                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4007         } else if (line->type != LINE_TREE_DIR) {
4008                 return;
4009         }
4011         string_copy_rev(view->ref, entry->id);
4014 static bool
4015 tree_open(struct view *view, enum open_flags flags)
4017         static const char *tree_argv[] = {
4018                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4019         };
4021         if (view->lines == 0 && opt_prefix[0]) {
4022                 char *pos = opt_prefix;
4024                 while (pos && *pos) {
4025                         char *end = strchr(pos, '/');
4027                         if (end)
4028                                 *end = 0;
4029                         push_tree_stack_entry(pos, 0);
4030                         pos = end;
4031                         if (end) {
4032                                 *end = '/';
4033                                 pos++;
4034                         }
4035                 }
4037         } else if (strcmp(view->vid, view->id)) {
4038                 opt_path[0] = 0;
4039         }
4041         return begin_update(view, opt_cdup, tree_argv, flags);
4044 static struct view_ops tree_ops = {
4045         "file",
4046         tree_open,
4047         tree_read,
4048         tree_draw,
4049         tree_request,
4050         tree_grep,
4051         tree_select,
4052 };
4054 static bool
4055 blob_open(struct view *view, enum open_flags flags)
4057         static const char *blob_argv[] = {
4058                 "git", "cat-file", "blob", "%(blob)", NULL
4059         };
4061         return begin_update(view, NULL, blob_argv, flags);
4064 static bool
4065 blob_read(struct view *view, char *line)
4067         if (!line)
4068                 return TRUE;
4069         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4072 static enum request
4073 blob_request(struct view *view, enum request request, struct line *line)
4075         switch (request) {
4076         case REQ_EDIT:
4077                 open_blob_editor(view->vid);
4078                 return REQ_NONE;
4079         default:
4080                 return pager_request(view, request, line);
4081         }
4084 static struct view_ops blob_ops = {
4085         "line",
4086         blob_open,
4087         blob_read,
4088         pager_draw,
4089         blob_request,
4090         pager_grep,
4091         pager_select,
4092 };
4094 /*
4095  * Blame backend
4096  *
4097  * Loading the blame view is a two phase job:
4098  *
4099  *  1. File content is read either using opt_file from the
4100  *     filesystem or using git-cat-file.
4101  *  2. Then blame information is incrementally added by
4102  *     reading output from git-blame.
4103  */
4105 struct blame_commit {
4106         char id[SIZEOF_REV];            /* SHA1 ID. */
4107         char title[128];                /* First line of the commit message. */
4108         const char *author;             /* Author of the commit. */
4109         struct time time;               /* Date from the author ident. */
4110         char filename[128];             /* Name of file. */
4111         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4112         char parent_filename[128];      /* Parent/previous name of file. */
4113 };
4115 struct blame {
4116         struct blame_commit *commit;
4117         unsigned long lineno;
4118         char text[1];
4119 };
4121 static bool
4122 blame_open(struct view *view, enum open_flags flags)
4124         const char *file_argv[] = { opt_cdup, opt_file , NULL };
4125         char path[SIZEOF_STR];
4126         size_t i;
4128         if (!view->prev && *opt_prefix) {
4129                 string_copy(path, opt_file);
4130                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4131                         return FALSE;
4132         }
4134         if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4135                 const char *blame_cat_file_argv[] = {
4136                         "git", "cat-file", "blob", "%(ref):%(file)", NULL
4137                 };
4139                 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4140                         return FALSE;
4141         }
4143         /* First pass: remove multiple references to the same commit. */
4144         for (i = 0; i < view->lines; i++) {
4145                 struct blame *blame = view->line[i].data;
4147                 if (blame->commit && blame->commit->id[0])
4148                         blame->commit->id[0] = 0;
4149                 else
4150                         blame->commit = NULL;
4151         }
4153         /* Second pass: free existing references. */
4154         for (i = 0; i < view->lines; i++) {
4155                 struct blame *blame = view->line[i].data;
4157                 if (blame->commit)
4158                         free(blame->commit);
4159         }
4161         string_format(view->vid, "%s", opt_file);
4162         string_format(view->ref, "%s ...", opt_file);
4164         return TRUE;
4167 static struct blame_commit *
4168 get_blame_commit(struct view *view, const char *id)
4170         size_t i;
4172         for (i = 0; i < view->lines; i++) {
4173                 struct blame *blame = view->line[i].data;
4175                 if (!blame->commit)
4176                         continue;
4178                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4179                         return blame->commit;
4180         }
4182         {
4183                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4185                 if (commit)
4186                         string_ncopy(commit->id, id, SIZEOF_REV);
4187                 return commit;
4188         }
4191 static bool
4192 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4194         const char *pos = *posref;
4196         *posref = NULL;
4197         pos = strchr(pos + 1, ' ');
4198         if (!pos || !isdigit(pos[1]))
4199                 return FALSE;
4200         *number = atoi(pos + 1);
4201         if (*number < min || *number > max)
4202                 return FALSE;
4204         *posref = pos;
4205         return TRUE;
4208 static struct blame_commit *
4209 parse_blame_commit(struct view *view, const char *text, int *blamed)
4211         struct blame_commit *commit;
4212         struct blame *blame;
4213         const char *pos = text + SIZEOF_REV - 2;
4214         size_t orig_lineno = 0;
4215         size_t lineno;
4216         size_t group;
4218         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4219                 return NULL;
4221         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4222             !parse_number(&pos, &lineno, 1, view->lines) ||
4223             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4224                 return NULL;
4226         commit = get_blame_commit(view, text);
4227         if (!commit)
4228                 return NULL;
4230         *blamed += group;
4231         while (group--) {
4232                 struct line *line = &view->line[lineno + group - 1];
4234                 blame = line->data;
4235                 blame->commit = commit;
4236                 blame->lineno = orig_lineno + group - 1;
4237                 line->dirty = 1;
4238         }
4240         return commit;
4243 static bool
4244 blame_read_file(struct view *view, const char *line, bool *read_file)
4246         if (!line) {
4247                 const char *blame_argv[] = {
4248                         "git", "blame", "%(blameargs)", "--incremental",
4249                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4250                 };
4252                 if (view->lines == 0 && !view->prev)
4253                         die("No blame exist for %s", view->vid);
4255                 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4256                         report("Failed to load blame data");
4257                         return TRUE;
4258                 }
4260                 *read_file = FALSE;
4261                 return FALSE;
4263         } else {
4264                 size_t linelen = strlen(line);
4265                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4267                 if (!blame)
4268                         return FALSE;
4270                 blame->commit = NULL;
4271                 strncpy(blame->text, line, linelen);
4272                 blame->text[linelen] = 0;
4273                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4274         }
4277 static bool
4278 match_blame_header(const char *name, char **line)
4280         size_t namelen = strlen(name);
4281         bool matched = !strncmp(name, *line, namelen);
4283         if (matched)
4284                 *line += namelen;
4286         return matched;
4289 static bool
4290 blame_read(struct view *view, char *line)
4292         static struct blame_commit *commit = NULL;
4293         static int blamed = 0;
4294         static bool read_file = TRUE;
4296         if (read_file)
4297                 return blame_read_file(view, line, &read_file);
4299         if (!line) {
4300                 /* Reset all! */
4301                 commit = NULL;
4302                 blamed = 0;
4303                 read_file = TRUE;
4304                 string_format(view->ref, "%s", view->vid);
4305                 if (view_is_displayed(view)) {
4306                         update_view_title(view);
4307                         redraw_view_from(view, 0);
4308                 }
4309                 return TRUE;
4310         }
4312         if (!commit) {
4313                 commit = parse_blame_commit(view, line, &blamed);
4314                 string_format(view->ref, "%s %2d%%", view->vid,
4315                               view->lines ? blamed * 100 / view->lines : 0);
4317         } else if (match_blame_header("author ", &line)) {
4318                 commit->author = get_author(line);
4320         } else if (match_blame_header("author-time ", &line)) {
4321                 parse_timesec(&commit->time, line);
4323         } else if (match_blame_header("author-tz ", &line)) {
4324                 parse_timezone(&commit->time, line);
4326         } else if (match_blame_header("summary ", &line)) {
4327                 string_ncopy(commit->title, line, strlen(line));
4329         } else if (match_blame_header("previous ", &line)) {
4330                 if (strlen(line) <= SIZEOF_REV)
4331                         return FALSE;
4332                 string_copy_rev(commit->parent_id, line);
4333                 line += SIZEOF_REV;
4334                 string_ncopy(commit->parent_filename, line, strlen(line));
4336         } else if (match_blame_header("filename ", &line)) {
4337                 string_ncopy(commit->filename, line, strlen(line));
4338                 commit = NULL;
4339         }
4341         return TRUE;
4344 static bool
4345 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4347         struct blame *blame = line->data;
4348         struct time *time = NULL;
4349         const char *id = NULL, *author = NULL;
4351         if (blame->commit && *blame->commit->filename) {
4352                 id = blame->commit->id;
4353                 author = blame->commit->author;
4354                 time = &blame->commit->time;
4355         }
4357         if (draw_date(view, time))
4358                 return TRUE;
4360         if (draw_author(view, author))
4361                 return TRUE;
4363         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4364                 return TRUE;
4366         if (draw_lineno(view, lineno))
4367                 return TRUE;
4369         draw_text(view, LINE_DEFAULT, blame->text);
4370         return TRUE;
4373 static bool
4374 check_blame_commit(struct blame *blame, bool check_null_id)
4376         if (!blame->commit)
4377                 report("Commit data not loaded yet");
4378         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4379                 report("No commit exist for the selected line");
4380         else
4381                 return TRUE;
4382         return FALSE;
4385 static void
4386 setup_blame_parent_line(struct view *view, struct blame *blame)
4388         char from[SIZEOF_REF + SIZEOF_STR];
4389         char to[SIZEOF_REF + SIZEOF_STR];
4390         const char *diff_tree_argv[] = {
4391                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4392                         "-U0", from, to, "--", NULL
4393         };
4394         struct io io;
4395         int parent_lineno = -1;
4396         int blamed_lineno = -1;
4397         char *line;
4399         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4400             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4401             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4402                 return;
4404         while ((line = io_get(&io, '\n', TRUE))) {
4405                 if (*line == '@') {
4406                         char *pos = strchr(line, '+');
4408                         parent_lineno = atoi(line + 4);
4409                         if (pos)
4410                                 blamed_lineno = atoi(pos + 1);
4412                 } else if (*line == '+' && parent_lineno != -1) {
4413                         if (blame->lineno == blamed_lineno - 1 &&
4414                             !strcmp(blame->text, line + 1)) {
4415                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4416                                 break;
4417                         }
4418                         blamed_lineno++;
4419                 }
4420         }
4422         io_done(&io);
4425 static enum request
4426 blame_request(struct view *view, enum request request, struct line *line)
4428         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4429         struct blame *blame = line->data;
4431         switch (request) {
4432         case REQ_VIEW_BLAME:
4433                 if (check_blame_commit(blame, TRUE)) {
4434                         string_copy(opt_ref, blame->commit->id);
4435                         string_copy(opt_file, blame->commit->filename);
4436                         if (blame->lineno)
4437                                 view->lineno = blame->lineno;
4438                         reload_view(view);
4439                 }
4440                 break;
4442         case REQ_PARENT:
4443                 if (!check_blame_commit(blame, TRUE))
4444                         break;
4445                 if (!*blame->commit->parent_id) {
4446                         report("The selected commit has no parents");
4447                 } else {
4448                         string_copy_rev(opt_ref, blame->commit->parent_id);
4449                         string_copy(opt_file, blame->commit->parent_filename);
4450                         setup_blame_parent_line(view, blame);
4451                         reload_view(view);
4452                 }
4453                 break;
4455         case REQ_ENTER:
4456                 if (!check_blame_commit(blame, FALSE))
4457                         break;
4459                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4460                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4461                         break;
4463                 if (!strcmp(blame->commit->id, NULL_ID)) {
4464                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4465                         const char *diff_index_argv[] = {
4466                                 "git", "diff-index", "--root", "--patch-with-stat",
4467                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4468                         };
4470                         if (!*blame->commit->parent_id) {
4471                                 diff_index_argv[1] = "diff";
4472                                 diff_index_argv[2] = "--no-color";
4473                                 diff_index_argv[6] = "--";
4474                                 diff_index_argv[7] = "/dev/null";
4475                         }
4477                         open_argv(view, diff, diff_index_argv, NULL, flags);
4478                 } else {
4479                         open_view(view, REQ_VIEW_DIFF, flags);
4480                 }
4481                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4482                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4483                 break;
4485         default:
4486                 return request;
4487         }
4489         return REQ_NONE;
4492 static bool
4493 blame_grep(struct view *view, struct line *line)
4495         struct blame *blame = line->data;
4496         struct blame_commit *commit = blame->commit;
4497         const char *text[] = {
4498                 blame->text,
4499                 commit ? commit->title : "",
4500                 commit ? commit->id : "",
4501                 commit && opt_author ? commit->author : "",
4502                 commit ? mkdate(&commit->time, opt_date) : "",
4503                 NULL
4504         };
4506         return grep_text(view, text);
4509 static void
4510 blame_select(struct view *view, struct line *line)
4512         struct blame *blame = line->data;
4513         struct blame_commit *commit = blame->commit;
4515         if (!commit)
4516                 return;
4518         if (!strcmp(commit->id, NULL_ID))
4519                 string_ncopy(ref_commit, "HEAD", 4);
4520         else
4521                 string_copy_rev(ref_commit, commit->id);
4524 static struct view_ops blame_ops = {
4525         "line",
4526         blame_open,
4527         blame_read,
4528         blame_draw,
4529         blame_request,
4530         blame_grep,
4531         blame_select,
4532 };
4534 /*
4535  * Branch backend
4536  */
4538 struct branch {
4539         const char *author;             /* Author of the last commit. */
4540         struct time time;               /* Date of the last activity. */
4541         const struct ref *ref;          /* Name and commit ID information. */
4542 };
4544 static const struct ref branch_all;
4546 static const enum sort_field branch_sort_fields[] = {
4547         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4548 };
4549 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4551 static int
4552 branch_compare(const void *l1, const void *l2)
4554         const struct branch *branch1 = ((const struct line *) l1)->data;
4555         const struct branch *branch2 = ((const struct line *) l2)->data;
4557         switch (get_sort_field(branch_sort_state)) {
4558         case ORDERBY_DATE:
4559                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4561         case ORDERBY_AUTHOR:
4562                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4564         case ORDERBY_NAME:
4565         default:
4566                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4567         }
4570 static bool
4571 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4573         struct branch *branch = line->data;
4574         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4576         if (draw_date(view, &branch->time))
4577                 return TRUE;
4579         if (draw_author(view, branch->author))
4580                 return TRUE;
4582         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4583         return TRUE;
4586 static enum request
4587 branch_request(struct view *view, enum request request, struct line *line)
4589         struct branch *branch = line->data;
4591         switch (request) {
4592         case REQ_REFRESH:
4593                 load_refs();
4594                 refresh_view(view);
4595                 return REQ_NONE;
4597         case REQ_TOGGLE_SORT_FIELD:
4598         case REQ_TOGGLE_SORT_ORDER:
4599                 sort_view(view, request, &branch_sort_state, branch_compare);
4600                 return REQ_NONE;
4602         case REQ_ENTER:
4603         {
4604                 const struct ref *ref = branch->ref;
4605                 const char *all_branches_argv[] = {
4606                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4607                               "--topo-order",
4608                               ref == &branch_all ? "--all" : ref->name, NULL
4609                 };
4610                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4612                 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4613                 return REQ_NONE;
4614         }
4615         default:
4616                 return request;
4617         }
4620 static bool
4621 branch_read(struct view *view, char *line)
4623         static char id[SIZEOF_REV];
4624         struct branch *reference;
4625         size_t i;
4627         if (!line)
4628                 return TRUE;
4630         switch (get_line_type(line)) {
4631         case LINE_COMMIT:
4632                 string_copy_rev(id, line + STRING_SIZE("commit "));
4633                 return TRUE;
4635         case LINE_AUTHOR:
4636                 for (i = 0, reference = NULL; i < view->lines; i++) {
4637                         struct branch *branch = view->line[i].data;
4639                         if (strcmp(branch->ref->id, id))
4640                                 continue;
4642                         view->line[i].dirty = TRUE;
4643                         if (reference) {
4644                                 branch->author = reference->author;
4645                                 branch->time = reference->time;
4646                                 continue;
4647                         }
4649                         parse_author_line(line + STRING_SIZE("author "),
4650                                           &branch->author, &branch->time);
4651                         reference = branch;
4652                 }
4653                 return TRUE;
4655         default:
4656                 return TRUE;
4657         }
4661 static bool
4662 branch_open_visitor(void *data, const struct ref *ref)
4664         struct view *view = data;
4665         struct branch *branch;
4667         if (ref->tag || ref->ltag || ref->remote)
4668                 return TRUE;
4670         branch = calloc(1, sizeof(*branch));
4671         if (!branch)
4672                 return FALSE;
4674         branch->ref = ref;
4675         return !!add_line_data(view, branch, LINE_DEFAULT);
4678 static bool
4679 branch_open(struct view *view, enum open_flags flags)
4681         const char *branch_log[] = {
4682                 "git", "log", "--no-color", "--pretty=raw",
4683                         "--simplify-by-decoration", "--all", NULL
4684         };
4686         if (!begin_update(view, NULL, branch_log, flags)) {
4687                 report("Failed to load branch data");
4688                 return TRUE;
4689         }
4691         branch_open_visitor(view, &branch_all);
4692         foreach_ref(branch_open_visitor, view);
4693         view->p_restore = TRUE;
4695         return TRUE;
4698 static bool
4699 branch_grep(struct view *view, struct line *line)
4701         struct branch *branch = line->data;
4702         const char *text[] = {
4703                 branch->ref->name,
4704                 mkauthor(branch->author, opt_author_cols, opt_author),
4705                 NULL
4706         };
4708         return grep_text(view, text);
4711 static void
4712 branch_select(struct view *view, struct line *line)
4714         struct branch *branch = line->data;
4716         string_copy_rev(view->ref, branch->ref->id);
4717         string_copy_rev(ref_commit, branch->ref->id);
4718         string_copy_rev(ref_head, branch->ref->id);
4719         string_copy_rev(ref_branch, branch->ref->name);
4722 static struct view_ops branch_ops = {
4723         "branch",
4724         branch_open,
4725         branch_read,
4726         branch_draw,
4727         branch_request,
4728         branch_grep,
4729         branch_select,
4730 };
4732 /*
4733  * Status backend
4734  */
4736 struct status {
4737         char status;
4738         struct {
4739                 mode_t mode;
4740                 char rev[SIZEOF_REV];
4741                 char name[SIZEOF_STR];
4742         } old;
4743         struct {
4744                 mode_t mode;
4745                 char rev[SIZEOF_REV];
4746                 char name[SIZEOF_STR];
4747         } new;
4748 };
4750 static char status_onbranch[SIZEOF_STR];
4751 static struct status stage_status;
4752 static enum line_type stage_line_type;
4753 static size_t stage_chunks;
4754 static int *stage_chunk;
4756 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4758 /* This should work even for the "On branch" line. */
4759 static inline bool
4760 status_has_none(struct view *view, struct line *line)
4762         return line < view->line + view->lines && !line[1].data;
4765 /* Get fields from the diff line:
4766  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4767  */
4768 static inline bool
4769 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4771         const char *old_mode = buf +  1;
4772         const char *new_mode = buf +  8;
4773         const char *old_rev  = buf + 15;
4774         const char *new_rev  = buf + 56;
4775         const char *status   = buf + 97;
4777         if (bufsize < 98 ||
4778             old_mode[-1] != ':' ||
4779             new_mode[-1] != ' ' ||
4780             old_rev[-1]  != ' ' ||
4781             new_rev[-1]  != ' ' ||
4782             status[-1]   != ' ')
4783                 return FALSE;
4785         file->status = *status;
4787         string_copy_rev(file->old.rev, old_rev);
4788         string_copy_rev(file->new.rev, new_rev);
4790         file->old.mode = strtoul(old_mode, NULL, 8);
4791         file->new.mode = strtoul(new_mode, NULL, 8);
4793         file->old.name[0] = file->new.name[0] = 0;
4795         return TRUE;
4798 static bool
4799 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4801         struct status *unmerged = NULL;
4802         char *buf;
4803         struct io io;
4805         if (!io_run(&io, IO_RD, opt_cdup, argv))
4806                 return FALSE;
4808         add_line_data(view, NULL, type);
4810         while ((buf = io_get(&io, 0, TRUE))) {
4811                 struct status *file = unmerged;
4813                 if (!file) {
4814                         file = calloc(1, sizeof(*file));
4815                         if (!file || !add_line_data(view, file, type))
4816                                 goto error_out;
4817                 }
4819                 /* Parse diff info part. */
4820                 if (status) {
4821                         file->status = status;
4822                         if (status == 'A')
4823                                 string_copy(file->old.rev, NULL_ID);
4825                 } else if (!file->status || file == unmerged) {
4826                         if (!status_get_diff(file, buf, strlen(buf)))
4827                                 goto error_out;
4829                         buf = io_get(&io, 0, TRUE);
4830                         if (!buf)
4831                                 break;
4833                         /* Collapse all modified entries that follow an
4834                          * associated unmerged entry. */
4835                         if (unmerged == file) {
4836                                 unmerged->status = 'U';
4837                                 unmerged = NULL;
4838                         } else if (file->status == 'U') {
4839                                 unmerged = file;
4840                         }
4841                 }
4843                 /* Grab the old name for rename/copy. */
4844                 if (!*file->old.name &&
4845                     (file->status == 'R' || file->status == 'C')) {
4846                         string_ncopy(file->old.name, buf, strlen(buf));
4848                         buf = io_get(&io, 0, TRUE);
4849                         if (!buf)
4850                                 break;
4851                 }
4853                 /* git-ls-files just delivers a NUL separated list of
4854                  * file names similar to the second half of the
4855                  * git-diff-* output. */
4856                 string_ncopy(file->new.name, buf, strlen(buf));
4857                 if (!*file->old.name)
4858                         string_copy(file->old.name, file->new.name);
4859                 file = NULL;
4860         }
4862         if (io_error(&io)) {
4863 error_out:
4864                 io_done(&io);
4865                 return FALSE;
4866         }
4868         if (!view->line[view->lines - 1].data)
4869                 add_line_data(view, NULL, LINE_STAT_NONE);
4871         io_done(&io);
4872         return TRUE;
4875 /* Don't show unmerged entries in the staged section. */
4876 static const char *status_diff_index_argv[] = {
4877         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4878                              "--cached", "-M", "HEAD", NULL
4879 };
4881 static const char *status_diff_files_argv[] = {
4882         "git", "diff-files", "-z", NULL
4883 };
4885 static const char *status_list_other_argv[] = {
4886         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4887 };
4889 static const char *status_list_no_head_argv[] = {
4890         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4891 };
4893 static const char *update_index_argv[] = {
4894         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4895 };
4897 /* Restore the previous line number to stay in the context or select a
4898  * line with something that can be updated. */
4899 static void
4900 status_restore(struct view *view)
4902         if (view->p_lineno >= view->lines)
4903                 view->p_lineno = view->lines - 1;
4904         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4905                 view->p_lineno++;
4906         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4907                 view->p_lineno--;
4909         /* If the above fails, always skip the "On branch" line. */
4910         if (view->p_lineno < view->lines)
4911                 view->lineno = view->p_lineno;
4912         else
4913                 view->lineno = 1;
4915         if (view->lineno < view->offset)
4916                 view->offset = view->lineno;
4917         else if (view->offset + view->height <= view->lineno)
4918                 view->offset = view->lineno - view->height + 1;
4920         view->p_restore = FALSE;
4923 static void
4924 status_update_onbranch(void)
4926         static const char *paths[][2] = {
4927                 { "rebase-apply/rebasing",      "Rebasing" },
4928                 { "rebase-apply/applying",      "Applying mailbox" },
4929                 { "rebase-apply/",              "Rebasing mailbox" },
4930                 { "rebase-merge/interactive",   "Interactive rebase" },
4931                 { "rebase-merge/",              "Rebase merge" },
4932                 { "MERGE_HEAD",                 "Merging" },
4933                 { "BISECT_LOG",                 "Bisecting" },
4934                 { "HEAD",                       "On branch" },
4935         };
4936         char buf[SIZEOF_STR];
4937         struct stat stat;
4938         int i;
4940         if (is_initial_commit()) {
4941                 string_copy(status_onbranch, "Initial commit");
4942                 return;
4943         }
4945         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4946                 char *head = opt_head;
4948                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4949                     lstat(buf, &stat) < 0)
4950                         continue;
4952                 if (!*opt_head) {
4953                         struct io io;
4955                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4956                             io_read_buf(&io, buf, sizeof(buf))) {
4957                                 head = buf;
4958                                 if (!prefixcmp(head, "refs/heads/"))
4959                                         head += STRING_SIZE("refs/heads/");
4960                         }
4961                 }
4963                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4964                         string_copy(status_onbranch, opt_head);
4965                 return;
4966         }
4968         string_copy(status_onbranch, "Not currently on any branch");
4971 /* First parse staged info using git-diff-index(1), then parse unstaged
4972  * info using git-diff-files(1), and finally untracked files using
4973  * git-ls-files(1). */
4974 static bool
4975 status_open(struct view *view, enum open_flags flags)
4977         reset_view(view);
4979         add_line_data(view, NULL, LINE_STAT_HEAD);
4980         status_update_onbranch();
4982         io_run_bg(update_index_argv);
4984         if (is_initial_commit()) {
4985                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4986                         return FALSE;
4987         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4988                 return FALSE;
4989         }
4991         if (!opt_untracked_dirs_content)
4992                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4994         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4995             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4996                 return FALSE;
4998         /* Restore the exact position or use the specialized restore
4999          * mode? */
5000         if (!view->p_restore)
5001                 status_restore(view);
5002         return TRUE;
5005 static bool
5006 status_draw(struct view *view, struct line *line, unsigned int lineno)
5008         struct status *status = line->data;
5009         enum line_type type;
5010         const char *text;
5012         if (!status) {
5013                 switch (line->type) {
5014                 case LINE_STAT_STAGED:
5015                         type = LINE_STAT_SECTION;
5016                         text = "Changes to be committed:";
5017                         break;
5019                 case LINE_STAT_UNSTAGED:
5020                         type = LINE_STAT_SECTION;
5021                         text = "Changed but not updated:";
5022                         break;
5024                 case LINE_STAT_UNTRACKED:
5025                         type = LINE_STAT_SECTION;
5026                         text = "Untracked files:";
5027                         break;
5029                 case LINE_STAT_NONE:
5030                         type = LINE_DEFAULT;
5031                         text = "  (no files)";
5032                         break;
5034                 case LINE_STAT_HEAD:
5035                         type = LINE_STAT_HEAD;
5036                         text = status_onbranch;
5037                         break;
5039                 default:
5040                         return FALSE;
5041                 }
5042         } else {
5043                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5045                 buf[0] = status->status;
5046                 if (draw_text(view, line->type, buf))
5047                         return TRUE;
5048                 type = LINE_DEFAULT;
5049                 text = status->new.name;
5050         }
5052         draw_text(view, type, text);
5053         return TRUE;
5056 static enum request
5057 status_enter(struct view *view, struct line *line)
5059         struct status *status = line->data;
5060         const char *oldpath = status ? status->old.name : NULL;
5061         /* Diffs for unmerged entries are empty when passing the new
5062          * path, so leave it empty. */
5063         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5064         const char *info;
5065         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5066         struct view *stage = VIEW(REQ_VIEW_STAGE);
5068         if (line->type == LINE_STAT_NONE ||
5069             (!status && line[1].type == LINE_STAT_NONE)) {
5070                 report("No file to diff");
5071                 return REQ_NONE;
5072         }
5074         switch (line->type) {
5075         case LINE_STAT_STAGED:
5076                 if (is_initial_commit()) {
5077                         const char *no_head_diff_argv[] = {
5078                                 "git", "diff", "--no-color", "--patch-with-stat",
5079                                         "--", "/dev/null", newpath, NULL
5080                         };
5082                         open_argv(view, stage, no_head_diff_argv, opt_cdup, flags); 
5083                 } else {
5084                         const char *index_show_argv[] = {
5085                                 "git", "diff-index", "--root", "--patch-with-stat",
5086                                         "-C", "-M", "--cached", "HEAD", "--",
5087                                         oldpath, newpath, NULL
5088                         };
5090                         open_argv(view, stage, index_show_argv, opt_cdup, flags);
5091                 }
5093                 if (status)
5094                         info = "Staged changes to %s";
5095                 else
5096                         info = "Staged changes";
5097                 break;
5099         case LINE_STAT_UNSTAGED:
5100         {
5101                 const char *files_show_argv[] = {
5102                         "git", "diff-files", "--root", "--patch-with-stat",
5103                                 "-C", "-M", "--", oldpath, newpath, NULL
5104                 };
5106                 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5107                 if (status)
5108                         info = "Unstaged changes to %s";
5109                 else
5110                         info = "Unstaged changes";
5111                 break;
5112         }
5113         case LINE_STAT_UNTRACKED:
5114                 if (!newpath) {
5115                         report("No file to show");
5116                         return REQ_NONE;
5117                 }
5119                 if (!suffixcmp(status->new.name, -1, "/")) {
5120                         report("Cannot display a directory");
5121                         return REQ_NONE;
5122                 }
5124                 open_file(view, stage, newpath, flags);
5125                 info = "Untracked file %s";
5126                 break;
5128         case LINE_STAT_HEAD:
5129                 return REQ_NONE;
5131         default:
5132                 die("line type %d not handled in switch", line->type);
5133         }
5135         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5136                 if (status) {
5137                         stage_status = *status;
5138                 } else {
5139                         memset(&stage_status, 0, sizeof(stage_status));
5140                 }
5142                 stage_line_type = line->type;
5143                 stage_chunks = 0;
5144                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5145         }
5147         return REQ_NONE;
5150 static bool
5151 status_exists(struct status *status, enum line_type type)
5153         struct view *view = VIEW(REQ_VIEW_STATUS);
5154         unsigned long lineno;
5156         for (lineno = 0; lineno < view->lines; lineno++) {
5157                 struct line *line = &view->line[lineno];
5158                 struct status *pos = line->data;
5160                 if (line->type != type)
5161                         continue;
5162                 if (!pos && (!status || !status->status) && line[1].data) {
5163                         select_view_line(view, lineno);
5164                         return TRUE;
5165                 }
5166                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5167                         select_view_line(view, lineno);
5168                         return TRUE;
5169                 }
5170         }
5172         return FALSE;
5176 static bool
5177 status_update_prepare(struct io *io, enum line_type type)
5179         const char *staged_argv[] = {
5180                 "git", "update-index", "-z", "--index-info", NULL
5181         };
5182         const char *others_argv[] = {
5183                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5184         };
5186         switch (type) {
5187         case LINE_STAT_STAGED:
5188                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5190         case LINE_STAT_UNSTAGED:
5191         case LINE_STAT_UNTRACKED:
5192                 return io_run(io, IO_WR, opt_cdup, others_argv);
5194         default:
5195                 die("line type %d not handled in switch", type);
5196                 return FALSE;
5197         }
5200 static bool
5201 status_update_write(struct io *io, struct status *status, enum line_type type)
5203         char buf[SIZEOF_STR];
5204         size_t bufsize = 0;
5206         switch (type) {
5207         case LINE_STAT_STAGED:
5208                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5209                                         status->old.mode,
5210                                         status->old.rev,
5211                                         status->old.name, 0))
5212                         return FALSE;
5213                 break;
5215         case LINE_STAT_UNSTAGED:
5216         case LINE_STAT_UNTRACKED:
5217                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5218                         return FALSE;
5219                 break;
5221         default:
5222                 die("line type %d not handled in switch", type);
5223         }
5225         return io_write(io, buf, bufsize);
5228 static bool
5229 status_update_file(struct status *status, enum line_type type)
5231         struct io io;
5232         bool result;
5234         if (!status_update_prepare(&io, type))
5235                 return FALSE;
5237         result = status_update_write(&io, status, type);
5238         return io_done(&io) && result;
5241 static bool
5242 status_update_files(struct view *view, struct line *line)
5244         char buf[sizeof(view->ref)];
5245         struct io io;
5246         bool result = TRUE;
5247         struct line *pos = view->line + view->lines;
5248         int files = 0;
5249         int file, done;
5250         int cursor_y = -1, cursor_x = -1;
5252         if (!status_update_prepare(&io, line->type))
5253                 return FALSE;
5255         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5256                 files++;
5258         string_copy(buf, view->ref);
5259         getsyx(cursor_y, cursor_x);
5260         for (file = 0, done = 5; result && file < files; line++, file++) {
5261                 int almost_done = file * 100 / files;
5263                 if (almost_done > done) {
5264                         done = almost_done;
5265                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5266                                       file, files, done);
5267                         update_view_title(view);
5268                         setsyx(cursor_y, cursor_x);
5269                         doupdate();
5270                 }
5271                 result = status_update_write(&io, line->data, line->type);
5272         }
5273         string_copy(view->ref, buf);
5275         return io_done(&io) && result;
5278 static bool
5279 status_update(struct view *view)
5281         struct line *line = &view->line[view->lineno];
5283         assert(view->lines);
5285         if (!line->data) {
5286                 /* This should work even for the "On branch" line. */
5287                 if (line < view->line + view->lines && !line[1].data) {
5288                         report("Nothing to update");
5289                         return FALSE;
5290                 }
5292                 if (!status_update_files(view, line + 1)) {
5293                         report("Failed to update file status");
5294                         return FALSE;
5295                 }
5297         } else if (!status_update_file(line->data, line->type)) {
5298                 report("Failed to update file status");
5299                 return FALSE;
5300         }
5302         return TRUE;
5305 static bool
5306 status_revert(struct status *status, enum line_type type, bool has_none)
5308         if (!status || type != LINE_STAT_UNSTAGED) {
5309                 if (type == LINE_STAT_STAGED) {
5310                         report("Cannot revert changes to staged files");
5311                 } else if (type == LINE_STAT_UNTRACKED) {
5312                         report("Cannot revert changes to untracked files");
5313                 } else if (has_none) {
5314                         report("Nothing to revert");
5315                 } else {
5316                         report("Cannot revert changes to multiple files");
5317                 }
5319         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5320                 char mode[10] = "100644";
5321                 const char *reset_argv[] = {
5322                         "git", "update-index", "--cacheinfo", mode,
5323                                 status->old.rev, status->old.name, NULL
5324                 };
5325                 const char *checkout_argv[] = {
5326                         "git", "checkout", "--", status->old.name, NULL
5327                 };
5329                 if (status->status == 'U') {
5330                         string_format(mode, "%5o", status->old.mode);
5332                         if (status->old.mode == 0 && status->new.mode == 0) {
5333                                 reset_argv[2] = "--force-remove";
5334                                 reset_argv[3] = status->old.name;
5335                                 reset_argv[4] = NULL;
5336                         }
5338                         if (!io_run_fg(reset_argv, opt_cdup))
5339                                 return FALSE;
5340                         if (status->old.mode == 0 && status->new.mode == 0)
5341                                 return TRUE;
5342                 }
5344                 return io_run_fg(checkout_argv, opt_cdup);
5345         }
5347         return FALSE;
5350 static enum request
5351 status_request(struct view *view, enum request request, struct line *line)
5353         struct status *status = line->data;
5355         switch (request) {
5356         case REQ_STATUS_UPDATE:
5357                 if (!status_update(view))
5358                         return REQ_NONE;
5359                 break;
5361         case REQ_STATUS_REVERT:
5362                 if (!status_revert(status, line->type, status_has_none(view, line)))
5363                         return REQ_NONE;
5364                 break;
5366         case REQ_STATUS_MERGE:
5367                 if (!status || status->status != 'U') {
5368                         report("Merging only possible for files with unmerged status ('U').");
5369                         return REQ_NONE;
5370                 }
5371                 open_mergetool(status->new.name);
5372                 break;
5374         case REQ_EDIT:
5375                 if (!status)
5376                         return request;
5377                 if (status->status == 'D') {
5378                         report("File has been deleted.");
5379                         return REQ_NONE;
5380                 }
5382                 open_editor(status->new.name);
5383                 break;
5385         case REQ_VIEW_BLAME:
5386                 if (status)
5387                         opt_ref[0] = 0;
5388                 return request;
5390         case REQ_ENTER:
5391                 /* After returning the status view has been split to
5392                  * show the stage view. No further reloading is
5393                  * necessary. */
5394                 return status_enter(view, line);
5396         case REQ_REFRESH:
5397                 /* Simply reload the view. */
5398                 break;
5400         default:
5401                 return request;
5402         }
5404         refresh_view(view);
5406         return REQ_NONE;
5409 static void
5410 status_select(struct view *view, struct line *line)
5412         struct status *status = line->data;
5413         char file[SIZEOF_STR] = "all files";
5414         const char *text;
5415         const char *key;
5417         if (status && !string_format(file, "'%s'", status->new.name))
5418                 return;
5420         if (!status && line[1].type == LINE_STAT_NONE)
5421                 line++;
5423         switch (line->type) {
5424         case LINE_STAT_STAGED:
5425                 text = "Press %s to unstage %s for commit";
5426                 break;
5428         case LINE_STAT_UNSTAGED:
5429                 text = "Press %s to stage %s for commit";
5430                 break;
5432         case LINE_STAT_UNTRACKED:
5433                 text = "Press %s to stage %s for addition";
5434                 break;
5436         case LINE_STAT_HEAD:
5437         case LINE_STAT_NONE:
5438                 text = "Nothing to update";
5439                 break;
5441         default:
5442                 die("line type %d not handled in switch", line->type);
5443         }
5445         if (status && status->status == 'U') {
5446                 text = "Press %s to resolve conflict in %s";
5447                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5449         } else {
5450                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5451         }
5453         string_format(view->ref, text, key, file);
5454         if (status)
5455                 string_copy(opt_file, status->new.name);
5458 static bool
5459 status_grep(struct view *view, struct line *line)
5461         struct status *status = line->data;
5463         if (status) {
5464                 const char buf[2] = { status->status, 0 };
5465                 const char *text[] = { status->new.name, buf, NULL };
5467                 return grep_text(view, text);
5468         }
5470         return FALSE;
5473 static struct view_ops status_ops = {
5474         "file",
5475         status_open,
5476         NULL,
5477         status_draw,
5478         status_request,
5479         status_grep,
5480         status_select,
5481 };
5484 static bool
5485 stage_diff_write(struct io *io, struct line *line, struct line *end)
5487         while (line < end) {
5488                 if (!io_write(io, line->data, strlen(line->data)) ||
5489                     !io_write(io, "\n", 1))
5490                         return FALSE;
5491                 line++;
5492                 if (line->type == LINE_DIFF_CHUNK ||
5493                     line->type == LINE_DIFF_HEADER)
5494                         break;
5495         }
5497         return TRUE;
5500 static struct line *
5501 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5503         for (; view->line < line; line--)
5504                 if (line->type == type)
5505                         return line;
5507         return NULL;
5510 static bool
5511 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5513         const char *apply_argv[SIZEOF_ARG] = {
5514                 "git", "apply", "--whitespace=nowarn", NULL
5515         };
5516         struct line *diff_hdr;
5517         struct io io;
5518         int argc = 3;
5520         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5521         if (!diff_hdr)
5522                 return FALSE;
5524         if (!revert)
5525                 apply_argv[argc++] = "--cached";
5526         if (revert || stage_line_type == LINE_STAT_STAGED)
5527                 apply_argv[argc++] = "-R";
5528         apply_argv[argc++] = "-";
5529         apply_argv[argc++] = NULL;
5530         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5531                 return FALSE;
5533         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5534             !stage_diff_write(&io, chunk, view->line + view->lines))
5535                 chunk = NULL;
5537         io_done(&io);
5538         io_run_bg(update_index_argv);
5540         return chunk ? TRUE : FALSE;
5543 static bool
5544 stage_update(struct view *view, struct line *line)
5546         struct line *chunk = NULL;
5548         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5549                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5551         if (chunk) {
5552                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5553                         report("Failed to apply chunk");
5554                         return FALSE;
5555                 }
5557         } else if (!stage_status.status) {
5558                 view = VIEW(REQ_VIEW_STATUS);
5560                 for (line = view->line; line < view->line + view->lines; line++)
5561                         if (line->type == stage_line_type)
5562                                 break;
5564                 if (!status_update_files(view, line + 1)) {
5565                         report("Failed to update files");
5566                         return FALSE;
5567                 }
5569         } else if (!status_update_file(&stage_status, stage_line_type)) {
5570                 report("Failed to update file");
5571                 return FALSE;
5572         }
5574         return TRUE;
5577 static bool
5578 stage_revert(struct view *view, struct line *line)
5580         struct line *chunk = NULL;
5582         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5583                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5585         if (chunk) {
5586                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5587                         return FALSE;
5589                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5590                         report("Failed to revert chunk");
5591                         return FALSE;
5592                 }
5593                 return TRUE;
5595         } else {
5596                 return status_revert(stage_status.status ? &stage_status : NULL,
5597                                      stage_line_type, FALSE);
5598         }
5602 static void
5603 stage_next(struct view *view, struct line *line)
5605         int i;
5607         if (!stage_chunks) {
5608                 for (line = view->line; line < view->line + view->lines; line++) {
5609                         if (line->type != LINE_DIFF_CHUNK)
5610                                 continue;
5612                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5613                                 report("Allocation failure");
5614                                 return;
5615                         }
5617                         stage_chunk[stage_chunks++] = line - view->line;
5618                 }
5619         }
5621         for (i = 0; i < stage_chunks; i++) {
5622                 if (stage_chunk[i] > view->lineno) {
5623                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5624                         report("Chunk %d of %d", i + 1, stage_chunks);
5625                         return;
5626                 }
5627         }
5629         report("No next chunk found");
5632 static enum request
5633 stage_request(struct view *view, enum request request, struct line *line)
5635         switch (request) {
5636         case REQ_STATUS_UPDATE:
5637                 if (!stage_update(view, line))
5638                         return REQ_NONE;
5639                 break;
5641         case REQ_STATUS_REVERT:
5642                 if (!stage_revert(view, line))
5643                         return REQ_NONE;
5644                 break;
5646         case REQ_STAGE_NEXT:
5647                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5648                         report("File is untracked; press %s to add",
5649                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5650                         return REQ_NONE;
5651                 }
5652                 stage_next(view, line);
5653                 return REQ_NONE;
5655         case REQ_EDIT:
5656                 if (!stage_status.new.name[0])
5657                         return request;
5658                 if (stage_status.status == 'D') {
5659                         report("File has been deleted.");
5660                         return REQ_NONE;
5661                 }
5663                 open_editor(stage_status.new.name);
5664                 break;
5666         case REQ_REFRESH:
5667                 /* Reload everything ... */
5668                 break;
5670         case REQ_VIEW_BLAME:
5671                 if (stage_status.new.name[0]) {
5672                         string_copy(opt_file, stage_status.new.name);
5673                         opt_ref[0] = 0;
5674                 }
5675                 return request;
5677         case REQ_ENTER:
5678                 return pager_request(view, request, line);
5680         default:
5681                 return request;
5682         }
5684         refresh_view(view->parent);
5686         /* Check whether the staged entry still exists, and close the
5687          * stage view if it doesn't. */
5688         if (!status_exists(&stage_status, stage_line_type)) {
5689                 status_restore(VIEW(REQ_VIEW_STATUS));
5690                 return REQ_VIEW_CLOSE;
5691         }
5693         refresh_view(view);
5695         return REQ_NONE;
5698 static struct view_ops stage_ops = {
5699         "line",
5700         view_open,
5701         pager_read,
5702         pager_draw,
5703         stage_request,
5704         pager_grep,
5705         pager_select,
5706 };
5709 /*
5710  * Revision graph
5711  */
5713 static const enum line_type graph_colors[] = {
5714         LINE_GRAPH_LINE_0,
5715         LINE_GRAPH_LINE_1,
5716         LINE_GRAPH_LINE_2,
5717         LINE_GRAPH_LINE_3,
5718         LINE_GRAPH_LINE_4,
5719         LINE_GRAPH_LINE_5,
5720         LINE_GRAPH_LINE_6,
5721 };
5723 static enum line_type get_graph_color(struct graph_symbol *symbol)
5725         if (symbol->commit)
5726                 return LINE_GRAPH_COMMIT;
5727         assert(symbol->color < ARRAY_SIZE(graph_colors));
5728         return graph_colors[symbol->color];
5731 static bool
5732 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5734         const char *chars = graph_symbol_to_utf8(symbol);
5736         return draw_text(view, color, chars + !!first); 
5739 static bool
5740 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5742         const char *chars = graph_symbol_to_ascii(symbol);
5744         return draw_text(view, color, chars + !!first); 
5747 static bool
5748 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5750         const chtype *chars = graph_symbol_to_chtype(symbol);
5752         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5755 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5757 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5759         static const draw_graph_fn fns[] = {
5760                 draw_graph_ascii,
5761                 draw_graph_chtype,
5762                 draw_graph_utf8
5763         };
5764         draw_graph_fn fn = fns[opt_line_graphics];
5765         int i;
5767         for (i = 0; i < canvas->size; i++) {
5768                 struct graph_symbol *symbol = &canvas->symbols[i];
5769                 enum line_type color = get_graph_color(symbol);
5771                 if (fn(view, symbol, color, i == 0))
5772                         return TRUE;
5773         }
5775         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5778 /*
5779  * Main view backend
5780  */
5782 struct commit {
5783         char id[SIZEOF_REV];            /* SHA1 ID. */
5784         char title[128];                /* First line of the commit message. */
5785         const char *author;             /* Author of the commit. */
5786         struct time time;               /* Date from the author ident. */
5787         struct ref_list *refs;          /* Repository references. */
5788         struct graph_canvas graph;      /* Ancestry chain graphics. */
5789 };
5791 static bool
5792 main_open(struct view *view, enum open_flags flags)
5794         static const char *main_argv[] = {
5795                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5796                         "--topo-order", "%(diffargs)", "%(revargs)",
5797                         "--", "%(fileargs)", NULL
5798         };
5800         return begin_update(view, NULL, main_argv, flags);
5803 static bool
5804 main_draw(struct view *view, struct line *line, unsigned int lineno)
5806         struct commit *commit = line->data;
5808         if (!commit->author)
5809                 return FALSE;
5811         if (draw_date(view, &commit->time))
5812                 return TRUE;
5814         if (draw_author(view, commit->author))
5815                 return TRUE;
5817         if (opt_rev_graph && draw_graph(view, &commit->graph))
5818                 return TRUE;
5820         if (draw_refs(view, commit->refs))
5821                 return TRUE;
5823         draw_text(view, LINE_DEFAULT, commit->title);
5824         return TRUE;
5827 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5828 static bool
5829 main_read(struct view *view, char *line)
5831         static struct graph graph;
5832         enum line_type type;
5833         struct commit *commit;
5835         if (!line) {
5836                 if (!view->lines && !view->prev)
5837                         die("No revisions match the given arguments.");
5838                 if (view->lines > 0) {
5839                         commit = view->line[view->lines - 1].data;
5840                         view->line[view->lines - 1].dirty = 1;
5841                         if (!commit->author) {
5842                                 view->lines--;
5843                                 free(commit);
5844                         }
5845                 }
5847                 done_graph(&graph);
5848                 return TRUE;
5849         }
5851         type = get_line_type(line);
5852         if (type == LINE_COMMIT) {
5853                 bool is_boundary;
5855                 commit = calloc(1, sizeof(struct commit));
5856                 if (!commit)
5857                         return FALSE;
5859                 line += STRING_SIZE("commit ");
5860                 is_boundary = *line == '-';
5861                 if (is_boundary)
5862                         line++;
5864                 string_copy_rev(commit->id, line);
5865                 commit->refs = get_ref_list(commit->id);
5866                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5867                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5868                 return TRUE;
5869         }
5871         if (!view->lines)
5872                 return TRUE;
5873         commit = view->line[view->lines - 1].data;
5875         switch (type) {
5876         case LINE_PARENT:
5877                 if (!graph.has_parents)
5878                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5879                 break;
5881         case LINE_AUTHOR:
5882                 parse_author_line(line + STRING_SIZE("author "),
5883                                   &commit->author, &commit->time);
5884                 graph_render_parents(&graph);
5885                 break;
5887         default:
5888                 /* Fill in the commit title if it has not already been set. */
5889                 if (commit->title[0])
5890                         break;
5892                 /* Require titles to start with a non-space character at the
5893                  * offset used by git log. */
5894                 if (strncmp(line, "    ", 4))
5895                         break;
5896                 line += 4;
5897                 /* Well, if the title starts with a whitespace character,
5898                  * try to be forgiving.  Otherwise we end up with no title. */
5899                 while (isspace(*line))
5900                         line++;
5901                 if (*line == '\0')
5902                         break;
5903                 /* FIXME: More graceful handling of titles; append "..." to
5904                  * shortened titles, etc. */
5906                 string_expand(commit->title, sizeof(commit->title), line, 1);
5907                 view->line[view->lines - 1].dirty = 1;
5908         }
5910         return TRUE;
5913 static enum request
5914 main_request(struct view *view, enum request request, struct line *line)
5916         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5918         switch (request) {
5919         case REQ_ENTER:
5920                 if (view_is_displayed(view) && display[0] != view)
5921                         maximize_view(view, TRUE);
5922                 open_view(view, REQ_VIEW_DIFF, flags);
5923                 break;
5924         case REQ_REFRESH:
5925                 load_refs();
5926                 refresh_view(view);
5927                 break;
5928         default:
5929                 return request;
5930         }
5932         return REQ_NONE;
5935 static bool
5936 grep_refs(struct ref_list *list, regex_t *regex)
5938         regmatch_t pmatch;
5939         size_t i;
5941         if (!opt_show_refs || !list)
5942                 return FALSE;
5944         for (i = 0; i < list->size; i++) {
5945                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5946                         return TRUE;
5947         }
5949         return FALSE;
5952 static bool
5953 main_grep(struct view *view, struct line *line)
5955         struct commit *commit = line->data;
5956         const char *text[] = {
5957                 commit->title,
5958                 mkauthor(commit->author, opt_author_cols, opt_author),
5959                 mkdate(&commit->time, opt_date),
5960                 NULL
5961         };
5963         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5966 static void
5967 main_select(struct view *view, struct line *line)
5969         struct commit *commit = line->data;
5971         string_copy_rev(view->ref, commit->id);
5972         string_copy_rev(ref_commit, view->ref);
5975 static struct view_ops main_ops = {
5976         "commit",
5977         main_open,
5978         main_read,
5979         main_draw,
5980         main_request,
5981         main_grep,
5982         main_select,
5983 };
5986 /*
5987  * Status management
5988  */
5990 /* Whether or not the curses interface has been initialized. */
5991 static bool cursed = FALSE;
5993 /* Terminal hacks and workarounds. */
5994 static bool use_scroll_redrawwin;
5995 static bool use_scroll_status_wclear;
5997 /* The status window is used for polling keystrokes. */
5998 static WINDOW *status_win;
6000 /* Reading from the prompt? */
6001 static bool input_mode = FALSE;
6003 static bool status_empty = FALSE;
6005 /* Update status and title window. */
6006 static void
6007 report(const char *msg, ...)
6009         struct view *view = display[current_view];
6011         if (input_mode)
6012                 return;
6014         if (!view) {
6015                 char buf[SIZEOF_STR];
6016                 va_list args;
6018                 va_start(args, msg);
6019                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6020                         buf[sizeof(buf) - 1] = 0;
6021                         buf[sizeof(buf) - 2] = '.';
6022                         buf[sizeof(buf) - 3] = '.';
6023                         buf[sizeof(buf) - 4] = '.';
6024                 }
6025                 va_end(args);
6026                 die("%s", buf);
6027         }
6029         if (!status_empty || *msg) {
6030                 va_list args;
6032                 va_start(args, msg);
6034                 wmove(status_win, 0, 0);
6035                 if (view->has_scrolled && use_scroll_status_wclear)
6036                         wclear(status_win);
6037                 if (*msg) {
6038                         vwprintw(status_win, msg, args);
6039                         status_empty = FALSE;
6040                 } else {
6041                         status_empty = TRUE;
6042                 }
6043                 wclrtoeol(status_win);
6044                 wnoutrefresh(status_win);
6046                 va_end(args);
6047         }
6049         update_view_title(view);
6052 static void
6053 init_display(void)
6055         const char *term;
6056         int x, y;
6058         /* Initialize the curses library */
6059         if (isatty(STDIN_FILENO)) {
6060                 cursed = !!initscr();
6061                 opt_tty = stdin;
6062         } else {
6063                 /* Leave stdin and stdout alone when acting as a pager. */
6064                 opt_tty = fopen("/dev/tty", "r+");
6065                 if (!opt_tty)
6066                         die("Failed to open /dev/tty");
6067                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6068         }
6070         if (!cursed)
6071                 die("Failed to initialize curses");
6073         nonl();         /* Disable conversion and detect newlines from input. */
6074         cbreak();       /* Take input chars one at a time, no wait for \n */
6075         noecho();       /* Don't echo input */
6076         leaveok(stdscr, FALSE);
6078         if (has_colors())
6079                 init_colors();
6081         getmaxyx(stdscr, y, x);
6082         status_win = newwin(1, x, y - 1, 0);
6083         if (!status_win)
6084                 die("Failed to create status window");
6086         /* Enable keyboard mapping */
6087         keypad(status_win, TRUE);
6088         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6090 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6091         set_tabsize(opt_tab_size);
6092 #else
6093         TABSIZE = opt_tab_size;
6094 #endif
6096         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6097         if (term && !strcmp(term, "gnome-terminal")) {
6098                 /* In the gnome-terminal-emulator, the message from
6099                  * scrolling up one line when impossible followed by
6100                  * scrolling down one line causes corruption of the
6101                  * status line. This is fixed by calling wclear. */
6102                 use_scroll_status_wclear = TRUE;
6103                 use_scroll_redrawwin = FALSE;
6105         } else if (term && !strcmp(term, "xrvt-xpm")) {
6106                 /* No problems with full optimizations in xrvt-(unicode)
6107                  * and aterm. */
6108                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6110         } else {
6111                 /* When scrolling in (u)xterm the last line in the
6112                  * scrolling direction will update slowly. */
6113                 use_scroll_redrawwin = TRUE;
6114                 use_scroll_status_wclear = FALSE;
6115         }
6118 static int
6119 get_input(int prompt_position)
6121         struct view *view;
6122         int i, key, cursor_y, cursor_x;
6124         if (prompt_position)
6125                 input_mode = TRUE;
6127         while (TRUE) {
6128                 bool loading = FALSE;
6130                 foreach_view (view, i) {
6131                         update_view(view);
6132                         if (view_is_displayed(view) && view->has_scrolled &&
6133                             use_scroll_redrawwin)
6134                                 redrawwin(view->win);
6135                         view->has_scrolled = FALSE;
6136                         if (view->pipe)
6137                                 loading = TRUE;
6138                 }
6140                 /* Update the cursor position. */
6141                 if (prompt_position) {
6142                         getbegyx(status_win, cursor_y, cursor_x);
6143                         cursor_x = prompt_position;
6144                 } else {
6145                         view = display[current_view];
6146                         getbegyx(view->win, cursor_y, cursor_x);
6147                         cursor_x = view->width - 1;
6148                         cursor_y += view->lineno - view->offset;
6149                 }
6150                 setsyx(cursor_y, cursor_x);
6152                 /* Refresh, accept single keystroke of input */
6153                 doupdate();
6154                 nodelay(status_win, loading);
6155                 key = wgetch(status_win);
6157                 /* wgetch() with nodelay() enabled returns ERR when
6158                  * there's no input. */
6159                 if (key == ERR) {
6161                 } else if (key == KEY_RESIZE) {
6162                         int height, width;
6164                         getmaxyx(stdscr, height, width);
6166                         wresize(status_win, 1, width);
6167                         mvwin(status_win, height - 1, 0);
6168                         wnoutrefresh(status_win);
6169                         resize_display();
6170                         redraw_display(TRUE);
6172                 } else {
6173                         input_mode = FALSE;
6174                         return key;
6175                 }
6176         }
6179 static char *
6180 prompt_input(const char *prompt, input_handler handler, void *data)
6182         enum input_status status = INPUT_OK;
6183         static char buf[SIZEOF_STR];
6184         size_t pos = 0;
6186         buf[pos] = 0;
6188         while (status == INPUT_OK || status == INPUT_SKIP) {
6189                 int key;
6191                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6192                 wclrtoeol(status_win);
6194                 key = get_input(pos + 1);
6195                 switch (key) {
6196                 case KEY_RETURN:
6197                 case KEY_ENTER:
6198                 case '\n':
6199                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6200                         break;
6202                 case KEY_BACKSPACE:
6203                         if (pos > 0)
6204                                 buf[--pos] = 0;
6205                         else
6206                                 status = INPUT_CANCEL;
6207                         break;
6209                 case KEY_ESC:
6210                         status = INPUT_CANCEL;
6211                         break;
6213                 default:
6214                         if (pos >= sizeof(buf)) {
6215                                 report("Input string too long");
6216                                 return NULL;
6217                         }
6219                         status = handler(data, buf, key);
6220                         if (status == INPUT_OK)
6221                                 buf[pos++] = (char) key;
6222                 }
6223         }
6225         /* Clear the status window */
6226         status_empty = FALSE;
6227         report("");
6229         if (status == INPUT_CANCEL)
6230                 return NULL;
6232         buf[pos++] = 0;
6234         return buf;
6237 static enum input_status
6238 prompt_yesno_handler(void *data, char *buf, int c)
6240         if (c == 'y' || c == 'Y')
6241                 return INPUT_STOP;
6242         if (c == 'n' || c == 'N')
6243                 return INPUT_CANCEL;
6244         return INPUT_SKIP;
6247 static bool
6248 prompt_yesno(const char *prompt)
6250         char prompt2[SIZEOF_STR];
6252         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6253                 return FALSE;
6255         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6258 static enum input_status
6259 read_prompt_handler(void *data, char *buf, int c)
6261         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6264 static char *
6265 read_prompt(const char *prompt)
6267         return prompt_input(prompt, read_prompt_handler, NULL);
6270 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6272         enum input_status status = INPUT_OK;
6273         int size = 0;
6275         while (items[size].text)
6276                 size++;
6278         while (status == INPUT_OK) {
6279                 const struct menu_item *item = &items[*selected];
6280                 int key;
6281                 int i;
6283                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6284                           prompt, *selected + 1, size);
6285                 if (item->hotkey)
6286                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6287                 wprintw(status_win, "%s", item->text);
6288                 wclrtoeol(status_win);
6290                 key = get_input(COLS - 1);
6291                 switch (key) {
6292                 case KEY_RETURN:
6293                 case KEY_ENTER:
6294                 case '\n':
6295                         status = INPUT_STOP;
6296                         break;
6298                 case KEY_LEFT:
6299                 case KEY_UP:
6300                         *selected = *selected - 1;
6301                         if (*selected < 0)
6302                                 *selected = size - 1;
6303                         break;
6305                 case KEY_RIGHT:
6306                 case KEY_DOWN:
6307                         *selected = (*selected + 1) % size;
6308                         break;
6310                 case KEY_ESC:
6311                         status = INPUT_CANCEL;
6312                         break;
6314                 default:
6315                         for (i = 0; items[i].text; i++)
6316                                 if (items[i].hotkey == key) {
6317                                         *selected = i;
6318                                         status = INPUT_STOP;
6319                                         break;
6320                                 }
6321                 }
6322         }
6324         /* Clear the status window */
6325         status_empty = FALSE;
6326         report("");
6328         return status != INPUT_CANCEL;
6331 /*
6332  * Repository properties
6333  */
6335 static struct ref **refs = NULL;
6336 static size_t refs_size = 0;
6337 static struct ref *refs_head = NULL;
6339 static struct ref_list **ref_lists = NULL;
6340 static size_t ref_lists_size = 0;
6342 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6343 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6344 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6346 static int
6347 compare_refs(const void *ref1_, const void *ref2_)
6349         const struct ref *ref1 = *(const struct ref **)ref1_;
6350         const struct ref *ref2 = *(const struct ref **)ref2_;
6352         if (ref1->tag != ref2->tag)
6353                 return ref2->tag - ref1->tag;
6354         if (ref1->ltag != ref2->ltag)
6355                 return ref2->ltag - ref2->ltag;
6356         if (ref1->head != ref2->head)
6357                 return ref2->head - ref1->head;
6358         if (ref1->tracked != ref2->tracked)
6359                 return ref2->tracked - ref1->tracked;
6360         if (ref1->remote != ref2->remote)
6361                 return ref2->remote - ref1->remote;
6362         return strcmp(ref1->name, ref2->name);
6365 static void
6366 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6368         size_t i;
6370         for (i = 0; i < refs_size; i++)
6371                 if (!visitor(data, refs[i]))
6372                         break;
6375 static struct ref *
6376 get_ref_head()
6378         return refs_head;
6381 static struct ref_list *
6382 get_ref_list(const char *id)
6384         struct ref_list *list;
6385         size_t i;
6387         for (i = 0; i < ref_lists_size; i++)
6388                 if (!strcmp(id, ref_lists[i]->id))
6389                         return ref_lists[i];
6391         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6392                 return NULL;
6393         list = calloc(1, sizeof(*list));
6394         if (!list)
6395                 return NULL;
6397         for (i = 0; i < refs_size; i++) {
6398                 if (!strcmp(id, refs[i]->id) &&
6399                     realloc_refs_list(&list->refs, list->size, 1))
6400                         list->refs[list->size++] = refs[i];
6401         }
6403         if (!list->refs) {
6404                 free(list);
6405                 return NULL;
6406         }
6408         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6409         ref_lists[ref_lists_size++] = list;
6410         return list;
6413 static int
6414 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6416         struct ref *ref = NULL;
6417         bool tag = FALSE;
6418         bool ltag = FALSE;
6419         bool remote = FALSE;
6420         bool tracked = FALSE;
6421         bool head = FALSE;
6422         int from = 0, to = refs_size - 1;
6424         if (!prefixcmp(name, "refs/tags/")) {
6425                 if (!suffixcmp(name, namelen, "^{}")) {
6426                         namelen -= 3;
6427                         name[namelen] = 0;
6428                 } else {
6429                         ltag = TRUE;
6430                 }
6432                 tag = TRUE;
6433                 namelen -= STRING_SIZE("refs/tags/");
6434                 name    += STRING_SIZE("refs/tags/");
6436         } else if (!prefixcmp(name, "refs/remotes/")) {
6437                 remote = TRUE;
6438                 namelen -= STRING_SIZE("refs/remotes/");
6439                 name    += STRING_SIZE("refs/remotes/");
6440                 tracked  = !strcmp(opt_remote, name);
6442         } else if (!prefixcmp(name, "refs/heads/")) {
6443                 namelen -= STRING_SIZE("refs/heads/");
6444                 name    += STRING_SIZE("refs/heads/");
6445                 if (!strncmp(opt_head, name, namelen))
6446                         return OK;
6448         } else if (!strcmp(name, "HEAD")) {
6449                 head     = TRUE;
6450                 if (*opt_head) {
6451                         namelen  = strlen(opt_head);
6452                         name     = opt_head;
6453                 }
6454         }
6456         /* If we are reloading or it's an annotated tag, replace the
6457          * previous SHA1 with the resolved commit id; relies on the fact
6458          * git-ls-remote lists the commit id of an annotated tag right
6459          * before the commit id it points to. */
6460         while (from <= to) {
6461                 size_t pos = (to + from) / 2;
6462                 int cmp = strcmp(name, refs[pos]->name);
6464                 if (!cmp) {
6465                         ref = refs[pos];
6466                         break;
6467                 }
6469                 if (cmp < 0)
6470                         to = pos - 1;
6471                 else
6472                         from = pos + 1;
6473         }
6475         if (!ref) {
6476                 if (!realloc_refs(&refs, refs_size, 1))
6477                         return ERR;
6478                 ref = calloc(1, sizeof(*ref) + namelen);
6479                 if (!ref)
6480                         return ERR;
6481                 memmove(refs + from + 1, refs + from,
6482                         (refs_size - from) * sizeof(*refs));
6483                 refs[from] = ref;
6484                 strncpy(ref->name, name, namelen);
6485                 refs_size++;
6486         }
6488         ref->head = head;
6489         ref->tag = tag;
6490         ref->ltag = ltag;
6491         ref->remote = remote;
6492         ref->tracked = tracked;
6493         string_copy_rev(ref->id, id);
6495         if (head)
6496                 refs_head = ref;
6497         return OK;
6500 static int
6501 load_refs(void)
6503         const char *head_argv[] = {
6504                 "git", "symbolic-ref", "HEAD", NULL
6505         };
6506         static const char *ls_remote_argv[SIZEOF_ARG] = {
6507                 "git", "ls-remote", opt_git_dir, NULL
6508         };
6509         static bool init = FALSE;
6510         size_t i;
6512         if (!init) {
6513                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6514                         die("TIG_LS_REMOTE contains too many arguments");
6515                 init = TRUE;
6516         }
6518         if (!*opt_git_dir)
6519                 return OK;
6521         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6522             !prefixcmp(opt_head, "refs/heads/")) {
6523                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6525                 memmove(opt_head, offset, strlen(offset) + 1);
6526         }
6528         refs_head = NULL;
6529         for (i = 0; i < refs_size; i++)
6530                 refs[i]->id[0] = 0;
6532         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6533                 return ERR;
6535         /* Update the ref lists to reflect changes. */
6536         for (i = 0; i < ref_lists_size; i++) {
6537                 struct ref_list *list = ref_lists[i];
6538                 size_t old, new;
6540                 for (old = new = 0; old < list->size; old++)
6541                         if (!strcmp(list->id, list->refs[old]->id))
6542                                 list->refs[new++] = list->refs[old];
6543                 list->size = new;
6544         }
6546         return OK;
6549 static void
6550 set_remote_branch(const char *name, const char *value, size_t valuelen)
6552         if (!strcmp(name, ".remote")) {
6553                 string_ncopy(opt_remote, value, valuelen);
6555         } else if (*opt_remote && !strcmp(name, ".merge")) {
6556                 size_t from = strlen(opt_remote);
6558                 if (!prefixcmp(value, "refs/heads/"))
6559                         value += STRING_SIZE("refs/heads/");
6561                 if (!string_format_from(opt_remote, &from, "/%s", value))
6562                         opt_remote[0] = 0;
6563         }
6566 static void
6567 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6569         const char *argv[SIZEOF_ARG] = { name, "=" };
6570         int argc = 1 + (cmd == option_set_command);
6571         enum option_code error;
6573         if (!argv_from_string(argv, &argc, value))
6574                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6575         else
6576                 error = cmd(argc, argv);
6578         if (error != OPT_OK)
6579                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6582 static bool
6583 set_environment_variable(const char *name, const char *value)
6585         size_t len = strlen(name) + 1 + strlen(value) + 1;
6586         char *env = malloc(len);
6588         if (env &&
6589             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6590             putenv(env) == 0)
6591                 return TRUE;
6592         free(env);
6593         return FALSE;
6596 static void
6597 set_work_tree(const char *value)
6599         char cwd[SIZEOF_STR];
6601         if (!getcwd(cwd, sizeof(cwd)))
6602                 die("Failed to get cwd path: %s", strerror(errno));
6603         if (chdir(opt_git_dir) < 0)
6604                 die("Failed to chdir(%s): %s", strerror(errno));
6605         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6606                 die("Failed to get git path: %s", strerror(errno));
6607         if (chdir(cwd) < 0)
6608                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6609         if (chdir(value) < 0)
6610                 die("Failed to chdir(%s): %s", value, strerror(errno));
6611         if (!getcwd(cwd, sizeof(cwd)))
6612                 die("Failed to get cwd path: %s", strerror(errno));
6613         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6614                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6615         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6616                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6617         opt_is_inside_work_tree = TRUE;
6620 static int
6621 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6623         if (!strcmp(name, "i18n.commitencoding"))
6624                 string_ncopy(opt_encoding, value, valuelen);
6626         else if (!strcmp(name, "core.editor"))
6627                 string_ncopy(opt_editor, value, valuelen);
6629         else if (!strcmp(name, "core.worktree"))
6630                 set_work_tree(value);
6632         else if (!prefixcmp(name, "tig.color."))
6633                 set_repo_config_option(name + 10, value, option_color_command);
6635         else if (!prefixcmp(name, "tig.bind."))
6636                 set_repo_config_option(name + 9, value, option_bind_command);
6638         else if (!prefixcmp(name, "tig."))
6639                 set_repo_config_option(name + 4, value, option_set_command);
6641         else if (*opt_head && !prefixcmp(name, "branch.") &&
6642                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6643                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6645         return OK;
6648 static int
6649 load_git_config(void)
6651         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6653         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6656 static int
6657 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6659         if (!opt_git_dir[0]) {
6660                 string_ncopy(opt_git_dir, name, namelen);
6662         } else if (opt_is_inside_work_tree == -1) {
6663                 /* This can be 3 different values depending on the
6664                  * version of git being used. If git-rev-parse does not
6665                  * understand --is-inside-work-tree it will simply echo
6666                  * the option else either "true" or "false" is printed.
6667                  * Default to true for the unknown case. */
6668                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6670         } else if (*name == '.') {
6671                 string_ncopy(opt_cdup, name, namelen);
6673         } else {
6674                 string_ncopy(opt_prefix, name, namelen);
6675         }
6677         return OK;
6680 static int
6681 load_repo_info(void)
6683         const char *rev_parse_argv[] = {
6684                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6685                         "--show-cdup", "--show-prefix", NULL
6686         };
6688         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6692 /*
6693  * Main
6694  */
6696 static const char usage[] =
6697 "tig " TIG_VERSION " (" __DATE__ ")\n"
6698 "\n"
6699 "Usage: tig        [options] [revs] [--] [paths]\n"
6700 "   or: tig show   [options] [revs] [--] [paths]\n"
6701 "   or: tig blame  [options] [rev] [--] path\n"
6702 "   or: tig status\n"
6703 "   or: tig <      [git command output]\n"
6704 "\n"
6705 "Options:\n"
6706 "  -v, --version   Show version and exit\n"
6707 "  -h, --help      Show help message and exit";
6709 static void __NORETURN
6710 quit(int sig)
6712         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6713         if (cursed)
6714                 endwin();
6715         exit(0);
6718 static void __NORETURN
6719 die(const char *err, ...)
6721         va_list args;
6723         endwin();
6725         va_start(args, err);
6726         fputs("tig: ", stderr);
6727         vfprintf(stderr, err, args);
6728         fputs("\n", stderr);
6729         va_end(args);
6731         exit(1);
6734 static void
6735 warn(const char *msg, ...)
6737         va_list args;
6739         va_start(args, msg);
6740         fputs("tig warning: ", stderr);
6741         vfprintf(stderr, msg, args);
6742         fputs("\n", stderr);
6743         va_end(args);
6746 static int
6747 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6749         const char ***filter_args = data;
6751         return argv_append(filter_args, name) ? OK : ERR;
6754 static void
6755 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6757         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6758         const char **all_argv = NULL;
6760         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6761             !argv_append_array(&all_argv, argv) ||
6762             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6763                 die("Failed to split arguments");
6764         argv_free(all_argv);
6765         free(all_argv);
6768 static void
6769 filter_options(const char *argv[])
6771         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6772         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6773         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6776 static enum request
6777 parse_options(int argc, const char *argv[])
6779         enum request request = REQ_VIEW_MAIN;
6780         const char *subcommand;
6781         bool seen_dashdash = FALSE;
6782         const char **filter_argv = NULL;
6783         int i;
6785         if (!isatty(STDIN_FILENO))
6786                 return REQ_VIEW_PAGER;
6788         if (argc <= 1)
6789                 return REQ_VIEW_MAIN;
6791         subcommand = argv[1];
6792         if (!strcmp(subcommand, "status")) {
6793                 if (argc > 2)
6794                         warn("ignoring arguments after `%s'", subcommand);
6795                 return REQ_VIEW_STATUS;
6797         } else if (!strcmp(subcommand, "blame")) {
6798                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6799                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6800                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6802                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6803                         die("invalid number of options to blame\n\n%s", usage);
6805                 if (opt_rev_argv) {
6806                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6807                 }
6809                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6810                 return REQ_VIEW_BLAME;
6812         } else if (!strcmp(subcommand, "show")) {
6813                 request = REQ_VIEW_DIFF;
6815         } else {
6816                 subcommand = NULL;
6817         }
6819         for (i = 1 + !!subcommand; i < argc; i++) {
6820                 const char *opt = argv[i];
6822                 if (seen_dashdash) {
6823                         argv_append(&opt_file_argv, opt);
6824                         continue;
6826                 } else if (!strcmp(opt, "--")) {
6827                         seen_dashdash = TRUE;
6828                         continue;
6830                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6831                         printf("tig version %s\n", TIG_VERSION);
6832                         quit(0);
6834                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6835                         printf("%s\n", usage);
6836                         quit(0);
6838                 } else if (!strcmp(opt, "--all")) {
6839                         argv_append(&opt_rev_argv, opt);
6840                         continue;
6841                 }
6843                 if (!argv_append(&filter_argv, opt))
6844                         die("command too long");
6845         }
6847         if (filter_argv)
6848                 filter_options(filter_argv);
6850         return request;
6853 int
6854 main(int argc, const char *argv[])
6856         const char *codeset = "UTF-8";
6857         enum request request = parse_options(argc, argv);
6858         struct view *view;
6860         signal(SIGINT, quit);
6861         signal(SIGPIPE, SIG_IGN);
6863         if (setlocale(LC_ALL, "")) {
6864                 codeset = nl_langinfo(CODESET);
6865         }
6867         if (load_repo_info() == ERR)
6868                 die("Failed to load repo info.");
6870         if (load_options() == ERR)
6871                 die("Failed to load user config.");
6873         if (load_git_config() == ERR)
6874                 die("Failed to load repo config.");
6876         /* Require a git repository unless when running in pager mode. */
6877         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6878                 die("Not a git repository");
6880         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6881                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6882                 if (opt_iconv_in == ICONV_NONE)
6883                         die("Failed to initialize character set conversion");
6884         }
6886         if (codeset && strcmp(codeset, "UTF-8")) {
6887                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6888                 if (opt_iconv_out == ICONV_NONE)
6889                         die("Failed to initialize character set conversion");
6890         }
6892         if (load_refs() == ERR)
6893                 die("Failed to load refs.");
6895         init_display();
6897         while (view_driver(display[current_view], request)) {
6898                 int key = get_input(0);
6900                 view = display[current_view];
6901                 request = get_keybinding(view->keymap, key);
6903                 /* Some low-level request handling. This keeps access to
6904                  * status_win restricted. */
6905                 switch (request) {
6906                 case REQ_NONE:
6907                         report("Unknown key, press %s for help",
6908                                get_key(view->keymap, REQ_VIEW_HELP));
6909                         break;
6910                 case REQ_PROMPT:
6911                 {
6912                         char *cmd = read_prompt(":");
6914                         if (cmd && isdigit(*cmd)) {
6915                                 int lineno = view->lineno + 1;
6917                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6918                                         select_view_line(view, lineno - 1);
6919                                         report("");
6920                                 } else {
6921                                         report("Unable to parse '%s' as a line number", cmd);
6922                                 }
6924                         } else if (cmd) {
6925                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6926                                 const char *argv[SIZEOF_ARG] = { "git" };
6927                                 int argc = 1;
6929                                 /* When running random commands, initially show the
6930                                  * command in the title. However, it maybe later be
6931                                  * overwritten if a commit line is selected. */
6932                                 string_ncopy(next->ref, cmd, strlen(cmd));
6934                                 if (!argv_from_string(argv, &argc, cmd)) {
6935                                         report("Too many arguments");
6936                                 } else {
6937                                         open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6938                                 }
6939                         }
6941                         request = REQ_NONE;
6942                         break;
6943                 }
6944                 case REQ_SEARCH:
6945                 case REQ_SEARCH_BACK:
6946                 {
6947                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6948                         char *search = read_prompt(prompt);
6950                         if (search)
6951                                 string_ncopy(opt_search, search, strlen(search));
6952                         else if (*opt_search)
6953                                 request = request == REQ_SEARCH ?
6954                                         REQ_FIND_NEXT :
6955                                         REQ_FIND_PREV;
6956                         else
6957                                 request = REQ_NONE;
6958                         break;
6959                 }
6960                 default:
6961                         break;
6962                 }
6963         }
6965         quit(0);
6967         return 0;