Code

Move IO API to src/io.[ch]
[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"
17 static void __NORETURN die(const char *err, ...);
18 static void warn(const char *msg, ...);
19 static void report(const char *msg, ...);
22 struct ref {
23         char id[SIZEOF_REV];    /* Commit SHA1 ID */
24         unsigned int head:1;    /* Is it the current HEAD? */
25         unsigned int tag:1;     /* Is it a tag? */
26         unsigned int ltag:1;    /* If so, is the tag local? */
27         unsigned int remote:1;  /* Is it a remote ref? */
28         unsigned int tracked:1; /* Is it the remote for the current HEAD? */
29         char name[1];           /* Ref name; tag or head names are shortened. */
30 };
32 struct ref_list {
33         char id[SIZEOF_REV];    /* Commit SHA1 ID */
34         size_t size;            /* Number of refs. */
35         struct ref **refs;      /* References for this ID. */
36 };
38 static struct ref *get_ref_head();
39 static struct ref_list *get_ref_list(const char *id);
40 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
41 static int load_refs(void);
43 enum input_status {
44         INPUT_OK,
45         INPUT_SKIP,
46         INPUT_STOP,
47         INPUT_CANCEL
48 };
50 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
52 static char *prompt_input(const char *prompt, input_handler handler, void *data);
53 static bool prompt_yesno(const char *prompt);
55 struct menu_item {
56         int hotkey;
57         const char *text;
58         void *data;
59 };
61 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
63 #define DATE_INFO \
64         DATE_(NO), \
65         DATE_(DEFAULT), \
66         DATE_(LOCAL), \
67         DATE_(RELATIVE), \
68         DATE_(SHORT)
70 enum date {
71 #define DATE_(name) DATE_##name
72         DATE_INFO
73 #undef  DATE_
74 };
76 static const struct enum_map date_map[] = {
77 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
78         DATE_INFO
79 #undef  DATE_
80 };
82 struct time {
83         time_t sec;
84         int tz;
85 };
87 static inline int timecmp(const struct time *t1, const struct time *t2)
88 {
89         return t1->sec - t2->sec;
90 }
92 static const char *
93 mkdate(const struct time *time, enum date date)
94 {
95         static char buf[DATE_COLS + 1];
96         static const struct enum_map reldate[] = {
97                 { "second", 1,                  60 * 2 },
98                 { "minute", 60,                 60 * 60 * 2 },
99                 { "hour",   60 * 60,            60 * 60 * 24 * 2 },
100                 { "day",    60 * 60 * 24,       60 * 60 * 24 * 7 * 2 },
101                 { "week",   60 * 60 * 24 * 7,   60 * 60 * 24 * 7 * 5 },
102                 { "month",  60 * 60 * 24 * 30,  60 * 60 * 24 * 30 * 12 },
103         };
104         struct tm tm;
106         if (!date || !time || !time->sec)
107                 return "";
109         if (date == DATE_RELATIVE) {
110                 struct timeval now;
111                 time_t date = time->sec + time->tz;
112                 time_t seconds;
113                 int i;
115                 gettimeofday(&now, NULL);
116                 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
117                 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
118                         if (seconds >= reldate[i].value)
119                                 continue;
121                         seconds /= reldate[i].namelen;
122                         if (!string_format(buf, "%ld %s%s %s",
123                                            seconds, reldate[i].name,
124                                            seconds > 1 ? "s" : "",
125                                            now.tv_sec >= date ? "ago" : "ahead"))
126                                 break;
127                         return buf;
128                 }
129         }
131         if (date == DATE_LOCAL) {
132                 time_t date = time->sec + time->tz;
133                 localtime_r(&date, &tm);
134         }
135         else {
136                 gmtime_r(&time->sec, &tm);
137         }
138         return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
142 #define AUTHOR_VALUES \
143         AUTHOR_(NO), \
144         AUTHOR_(FULL), \
145         AUTHOR_(ABBREVIATED)
147 enum author {
148 #define AUTHOR_(name) AUTHOR_##name
149         AUTHOR_VALUES,
150 #undef  AUTHOR_
151         AUTHOR_DEFAULT = AUTHOR_FULL
152 };
154 static const struct enum_map author_map[] = {
155 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
156         AUTHOR_VALUES
157 #undef  AUTHOR_
158 };
160 static const char *
161 get_author_initials(const char *author)
163         static char initials[AUTHOR_COLS * 6 + 1];
164         size_t pos = 0;
165         const char *end = strchr(author, '\0');
167 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
169         memset(initials, 0, sizeof(initials));
170         while (author < end) {
171                 unsigned char bytes;
172                 size_t i;
174                 while (is_initial_sep(*author))
175                         author++;
177                 bytes = utf8_char_length(author, end);
178                 if (bytes < sizeof(initials) - 1 - pos) {
179                         while (bytes--) {
180                                 initials[pos++] = *author++;
181                         }
182                 }
184                 for (i = pos; author < end && !is_initial_sep(*author); author++) {
185                         if (i < sizeof(initials) - 1)
186                                 initials[i++] = *author;
187                 }
189                 initials[i++] = 0;
190         }
192         return initials;
196 /*
197  * User requests
198  */
200 #define REQ_INFO \
201         /* XXX: Keep the view request first and in sync with views[]. */ \
202         REQ_GROUP("View switching") \
203         REQ_(VIEW_MAIN,         "Show main view"), \
204         REQ_(VIEW_DIFF,         "Show diff view"), \
205         REQ_(VIEW_LOG,          "Show log view"), \
206         REQ_(VIEW_TREE,         "Show tree view"), \
207         REQ_(VIEW_BLOB,         "Show blob view"), \
208         REQ_(VIEW_BLAME,        "Show blame view"), \
209         REQ_(VIEW_BRANCH,       "Show branch view"), \
210         REQ_(VIEW_HELP,         "Show help page"), \
211         REQ_(VIEW_PAGER,        "Show pager view"), \
212         REQ_(VIEW_STATUS,       "Show status view"), \
213         REQ_(VIEW_STAGE,        "Show stage view"), \
214         \
215         REQ_GROUP("View manipulation") \
216         REQ_(ENTER,             "Enter current line and scroll"), \
217         REQ_(NEXT,              "Move to next"), \
218         REQ_(PREVIOUS,          "Move to previous"), \
219         REQ_(PARENT,            "Move to parent"), \
220         REQ_(VIEW_NEXT,         "Move focus to next view"), \
221         REQ_(REFRESH,           "Reload and refresh"), \
222         REQ_(MAXIMIZE,          "Maximize the current view"), \
223         REQ_(VIEW_CLOSE,        "Close the current view"), \
224         REQ_(QUIT,              "Close all views and quit"), \
225         \
226         REQ_GROUP("View specific requests") \
227         REQ_(STATUS_UPDATE,     "Update file status"), \
228         REQ_(STATUS_REVERT,     "Revert file changes"), \
229         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
230         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
231         \
232         REQ_GROUP("Cursor navigation") \
233         REQ_(MOVE_UP,           "Move cursor one line up"), \
234         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
235         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
236         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
237         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
238         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
239         \
240         REQ_GROUP("Scrolling") \
241         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
242         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
243         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
244         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
245         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
246         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
247         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
248         \
249         REQ_GROUP("Searching") \
250         REQ_(SEARCH,            "Search the view"), \
251         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
252         REQ_(FIND_NEXT,         "Find next search match"), \
253         REQ_(FIND_PREV,         "Find previous search match"), \
254         \
255         REQ_GROUP("Option manipulation") \
256         REQ_(OPTIONS,           "Open option menu"), \
257         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
258         REQ_(TOGGLE_DATE,       "Toggle date display"), \
259         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
260         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
261         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
262         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
263         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
264         \
265         REQ_GROUP("Misc") \
266         REQ_(PROMPT,            "Bring up the prompt"), \
267         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
268         REQ_(SHOW_VERSION,      "Show version information"), \
269         REQ_(STOP_LOADING,      "Stop all loading views"), \
270         REQ_(EDIT,              "Open in editor"), \
271         REQ_(NONE,              "Do nothing")
274 /* User action requests. */
275 enum request {
276 #define REQ_GROUP(help)
277 #define REQ_(req, help) REQ_##req
279         /* Offset all requests to avoid conflicts with ncurses getch values. */
280         REQ_UNKNOWN = KEY_MAX + 1,
281         REQ_OFFSET,
282         REQ_INFO
284 #undef  REQ_GROUP
285 #undef  REQ_
286 };
288 struct request_info {
289         enum request request;
290         const char *name;
291         int namelen;
292         const char *help;
293 };
295 static const struct request_info req_info[] = {
296 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
297 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
298         REQ_INFO
299 #undef  REQ_GROUP
300 #undef  REQ_
301 };
303 static enum request
304 get_request(const char *name)
306         int namelen = strlen(name);
307         int i;
309         for (i = 0; i < ARRAY_SIZE(req_info); i++)
310                 if (enum_equals(req_info[i], name, namelen))
311                         return req_info[i].request;
313         return REQ_UNKNOWN;
317 /*
318  * Options
319  */
321 /* Option and state variables. */
322 static enum date opt_date               = DATE_DEFAULT;
323 static enum author opt_author           = AUTHOR_DEFAULT;
324 static bool opt_line_number             = FALSE;
325 static bool opt_line_graphics           = TRUE;
326 static bool opt_rev_graph               = FALSE;
327 static bool opt_show_refs               = TRUE;
328 static bool opt_untracked_dirs_content  = TRUE;
329 static int opt_num_interval             = 5;
330 static double opt_hscroll               = 0.50;
331 static double opt_scale_split_view      = 2.0 / 3.0;
332 static int opt_tab_size                 = 8;
333 static int opt_author_cols              = AUTHOR_COLS;
334 static char opt_path[SIZEOF_STR]        = "";
335 static char opt_file[SIZEOF_STR]        = "";
336 static char opt_ref[SIZEOF_REF]         = "";
337 static char opt_head[SIZEOF_REF]        = "";
338 static char opt_remote[SIZEOF_REF]      = "";
339 static char opt_encoding[20]            = "UTF-8";
340 static iconv_t opt_iconv_in             = ICONV_NONE;
341 static iconv_t opt_iconv_out            = ICONV_NONE;
342 static char opt_search[SIZEOF_STR]      = "";
343 static char opt_cdup[SIZEOF_STR]        = "";
344 static char opt_prefix[SIZEOF_STR]      = "";
345 static char opt_git_dir[SIZEOF_STR]     = "";
346 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
347 static char opt_editor[SIZEOF_STR]      = "";
348 static FILE *opt_tty                    = NULL;
349 static const char **opt_diff_argv       = NULL;
350 static const char **opt_rev_argv        = NULL;
351 static const char **opt_file_argv       = NULL;
353 #define is_initial_commit()     (!get_ref_head())
354 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
357 /*
358  * Line-oriented content detection.
359  */
361 #define LINE_INFO \
362 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
363 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
364 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
365 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
366 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
367 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
368 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
369 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
370 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
371 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
372 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
373 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
374 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
375 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
376 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
377 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
378 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
379 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
380 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
381 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
382 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
383 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
384 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
385 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
386 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
387 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
388 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
389 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
390 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
391 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
392 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
393 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
394 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
395 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
396 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
397 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
398 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
399 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
400 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
401 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
402 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
403 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
404 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
405 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
406 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
407 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
408 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
409 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
410 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
411 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
412 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
413 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
414 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
415 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
416 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
417 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
418 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
419 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
420 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0)
422 enum line_type {
423 #define LINE(type, line, fg, bg, attr) \
424         LINE_##type
425         LINE_INFO,
426         LINE_NONE
427 #undef  LINE
428 };
430 struct line_info {
431         const char *name;       /* Option name. */
432         int namelen;            /* Size of option name. */
433         const char *line;       /* The start of line to match. */
434         int linelen;            /* Size of string to match. */
435         int fg, bg, attr;       /* Color and text attributes for the lines. */
436 };
438 static struct line_info line_info[] = {
439 #define LINE(type, line, fg, bg, attr) \
440         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
441         LINE_INFO
442 #undef  LINE
443 };
445 static enum line_type
446 get_line_type(const char *line)
448         int linelen = strlen(line);
449         enum line_type type;
451         for (type = 0; type < ARRAY_SIZE(line_info); type++)
452                 /* Case insensitive search matches Signed-off-by lines better. */
453                 if (linelen >= line_info[type].linelen &&
454                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
455                         return type;
457         return LINE_DEFAULT;
460 static inline int
461 get_line_attr(enum line_type type)
463         assert(type < ARRAY_SIZE(line_info));
464         return COLOR_PAIR(type) | line_info[type].attr;
467 static struct line_info *
468 get_line_info(const char *name)
470         size_t namelen = strlen(name);
471         enum line_type type;
473         for (type = 0; type < ARRAY_SIZE(line_info); type++)
474                 if (enum_equals(line_info[type], name, namelen))
475                         return &line_info[type];
477         return NULL;
480 static void
481 init_colors(void)
483         int default_bg = line_info[LINE_DEFAULT].bg;
484         int default_fg = line_info[LINE_DEFAULT].fg;
485         enum line_type type;
487         start_color();
489         if (assume_default_colors(default_fg, default_bg) == ERR) {
490                 default_bg = COLOR_BLACK;
491                 default_fg = COLOR_WHITE;
492         }
494         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
495                 struct line_info *info = &line_info[type];
496                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
497                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
499                 init_pair(type, fg, bg);
500         }
503 struct line {
504         enum line_type type;
506         /* State flags */
507         unsigned int selected:1;
508         unsigned int dirty:1;
509         unsigned int cleareol:1;
510         unsigned int other:16;
512         void *data;             /* User data */
513 };
516 /*
517  * Keys
518  */
520 struct keybinding {
521         int alias;
522         enum request request;
523 };
525 static struct keybinding default_keybindings[] = {
526         /* View switching */
527         { 'm',          REQ_VIEW_MAIN },
528         { 'd',          REQ_VIEW_DIFF },
529         { 'l',          REQ_VIEW_LOG },
530         { 't',          REQ_VIEW_TREE },
531         { 'f',          REQ_VIEW_BLOB },
532         { 'B',          REQ_VIEW_BLAME },
533         { 'H',          REQ_VIEW_BRANCH },
534         { 'p',          REQ_VIEW_PAGER },
535         { 'h',          REQ_VIEW_HELP },
536         { 'S',          REQ_VIEW_STATUS },
537         { 'c',          REQ_VIEW_STAGE },
539         /* View manipulation */
540         { 'q',          REQ_VIEW_CLOSE },
541         { KEY_TAB,      REQ_VIEW_NEXT },
542         { KEY_RETURN,   REQ_ENTER },
543         { KEY_UP,       REQ_PREVIOUS },
544         { KEY_CTL('P'), REQ_PREVIOUS },
545         { KEY_DOWN,     REQ_NEXT },
546         { KEY_CTL('N'), REQ_NEXT },
547         { 'R',          REQ_REFRESH },
548         { KEY_F(5),     REQ_REFRESH },
549         { 'O',          REQ_MAXIMIZE },
551         /* Cursor navigation */
552         { 'k',          REQ_MOVE_UP },
553         { 'j',          REQ_MOVE_DOWN },
554         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
555         { KEY_END,      REQ_MOVE_LAST_LINE },
556         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
557         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
558         { ' ',          REQ_MOVE_PAGE_DOWN },
559         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
560         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
561         { 'b',          REQ_MOVE_PAGE_UP },
562         { '-',          REQ_MOVE_PAGE_UP },
564         /* Scrolling */
565         { '|',          REQ_SCROLL_FIRST_COL },
566         { KEY_LEFT,     REQ_SCROLL_LEFT },
567         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
568         { KEY_IC,       REQ_SCROLL_LINE_UP },
569         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
570         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
571         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
572         { 'w',          REQ_SCROLL_PAGE_UP },
573         { 's',          REQ_SCROLL_PAGE_DOWN },
575         /* Searching */
576         { '/',          REQ_SEARCH },
577         { '?',          REQ_SEARCH_BACK },
578         { 'n',          REQ_FIND_NEXT },
579         { 'N',          REQ_FIND_PREV },
581         /* Misc */
582         { 'Q',          REQ_QUIT },
583         { 'z',          REQ_STOP_LOADING },
584         { 'v',          REQ_SHOW_VERSION },
585         { 'r',          REQ_SCREEN_REDRAW },
586         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
587         { 'o',          REQ_OPTIONS },
588         { '.',          REQ_TOGGLE_LINENO },
589         { 'D',          REQ_TOGGLE_DATE },
590         { 'A',          REQ_TOGGLE_AUTHOR },
591         { 'g',          REQ_TOGGLE_REV_GRAPH },
592         { 'F',          REQ_TOGGLE_REFS },
593         { 'I',          REQ_TOGGLE_SORT_ORDER },
594         { 'i',          REQ_TOGGLE_SORT_FIELD },
595         { ':',          REQ_PROMPT },
596         { 'u',          REQ_STATUS_UPDATE },
597         { '!',          REQ_STATUS_REVERT },
598         { 'M',          REQ_STATUS_MERGE },
599         { '@',          REQ_STAGE_NEXT },
600         { ',',          REQ_PARENT },
601         { 'e',          REQ_EDIT },
602 };
604 #define KEYMAP_INFO \
605         KEYMAP_(GENERIC), \
606         KEYMAP_(MAIN), \
607         KEYMAP_(DIFF), \
608         KEYMAP_(LOG), \
609         KEYMAP_(TREE), \
610         KEYMAP_(BLOB), \
611         KEYMAP_(BLAME), \
612         KEYMAP_(BRANCH), \
613         KEYMAP_(PAGER), \
614         KEYMAP_(HELP), \
615         KEYMAP_(STATUS), \
616         KEYMAP_(STAGE)
618 enum keymap {
619 #define KEYMAP_(name) KEYMAP_##name
620         KEYMAP_INFO
621 #undef  KEYMAP_
622 };
624 static const struct enum_map keymap_table[] = {
625 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
626         KEYMAP_INFO
627 #undef  KEYMAP_
628 };
630 #define set_keymap(map, name) map_enum(map, keymap_table, name)
632 struct keybinding_table {
633         struct keybinding *data;
634         size_t size;
635 };
637 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
639 static void
640 add_keybinding(enum keymap keymap, enum request request, int key)
642         struct keybinding_table *table = &keybindings[keymap];
643         size_t i;
645         for (i = 0; i < keybindings[keymap].size; i++) {
646                 if (keybindings[keymap].data[i].alias == key) {
647                         keybindings[keymap].data[i].request = request;
648                         return;
649                 }
650         }
652         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
653         if (!table->data)
654                 die("Failed to allocate keybinding");
655         table->data[table->size].alias = key;
656         table->data[table->size++].request = request;
658         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
659                 int i;
661                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
662                         if (default_keybindings[i].alias == key)
663                                 default_keybindings[i].request = REQ_NONE;
664         }
667 /* Looks for a key binding first in the given map, then in the generic map, and
668  * lastly in the default keybindings. */
669 static enum request
670 get_keybinding(enum keymap keymap, int key)
672         size_t i;
674         for (i = 0; i < keybindings[keymap].size; i++)
675                 if (keybindings[keymap].data[i].alias == key)
676                         return keybindings[keymap].data[i].request;
678         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
679                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
680                         return keybindings[KEYMAP_GENERIC].data[i].request;
682         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
683                 if (default_keybindings[i].alias == key)
684                         return default_keybindings[i].request;
686         return (enum request) key;
690 struct key {
691         const char *name;
692         int value;
693 };
695 static const struct key key_table[] = {
696         { "Enter",      KEY_RETURN },
697         { "Space",      ' ' },
698         { "Backspace",  KEY_BACKSPACE },
699         { "Tab",        KEY_TAB },
700         { "Escape",     KEY_ESC },
701         { "Left",       KEY_LEFT },
702         { "Right",      KEY_RIGHT },
703         { "Up",         KEY_UP },
704         { "Down",       KEY_DOWN },
705         { "Insert",     KEY_IC },
706         { "Delete",     KEY_DC },
707         { "Hash",       '#' },
708         { "Home",       KEY_HOME },
709         { "End",        KEY_END },
710         { "PageUp",     KEY_PPAGE },
711         { "PageDown",   KEY_NPAGE },
712         { "F1",         KEY_F(1) },
713         { "F2",         KEY_F(2) },
714         { "F3",         KEY_F(3) },
715         { "F4",         KEY_F(4) },
716         { "F5",         KEY_F(5) },
717         { "F6",         KEY_F(6) },
718         { "F7",         KEY_F(7) },
719         { "F8",         KEY_F(8) },
720         { "F9",         KEY_F(9) },
721         { "F10",        KEY_F(10) },
722         { "F11",        KEY_F(11) },
723         { "F12",        KEY_F(12) },
724 };
726 static int
727 get_key_value(const char *name)
729         int i;
731         for (i = 0; i < ARRAY_SIZE(key_table); i++)
732                 if (!strcasecmp(key_table[i].name, name))
733                         return key_table[i].value;
735         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
736                 return (int)name[1] & 0x1f;
737         if (strlen(name) == 1 && isprint(*name))
738                 return (int) *name;
739         return ERR;
742 static const char *
743 get_key_name(int key_value)
745         static char key_char[] = "'X'\0";
746         const char *seq = NULL;
747         int key;
749         for (key = 0; key < ARRAY_SIZE(key_table); key++)
750                 if (key_table[key].value == key_value)
751                         seq = key_table[key].name;
753         if (seq == NULL && key_value < 0x7f) {
754                 char *s = key_char + 1;
756                 if (key_value >= 0x20) {
757                         *s++ = key_value;
758                 } else {
759                         *s++ = '^';
760                         *s++ = 0x40 | (key_value & 0x1f);
761                 }
762                 *s++ = '\'';
763                 *s++ = '\0';
764                 seq = key_char;
765         }
767         return seq ? seq : "(no key)";
770 static bool
771 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
773         const char *sep = *pos > 0 ? ", " : "";
774         const char *keyname = get_key_name(keybinding->alias);
776         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
779 static bool
780 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
781                            enum keymap keymap, bool all)
783         int i;
785         for (i = 0; i < keybindings[keymap].size; i++) {
786                 if (keybindings[keymap].data[i].request == request) {
787                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
788                                 return FALSE;
789                         if (!all)
790                                 break;
791                 }
792         }
794         return TRUE;
797 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
799 static const char *
800 get_keys(enum keymap keymap, enum request request, bool all)
802         static char buf[BUFSIZ];
803         size_t pos = 0;
804         int i;
806         buf[pos] = 0;
808         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
809                 return "Too many keybindings!";
810         if (pos > 0 && !all)
811                 return buf;
813         if (keymap != KEYMAP_GENERIC) {
814                 /* Only the generic keymap includes the default keybindings when
815                  * listing all keys. */
816                 if (all)
817                         return buf;
819                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
820                         return "Too many keybindings!";
821                 if (pos)
822                         return buf;
823         }
825         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
826                 if (default_keybindings[i].request == request) {
827                         if (!append_key(buf, &pos, &default_keybindings[i]))
828                                 return "Too many keybindings!";
829                         if (!all)
830                                 return buf;
831                 }
832         }
834         return buf;
837 struct run_request {
838         enum keymap keymap;
839         int key;
840         const char **argv;
841 };
843 static struct run_request *run_request;
844 static size_t run_requests;
846 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
848 static enum request
849 add_run_request(enum keymap keymap, int key, const char **argv)
851         struct run_request *req;
853         if (!realloc_run_requests(&run_request, run_requests, 1))
854                 return REQ_NONE;
856         req = &run_request[run_requests];
857         req->keymap = keymap;
858         req->key = key;
859         req->argv = NULL;
861         if (!argv_copy(&req->argv, argv))
862                 return REQ_NONE;
864         return REQ_NONE + ++run_requests;
867 static struct run_request *
868 get_run_request(enum request request)
870         if (request <= REQ_NONE)
871                 return NULL;
872         return &run_request[request - REQ_NONE - 1];
875 static void
876 add_builtin_run_requests(void)
878         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
879         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
880         const char *commit[] = { "git", "commit", NULL };
881         const char *gc[] = { "git", "gc", NULL };
882         struct run_request reqs[] = {
883                 { KEYMAP_MAIN,    'C', cherry_pick },
884                 { KEYMAP_STATUS,  'C', commit },
885                 { KEYMAP_BRANCH,  'C', checkout },
886                 { KEYMAP_GENERIC, 'G', gc },
887         };
888         int i;
890         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
891                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
893                 if (req != reqs[i].key)
894                         continue;
895                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
896                 if (req != REQ_NONE)
897                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
898         }
901 /*
902  * User config file handling.
903  */
905 #define OPT_ERR_INFO \
906         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
907         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
908         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
909         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
910         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
911         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
912         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
913         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
914         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
915         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
916         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
917         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
918         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
919         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
920         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
921         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
923 enum option_code {
924 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
925         OPT_ERR_INFO
926 #undef  OPT_ERR_
927         OPT_OK
928 };
930 static const char *option_errors[] = {
931 #define OPT_ERR_(name, msg) msg
932         OPT_ERR_INFO
933 #undef  OPT_ERR_
934 };
936 static const struct enum_map color_map[] = {
937 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
938         COLOR_MAP(DEFAULT),
939         COLOR_MAP(BLACK),
940         COLOR_MAP(BLUE),
941         COLOR_MAP(CYAN),
942         COLOR_MAP(GREEN),
943         COLOR_MAP(MAGENTA),
944         COLOR_MAP(RED),
945         COLOR_MAP(WHITE),
946         COLOR_MAP(YELLOW),
947 };
949 static const struct enum_map attr_map[] = {
950 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
951         ATTR_MAP(NORMAL),
952         ATTR_MAP(BLINK),
953         ATTR_MAP(BOLD),
954         ATTR_MAP(DIM),
955         ATTR_MAP(REVERSE),
956         ATTR_MAP(STANDOUT),
957         ATTR_MAP(UNDERLINE),
958 };
960 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
962 static enum option_code
963 parse_step(double *opt, const char *arg)
965         *opt = atoi(arg);
966         if (!strchr(arg, '%'))
967                 return OPT_OK;
969         /* "Shift down" so 100% and 1 does not conflict. */
970         *opt = (*opt - 1) / 100;
971         if (*opt >= 1.0) {
972                 *opt = 0.99;
973                 return OPT_ERR_INVALID_STEP_VALUE;
974         }
975         if (*opt < 0.0) {
976                 *opt = 1;
977                 return OPT_ERR_INVALID_STEP_VALUE;
978         }
979         return OPT_OK;
982 static enum option_code
983 parse_int(int *opt, const char *arg, int min, int max)
985         int value = atoi(arg);
987         if (min <= value && value <= max) {
988                 *opt = value;
989                 return OPT_OK;
990         }
992         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
995 static bool
996 set_color(int *color, const char *name)
998         if (map_enum(color, color_map, name))
999                 return TRUE;
1000         if (!prefixcmp(name, "color"))
1001                 return parse_int(color, name + 5, 0, 255) == OK;
1002         return FALSE;
1005 /* Wants: object fgcolor bgcolor [attribute] */
1006 static enum option_code
1007 option_color_command(int argc, const char *argv[])
1009         struct line_info *info;
1011         if (argc < 3)
1012                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1014         info = get_line_info(argv[0]);
1015         if (!info) {
1016                 static const struct enum_map obsolete[] = {
1017                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1018                         ENUM_MAP("main-date",   LINE_DATE),
1019                         ENUM_MAP("main-author", LINE_AUTHOR),
1020                 };
1021                 int index;
1023                 if (!map_enum(&index, obsolete, argv[0]))
1024                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1025                 info = &line_info[index];
1026         }
1028         if (!set_color(&info->fg, argv[1]) ||
1029             !set_color(&info->bg, argv[2]))
1030                 return OPT_ERR_UNKNOWN_COLOR;
1032         info->attr = 0;
1033         while (argc-- > 3) {
1034                 int attr;
1036                 if (!set_attribute(&attr, argv[argc]))
1037                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1038                 info->attr |= attr;
1039         }
1041         return OPT_OK;
1044 static enum option_code
1045 parse_bool(bool *opt, const char *arg)
1047         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1048                 ? TRUE : FALSE;
1049         return OPT_OK;
1052 static enum option_code
1053 parse_enum_do(unsigned int *opt, const char *arg,
1054               const struct enum_map *map, size_t map_size)
1056         bool is_true;
1058         assert(map_size > 1);
1060         if (map_enum_do(map, map_size, (int *) opt, arg))
1061                 return OPT_OK;
1063         parse_bool(&is_true, arg);
1064         *opt = is_true ? map[1].value : map[0].value;
1065         return OPT_OK;
1068 #define parse_enum(opt, arg, map) \
1069         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1071 static enum option_code
1072 parse_string(char *opt, const char *arg, size_t optsize)
1074         int arglen = strlen(arg);
1076         switch (arg[0]) {
1077         case '\"':
1078         case '\'':
1079                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1080                         return OPT_ERR_UNMATCHED_QUOTATION;
1081                 arg += 1; arglen -= 2;
1082         default:
1083                 string_ncopy_do(opt, optsize, arg, arglen);
1084                 return OPT_OK;
1085         }
1088 /* Wants: name = value */
1089 static enum option_code
1090 option_set_command(int argc, const char *argv[])
1092         if (argc != 3)
1093                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1095         if (strcmp(argv[1], "="))
1096                 return OPT_ERR_NO_VALUE_ASSIGNED;
1098         if (!strcmp(argv[0], "show-author"))
1099                 return parse_enum(&opt_author, argv[2], author_map);
1101         if (!strcmp(argv[0], "show-date"))
1102                 return parse_enum(&opt_date, argv[2], date_map);
1104         if (!strcmp(argv[0], "show-rev-graph"))
1105                 return parse_bool(&opt_rev_graph, argv[2]);
1107         if (!strcmp(argv[0], "show-refs"))
1108                 return parse_bool(&opt_show_refs, argv[2]);
1110         if (!strcmp(argv[0], "show-line-numbers"))
1111                 return parse_bool(&opt_line_number, argv[2]);
1113         if (!strcmp(argv[0], "line-graphics"))
1114                 return parse_bool(&opt_line_graphics, argv[2]);
1116         if (!strcmp(argv[0], "line-number-interval"))
1117                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1119         if (!strcmp(argv[0], "author-width"))
1120                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1122         if (!strcmp(argv[0], "horizontal-scroll"))
1123                 return parse_step(&opt_hscroll, argv[2]);
1125         if (!strcmp(argv[0], "split-view-height"))
1126                 return parse_step(&opt_scale_split_view, argv[2]);
1128         if (!strcmp(argv[0], "tab-size"))
1129                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1131         if (!strcmp(argv[0], "commit-encoding"))
1132                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1134         if (!strcmp(argv[0], "status-untracked-dirs"))
1135                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1137         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1140 /* Wants: mode request key */
1141 static enum option_code
1142 option_bind_command(int argc, const char *argv[])
1144         enum request request;
1145         int keymap = -1;
1146         int key;
1148         if (argc < 3)
1149                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1151         if (!set_keymap(&keymap, argv[0]))
1152                 return OPT_ERR_UNKNOWN_KEY_MAP;
1154         key = get_key_value(argv[1]);
1155         if (key == ERR)
1156                 return OPT_ERR_UNKNOWN_KEY;
1158         request = get_request(argv[2]);
1159         if (request == REQ_UNKNOWN) {
1160                 static const struct enum_map obsolete[] = {
1161                         ENUM_MAP("cherry-pick",         REQ_NONE),
1162                         ENUM_MAP("screen-resize",       REQ_NONE),
1163                         ENUM_MAP("tree-parent",         REQ_PARENT),
1164                 };
1165                 int alias;
1167                 if (map_enum(&alias, obsolete, argv[2])) {
1168                         if (alias != REQ_NONE)
1169                                 add_keybinding(keymap, alias, key);
1170                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1171                 }
1172         }
1173         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1174                 request = add_run_request(keymap, key, argv + 2);
1175         if (request == REQ_UNKNOWN)
1176                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1178         add_keybinding(keymap, request, key);
1180         return OPT_OK;
1183 static enum option_code
1184 set_option(const char *opt, char *value)
1186         const char *argv[SIZEOF_ARG];
1187         int argc = 0;
1189         if (!argv_from_string(argv, &argc, value))
1190                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1192         if (!strcmp(opt, "color"))
1193                 return option_color_command(argc, argv);
1195         if (!strcmp(opt, "set"))
1196                 return option_set_command(argc, argv);
1198         if (!strcmp(opt, "bind"))
1199                 return option_bind_command(argc, argv);
1201         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1204 struct config_state {
1205         int lineno;
1206         bool errors;
1207 };
1209 static int
1210 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1212         struct config_state *config = data;
1213         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1215         config->lineno++;
1217         /* Check for comment markers, since read_properties() will
1218          * only ensure opt and value are split at first " \t". */
1219         optlen = strcspn(opt, "#");
1220         if (optlen == 0)
1221                 return OK;
1223         if (opt[optlen] == 0) {
1224                 /* Look for comment endings in the value. */
1225                 size_t len = strcspn(value, "#");
1227                 if (len < valuelen) {
1228                         valuelen = len;
1229                         value[valuelen] = 0;
1230                 }
1232                 status = set_option(opt, value);
1233         }
1235         if (status != OPT_OK) {
1236                 warn("Error on line %d, near '%.*s': %s",
1237                      config->lineno, (int) optlen, opt, option_errors[status]);
1238                 config->errors = TRUE;
1239         }
1241         /* Always keep going if errors are encountered. */
1242         return OK;
1245 static void
1246 load_option_file(const char *path)
1248         struct config_state config = { 0, FALSE };
1249         struct io io;
1251         /* It's OK that the file doesn't exist. */
1252         if (!io_open(&io, "%s", path))
1253                 return;
1255         if (io_load(&io, " \t", read_option, &config) == ERR ||
1256             config.errors == TRUE)
1257                 warn("Errors while loading %s.", path);
1260 static int
1261 load_options(void)
1263         const char *home = getenv("HOME");
1264         const char *tigrc_user = getenv("TIGRC_USER");
1265         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1266         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1267         char buf[SIZEOF_STR];
1269         if (!tigrc_system)
1270                 tigrc_system = SYSCONFDIR "/tigrc";
1271         load_option_file(tigrc_system);
1273         if (!tigrc_user) {
1274                 if (!home || !string_format(buf, "%s/.tigrc", home))
1275                         return ERR;
1276                 tigrc_user = buf;
1277         }
1278         load_option_file(tigrc_user);
1280         /* Add _after_ loading config files to avoid adding run requests
1281          * that conflict with keybindings. */
1282         add_builtin_run_requests();
1284         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1285                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1286                 int argc = 0;
1288                 if (!string_format(buf, "%s", tig_diff_opts) ||
1289                     !argv_from_string(diff_opts, &argc, buf))
1290                         die("TIG_DIFF_OPTS contains too many arguments");
1291                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1292                         die("Failed to format TIG_DIFF_OPTS arguments");
1293         }
1295         return OK;
1299 /*
1300  * The viewer
1301  */
1303 struct view;
1304 struct view_ops;
1306 /* The display array of active views and the index of the current view. */
1307 static struct view *display[2];
1308 static WINDOW *display_win[2];
1309 static WINDOW *display_title[2];
1310 static unsigned int current_view;
1312 #define foreach_displayed_view(view, i) \
1313         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1315 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1317 /* Current head and commit ID */
1318 static char ref_blob[SIZEOF_REF]        = "";
1319 static char ref_commit[SIZEOF_REF]      = "HEAD";
1320 static char ref_head[SIZEOF_REF]        = "HEAD";
1321 static char ref_branch[SIZEOF_REF]      = "";
1323 enum view_type {
1324         VIEW_MAIN,
1325         VIEW_DIFF,
1326         VIEW_LOG,
1327         VIEW_TREE,
1328         VIEW_BLOB,
1329         VIEW_BLAME,
1330         VIEW_BRANCH,
1331         VIEW_HELP,
1332         VIEW_PAGER,
1333         VIEW_STATUS,
1334         VIEW_STAGE,
1335 };
1337 struct view {
1338         enum view_type type;    /* View type */
1339         const char *name;       /* View name */
1340         const char *cmd_env;    /* Command line set via environment */
1341         const char *id;         /* Points to either of ref_{head,commit,blob} */
1343         struct view_ops *ops;   /* View operations */
1345         enum keymap keymap;     /* What keymap does this view have */
1346         bool git_dir;           /* Whether the view requires a git directory. */
1348         char ref[SIZEOF_REF];   /* Hovered commit reference */
1349         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1351         int height, width;      /* The width and height of the main window */
1352         WINDOW *win;            /* The main window */
1354         /* Navigation */
1355         unsigned long offset;   /* Offset of the window top */
1356         unsigned long yoffset;  /* Offset from the window side. */
1357         unsigned long lineno;   /* Current line number */
1358         unsigned long p_offset; /* Previous offset of the window top */
1359         unsigned long p_yoffset;/* Previous offset from the window side */
1360         unsigned long p_lineno; /* Previous current line number */
1361         bool p_restore;         /* Should the previous position be restored. */
1363         /* Searching */
1364         char grep[SIZEOF_STR];  /* Search string */
1365         regex_t *regex;         /* Pre-compiled regexp */
1367         /* If non-NULL, points to the view that opened this view. If this view
1368          * is closed tig will switch back to the parent view. */
1369         struct view *parent;
1370         struct view *prev;
1372         /* Buffering */
1373         size_t lines;           /* Total number of lines */
1374         struct line *line;      /* Line index */
1375         unsigned int digits;    /* Number of digits in the lines member. */
1377         /* Drawing */
1378         struct line *curline;   /* Line currently being drawn. */
1379         enum line_type curtype; /* Attribute currently used for drawing. */
1380         unsigned long col;      /* Column when drawing. */
1381         bool has_scrolled;      /* View was scrolled. */
1383         /* Loading */
1384         const char **argv;      /* Shell command arguments. */
1385         const char *dir;        /* Directory from which to execute. */
1386         struct io io;
1387         struct io *pipe;
1388         time_t start_time;
1389         time_t update_secs;
1390 };
1392 struct view_ops {
1393         /* What type of content being displayed. Used in the title bar. */
1394         const char *type;
1395         /* Default command arguments. */
1396         const char **argv;
1397         /* Open and reads in all view content. */
1398         bool (*open)(struct view *view);
1399         /* Read one line; updates view->line. */
1400         bool (*read)(struct view *view, char *data);
1401         /* Draw one line; @lineno must be < view->height. */
1402         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1403         /* Depending on view handle a special requests. */
1404         enum request (*request)(struct view *view, enum request request, struct line *line);
1405         /* Search for regexp in a line. */
1406         bool (*grep)(struct view *view, struct line *line);
1407         /* Select line */
1408         void (*select)(struct view *view, struct line *line);
1409         /* Prepare view for loading */
1410         bool (*prepare)(struct view *view);
1411 };
1413 static struct view_ops blame_ops;
1414 static struct view_ops blob_ops;
1415 static struct view_ops diff_ops;
1416 static struct view_ops help_ops;
1417 static struct view_ops log_ops;
1418 static struct view_ops main_ops;
1419 static struct view_ops pager_ops;
1420 static struct view_ops stage_ops;
1421 static struct view_ops status_ops;
1422 static struct view_ops tree_ops;
1423 static struct view_ops branch_ops;
1425 #define VIEW_STR(type, name, env, ref, ops, map, git) \
1426         { type, name, #env, ref, ops, map, git }
1428 #define VIEW_(id, name, ops, git, ref) \
1429         VIEW_STR(VIEW_##id, name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
1431 static struct view views[] = {
1432         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1433         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1434         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1435         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1436         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1437         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1438         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1439         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1440         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1441         VIEW_(STATUS, "status", &status_ops, TRUE,  ""),
1442         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1443 };
1445 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1447 #define foreach_view(view, i) \
1448         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1450 #define view_is_displayed(view) \
1451         (view == display[0] || view == display[1])
1453 static enum request
1454 view_request(struct view *view, enum request request)
1456         if (!view || !view->lines)
1457                 return request;
1458         return view->ops->request(view, request, &view->line[view->lineno]);
1462 /*
1463  * View drawing.
1464  */
1466 static inline void
1467 set_view_attr(struct view *view, enum line_type type)
1469         if (!view->curline->selected && view->curtype != type) {
1470                 (void) wattrset(view->win, get_line_attr(type));
1471                 wchgat(view->win, -1, 0, type, NULL);
1472                 view->curtype = type;
1473         }
1476 static int
1477 draw_chars(struct view *view, enum line_type type, const char *string,
1478            int max_len, bool use_tilde)
1480         static char out_buffer[BUFSIZ * 2];
1481         int len = 0;
1482         int col = 0;
1483         int trimmed = FALSE;
1484         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1486         if (max_len <= 0)
1487                 return 0;
1489         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1491         set_view_attr(view, type);
1492         if (len > 0) {
1493                 if (opt_iconv_out != ICONV_NONE) {
1494                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1495                         size_t inlen = len + 1;
1497                         char *outbuf = out_buffer;
1498                         size_t outlen = sizeof(out_buffer);
1500                         size_t ret;
1502                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1503                         if (ret != (size_t) -1) {
1504                                 string = out_buffer;
1505                                 len = sizeof(out_buffer) - outlen;
1506                         }
1507                 }
1509                 waddnstr(view->win, string, len);
1511                 if (trimmed && use_tilde) {
1512                         set_view_attr(view, LINE_DELIMITER);
1513                         waddch(view->win, '~');
1514                         col++;
1515                 }
1516         }
1518         return col;
1521 static int
1522 draw_space(struct view *view, enum line_type type, int max, int spaces)
1524         static char space[] = "                    ";
1525         int col = 0;
1527         spaces = MIN(max, spaces);
1529         while (spaces > 0) {
1530                 int len = MIN(spaces, sizeof(space) - 1);
1532                 col += draw_chars(view, type, space, len, FALSE);
1533                 spaces -= len;
1534         }
1536         return col;
1539 static bool
1540 draw_text(struct view *view, enum line_type type, const char *string)
1542         char text[SIZEOF_STR];
1544         do {
1545                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1547                 view->col += draw_chars(view, type, text, view->width + view->yoffset - view->col, TRUE);
1548                 string += pos;
1549         } while (*string && view->width + view->yoffset > view->col);
1551         return view->width + view->yoffset <= view->col;
1554 static bool
1555 draw_graphic(struct view *view, enum line_type type, chtype graphic[], size_t size)
1557         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1558         int max = view->width + view->yoffset - view->col;
1559         int i;
1561         if (max < size)
1562                 size = max;
1564         set_view_attr(view, type);
1565         /* Using waddch() instead of waddnstr() ensures that
1566          * they'll be rendered correctly for the cursor line. */
1567         for (i = skip; i < size; i++)
1568                 waddch(view->win, graphic[i]);
1570         view->col += size;
1571         if (size < max && skip <= size)
1572                 waddch(view->win, ' ');
1573         view->col++;
1575         return view->width + view->yoffset <= view->col;
1578 static bool
1579 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1581         int max = MIN(view->width + view->yoffset - view->col, len);
1582         int col;
1584         if (text)
1585                 col = draw_chars(view, type, text, max - 1, trim);
1586         else
1587                 col = draw_space(view, type, max - 1, max - 1);
1589         view->col += col;
1590         view->col += draw_space(view, LINE_DEFAULT, max - col, max - col);
1591         return view->width + view->yoffset <= view->col;
1594 static bool
1595 draw_date(struct view *view, struct time *time)
1597         const char *date = mkdate(time, opt_date);
1598         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1600         return draw_field(view, LINE_DATE, date, cols, FALSE);
1603 static bool
1604 draw_author(struct view *view, const char *author)
1606         bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1607         bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1609         if (abbreviate && author)
1610                 author = get_author_initials(author);
1612         return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1615 static bool
1616 draw_mode(struct view *view, mode_t mode)
1618         const char *str;
1620         if (S_ISDIR(mode))
1621                 str = "drwxr-xr-x";
1622         else if (S_ISLNK(mode))
1623                 str = "lrwxrwxrwx";
1624         else if (S_ISGITLINK(mode))
1625                 str = "m---------";
1626         else if (S_ISREG(mode) && mode & S_IXUSR)
1627                 str = "-rwxr-xr-x";
1628         else if (S_ISREG(mode))
1629                 str = "-rw-r--r--";
1630         else
1631                 str = "----------";
1633         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1636 static bool
1637 draw_lineno(struct view *view, unsigned int lineno)
1639         char number[10];
1640         int digits3 = view->digits < 3 ? 3 : view->digits;
1641         int max = MIN(view->width + view->yoffset - view->col, digits3);
1642         char *text = NULL;
1643         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1645         lineno += view->offset + 1;
1646         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1647                 static char fmt[] = "%1ld";
1649                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1650                 if (string_format(number, fmt, lineno))
1651                         text = number;
1652         }
1653         if (text)
1654                 view->col += draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1655         else
1656                 view->col += draw_space(view, LINE_LINE_NUMBER, max, digits3);
1657         return draw_graphic(view, LINE_DEFAULT, &separator, 1);
1660 static bool
1661 draw_view_line(struct view *view, unsigned int lineno)
1663         struct line *line;
1664         bool selected = (view->offset + lineno == view->lineno);
1666         assert(view_is_displayed(view));
1668         if (view->offset + lineno >= view->lines)
1669                 return FALSE;
1671         line = &view->line[view->offset + lineno];
1673         wmove(view->win, lineno, 0);
1674         if (line->cleareol)
1675                 wclrtoeol(view->win);
1676         view->col = 0;
1677         view->curline = line;
1678         view->curtype = LINE_NONE;
1679         line->selected = FALSE;
1680         line->dirty = line->cleareol = 0;
1682         if (selected) {
1683                 set_view_attr(view, LINE_CURSOR);
1684                 line->selected = TRUE;
1685                 view->ops->select(view, line);
1686         }
1688         return view->ops->draw(view, line, lineno);
1691 static void
1692 redraw_view_dirty(struct view *view)
1694         bool dirty = FALSE;
1695         int lineno;
1697         for (lineno = 0; lineno < view->height; lineno++) {
1698                 if (view->offset + lineno >= view->lines)
1699                         break;
1700                 if (!view->line[view->offset + lineno].dirty)
1701                         continue;
1702                 dirty = TRUE;
1703                 if (!draw_view_line(view, lineno))
1704                         break;
1705         }
1707         if (!dirty)
1708                 return;
1709         wnoutrefresh(view->win);
1712 static void
1713 redraw_view_from(struct view *view, int lineno)
1715         assert(0 <= lineno && lineno < view->height);
1717         for (; lineno < view->height; lineno++) {
1718                 if (!draw_view_line(view, lineno))
1719                         break;
1720         }
1722         wnoutrefresh(view->win);
1725 static void
1726 redraw_view(struct view *view)
1728         werase(view->win);
1729         redraw_view_from(view, 0);
1733 static void
1734 update_view_title(struct view *view)
1736         char buf[SIZEOF_STR];
1737         char state[SIZEOF_STR];
1738         size_t bufpos = 0, statelen = 0;
1739         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1741         assert(view_is_displayed(view));
1743         if (view->type != VIEW_STATUS && view->lines) {
1744                 unsigned int view_lines = view->offset + view->height;
1745                 unsigned int lines = view->lines
1746                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1747                                    : 0;
1749                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1750                                    view->ops->type,
1751                                    view->lineno + 1,
1752                                    view->lines,
1753                                    lines);
1755         }
1757         if (view->pipe) {
1758                 time_t secs = time(NULL) - view->start_time;
1760                 /* Three git seconds are a long time ... */
1761                 if (secs > 2)
1762                         string_format_from(state, &statelen, " loading %lds", secs);
1763         }
1765         string_format_from(buf, &bufpos, "[%s]", view->name);
1766         if (*view->ref && bufpos < view->width) {
1767                 size_t refsize = strlen(view->ref);
1768                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1770                 if (minsize < view->width)
1771                         refsize = view->width - minsize + 7;
1772                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1773         }
1775         if (statelen && bufpos < view->width) {
1776                 string_format_from(buf, &bufpos, "%s", state);
1777         }
1779         if (view == display[current_view])
1780                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1781         else
1782                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1784         mvwaddnstr(window, 0, 0, buf, bufpos);
1785         wclrtoeol(window);
1786         wnoutrefresh(window);
1789 static int
1790 apply_step(double step, int value)
1792         if (step >= 1)
1793                 return (int) step;
1794         value *= step + 0.01;
1795         return value ? value : 1;
1798 static void
1799 resize_display(void)
1801         int offset, i;
1802         struct view *base = display[0];
1803         struct view *view = display[1] ? display[1] : display[0];
1805         /* Setup window dimensions */
1807         getmaxyx(stdscr, base->height, base->width);
1809         /* Make room for the status window. */
1810         base->height -= 1;
1812         if (view != base) {
1813                 /* Horizontal split. */
1814                 view->width   = base->width;
1815                 view->height  = apply_step(opt_scale_split_view, base->height);
1816                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1817                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1818                 base->height -= view->height;
1820                 /* Make room for the title bar. */
1821                 view->height -= 1;
1822         }
1824         /* Make room for the title bar. */
1825         base->height -= 1;
1827         offset = 0;
1829         foreach_displayed_view (view, i) {
1830                 if (!display_win[i]) {
1831                         display_win[i] = newwin(view->height, view->width, offset, 0);
1832                         if (!display_win[i])
1833                                 die("Failed to create %s view", view->name);
1835                         scrollok(display_win[i], FALSE);
1837                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1838                         if (!display_title[i])
1839                                 die("Failed to create title window");
1841                 } else {
1842                         wresize(display_win[i], view->height, view->width);
1843                         mvwin(display_win[i],   offset, 0);
1844                         mvwin(display_title[i], offset + view->height, 0);
1845                 }
1847                 view->win = display_win[i];
1849                 offset += view->height + 1;
1850         }
1853 static void
1854 redraw_display(bool clear)
1856         struct view *view;
1857         int i;
1859         foreach_displayed_view (view, i) {
1860                 if (clear)
1861                         wclear(view->win);
1862                 redraw_view(view);
1863                 update_view_title(view);
1864         }
1868 /*
1869  * Option management
1870  */
1872 #define TOGGLE_MENU \
1873         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1874         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1875         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1876         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1877         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1879 static void
1880 toggle_option(enum request request)
1882         const struct {
1883                 enum request request;
1884                 const struct enum_map *map;
1885                 size_t map_size;
1886         } data[] = {            
1887 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1888                 TOGGLE_MENU
1889 #undef  TOGGLE_
1890         };
1891         const struct menu_item menu[] = {
1892 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1893                 TOGGLE_MENU
1894 #undef  TOGGLE_
1895                 { 0 }
1896         };
1897         int i = 0;
1899         if (request == REQ_OPTIONS) {
1900                 if (!prompt_menu("Toggle option", menu, &i))
1901                         return;
1902         } else {
1903                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1904                         i++;
1905                 if (i >= ARRAY_SIZE(data))
1906                         die("Invalid request (%d)", request);
1907         }
1909         if (data[i].map != NULL) {
1910                 unsigned int *opt = menu[i].data;
1912                 *opt = (*opt + 1) % data[i].map_size;
1913                 redraw_display(FALSE);
1914                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1916         } else {
1917                 bool *option = menu[i].data;
1919                 *option = !*option;
1920                 redraw_display(FALSE);
1921                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1922         }
1925 static void
1926 maximize_view(struct view *view)
1928         memset(display, 0, sizeof(display));
1929         current_view = 0;
1930         display[current_view] = view;
1931         resize_display();
1932         redraw_display(FALSE);
1933         report("");
1937 /*
1938  * Navigation
1939  */
1941 static bool
1942 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1944         if (lineno >= view->lines)
1945                 lineno = view->lines > 0 ? view->lines - 1 : 0;
1947         if (offset > lineno || offset + view->height <= lineno) {
1948                 unsigned long half = view->height / 2;
1950                 if (lineno > half)
1951                         offset = lineno - half;
1952                 else
1953                         offset = 0;
1954         }
1956         if (offset != view->offset || lineno != view->lineno) {
1957                 view->offset = offset;
1958                 view->lineno = lineno;
1959                 return TRUE;
1960         }
1962         return FALSE;
1965 /* Scrolling backend */
1966 static void
1967 do_scroll_view(struct view *view, int lines)
1969         bool redraw_current_line = FALSE;
1971         /* The rendering expects the new offset. */
1972         view->offset += lines;
1974         assert(0 <= view->offset && view->offset < view->lines);
1975         assert(lines);
1977         /* Move current line into the view. */
1978         if (view->lineno < view->offset) {
1979                 view->lineno = view->offset;
1980                 redraw_current_line = TRUE;
1981         } else if (view->lineno >= view->offset + view->height) {
1982                 view->lineno = view->offset + view->height - 1;
1983                 redraw_current_line = TRUE;
1984         }
1986         assert(view->offset <= view->lineno && view->lineno < view->lines);
1988         /* Redraw the whole screen if scrolling is pointless. */
1989         if (view->height < ABS(lines)) {
1990                 redraw_view(view);
1992         } else {
1993                 int line = lines > 0 ? view->height - lines : 0;
1994                 int end = line + ABS(lines);
1996                 scrollok(view->win, TRUE);
1997                 wscrl(view->win, lines);
1998                 scrollok(view->win, FALSE);
2000                 while (line < end && draw_view_line(view, line))
2001                         line++;
2003                 if (redraw_current_line)
2004                         draw_view_line(view, view->lineno - view->offset);
2005                 wnoutrefresh(view->win);
2006         }
2008         view->has_scrolled = TRUE;
2009         report("");
2012 /* Scroll frontend */
2013 static void
2014 scroll_view(struct view *view, enum request request)
2016         int lines = 1;
2018         assert(view_is_displayed(view));
2020         switch (request) {
2021         case REQ_SCROLL_FIRST_COL:
2022                 view->yoffset = 0;
2023                 redraw_view_from(view, 0);
2024                 report("");
2025                 return;
2026         case REQ_SCROLL_LEFT:
2027                 if (view->yoffset == 0) {
2028                         report("Cannot scroll beyond the first column");
2029                         return;
2030                 }
2031                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2032                         view->yoffset = 0;
2033                 else
2034                         view->yoffset -= apply_step(opt_hscroll, view->width);
2035                 redraw_view_from(view, 0);
2036                 report("");
2037                 return;
2038         case REQ_SCROLL_RIGHT:
2039                 view->yoffset += apply_step(opt_hscroll, view->width);
2040                 redraw_view(view);
2041                 report("");
2042                 return;
2043         case REQ_SCROLL_PAGE_DOWN:
2044                 lines = view->height;
2045         case REQ_SCROLL_LINE_DOWN:
2046                 if (view->offset + lines > view->lines)
2047                         lines = view->lines - view->offset;
2049                 if (lines == 0 || view->offset + view->height >= view->lines) {
2050                         report("Cannot scroll beyond the last line");
2051                         return;
2052                 }
2053                 break;
2055         case REQ_SCROLL_PAGE_UP:
2056                 lines = view->height;
2057         case REQ_SCROLL_LINE_UP:
2058                 if (lines > view->offset)
2059                         lines = view->offset;
2061                 if (lines == 0) {
2062                         report("Cannot scroll beyond the first line");
2063                         return;
2064                 }
2066                 lines = -lines;
2067                 break;
2069         default:
2070                 die("request %d not handled in switch", request);
2071         }
2073         do_scroll_view(view, lines);
2076 /* Cursor moving */
2077 static void
2078 move_view(struct view *view, enum request request)
2080         int scroll_steps = 0;
2081         int steps;
2083         switch (request) {
2084         case REQ_MOVE_FIRST_LINE:
2085                 steps = -view->lineno;
2086                 break;
2088         case REQ_MOVE_LAST_LINE:
2089                 steps = view->lines - view->lineno - 1;
2090                 break;
2092         case REQ_MOVE_PAGE_UP:
2093                 steps = view->height > view->lineno
2094                       ? -view->lineno : -view->height;
2095                 break;
2097         case REQ_MOVE_PAGE_DOWN:
2098                 steps = view->lineno + view->height >= view->lines
2099                       ? view->lines - view->lineno - 1 : view->height;
2100                 break;
2102         case REQ_MOVE_UP:
2103                 steps = -1;
2104                 break;
2106         case REQ_MOVE_DOWN:
2107                 steps = 1;
2108                 break;
2110         default:
2111                 die("request %d not handled in switch", request);
2112         }
2114         if (steps <= 0 && view->lineno == 0) {
2115                 report("Cannot move beyond the first line");
2116                 return;
2118         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2119                 report("Cannot move beyond the last line");
2120                 return;
2121         }
2123         /* Move the current line */
2124         view->lineno += steps;
2125         assert(0 <= view->lineno && view->lineno < view->lines);
2127         /* Check whether the view needs to be scrolled */
2128         if (view->lineno < view->offset ||
2129             view->lineno >= view->offset + view->height) {
2130                 scroll_steps = steps;
2131                 if (steps < 0 && -steps > view->offset) {
2132                         scroll_steps = -view->offset;
2134                 } else if (steps > 0) {
2135                         if (view->lineno == view->lines - 1 &&
2136                             view->lines > view->height) {
2137                                 scroll_steps = view->lines - view->offset - 1;
2138                                 if (scroll_steps >= view->height)
2139                                         scroll_steps -= view->height - 1;
2140                         }
2141                 }
2142         }
2144         if (!view_is_displayed(view)) {
2145                 view->offset += scroll_steps;
2146                 assert(0 <= view->offset && view->offset < view->lines);
2147                 view->ops->select(view, &view->line[view->lineno]);
2148                 return;
2149         }
2151         /* Repaint the old "current" line if we be scrolling */
2152         if (ABS(steps) < view->height)
2153                 draw_view_line(view, view->lineno - steps - view->offset);
2155         if (scroll_steps) {
2156                 do_scroll_view(view, scroll_steps);
2157                 return;
2158         }
2160         /* Draw the current line */
2161         draw_view_line(view, view->lineno - view->offset);
2163         wnoutrefresh(view->win);
2164         report("");
2168 /*
2169  * Searching
2170  */
2172 static void search_view(struct view *view, enum request request);
2174 static bool
2175 grep_text(struct view *view, const char *text[])
2177         regmatch_t pmatch;
2178         size_t i;
2180         for (i = 0; text[i]; i++)
2181                 if (*text[i] &&
2182                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2183                         return TRUE;
2184         return FALSE;
2187 static void
2188 select_view_line(struct view *view, unsigned long lineno)
2190         unsigned long old_lineno = view->lineno;
2191         unsigned long old_offset = view->offset;
2193         if (goto_view_line(view, view->offset, lineno)) {
2194                 if (view_is_displayed(view)) {
2195                         if (old_offset != view->offset) {
2196                                 redraw_view(view);
2197                         } else {
2198                                 draw_view_line(view, old_lineno - view->offset);
2199                                 draw_view_line(view, view->lineno - view->offset);
2200                                 wnoutrefresh(view->win);
2201                         }
2202                 } else {
2203                         view->ops->select(view, &view->line[view->lineno]);
2204                 }
2205         }
2208 static void
2209 find_next(struct view *view, enum request request)
2211         unsigned long lineno = view->lineno;
2212         int direction;
2214         if (!*view->grep) {
2215                 if (!*opt_search)
2216                         report("No previous search");
2217                 else
2218                         search_view(view, request);
2219                 return;
2220         }
2222         switch (request) {
2223         case REQ_SEARCH:
2224         case REQ_FIND_NEXT:
2225                 direction = 1;
2226                 break;
2228         case REQ_SEARCH_BACK:
2229         case REQ_FIND_PREV:
2230                 direction = -1;
2231                 break;
2233         default:
2234                 return;
2235         }
2237         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2238                 lineno += direction;
2240         /* Note, lineno is unsigned long so will wrap around in which case it
2241          * will become bigger than view->lines. */
2242         for (; lineno < view->lines; lineno += direction) {
2243                 if (view->ops->grep(view, &view->line[lineno])) {
2244                         select_view_line(view, lineno);
2245                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2246                         return;
2247                 }
2248         }
2250         report("No match found for '%s'", view->grep);
2253 static void
2254 search_view(struct view *view, enum request request)
2256         int regex_err;
2258         if (view->regex) {
2259                 regfree(view->regex);
2260                 *view->grep = 0;
2261         } else {
2262                 view->regex = calloc(1, sizeof(*view->regex));
2263                 if (!view->regex)
2264                         return;
2265         }
2267         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2268         if (regex_err != 0) {
2269                 char buf[SIZEOF_STR] = "unknown error";
2271                 regerror(regex_err, view->regex, buf, sizeof(buf));
2272                 report("Search failed: %s", buf);
2273                 return;
2274         }
2276         string_copy(view->grep, opt_search);
2278         find_next(view, request);
2281 /*
2282  * Incremental updating
2283  */
2285 static void
2286 reset_view(struct view *view)
2288         int i;
2290         for (i = 0; i < view->lines; i++)
2291                 free(view->line[i].data);
2292         free(view->line);
2294         view->p_offset = view->offset;
2295         view->p_yoffset = view->yoffset;
2296         view->p_lineno = view->lineno;
2298         view->line = NULL;
2299         view->offset = 0;
2300         view->yoffset = 0;
2301         view->lines  = 0;
2302         view->lineno = 0;
2303         view->vid[0] = 0;
2304         view->update_secs = 0;
2307 static const char *
2308 format_arg(const char *name)
2310         static struct {
2311                 const char *name;
2312                 size_t namelen;
2313                 const char *value;
2314                 const char *value_if_empty;
2315         } vars[] = {
2316 #define FORMAT_VAR(name, value, value_if_empty) \
2317         { name, STRING_SIZE(name), value, value_if_empty }
2318                 FORMAT_VAR("%(directory)",      opt_path,       ""),
2319                 FORMAT_VAR("%(file)",           opt_file,       ""),
2320                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2321                 FORMAT_VAR("%(head)",           ref_head,       ""),
2322                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2323                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2324                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2325         };
2326         int i;
2328         for (i = 0; i < ARRAY_SIZE(vars); i++)
2329                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2330                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2332         report("Unknown replacement: `%s`", name);
2333         return NULL;
2336 static bool
2337 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2339         char buf[SIZEOF_STR];
2340         int argc;
2342         argv_free(*dst_argv);
2344         for (argc = 0; src_argv[argc]; argc++) {
2345                 const char *arg = src_argv[argc];
2346                 size_t bufpos = 0;
2348                 if (!strcmp(arg, "%(fileargs)")) {
2349                         if (!argv_append_array(dst_argv, opt_file_argv))
2350                                 break;
2351                         continue;
2353                 } else if (!strcmp(arg, "%(diffargs)")) {
2354                         if (!argv_append_array(dst_argv, opt_diff_argv))
2355                                 break;
2356                         continue;
2358                 } else if (!strcmp(arg, "%(revargs)") ||
2359                            (first && !strcmp(arg, "%(commit)"))) {
2360                         if (!argv_append_array(dst_argv, opt_rev_argv))
2361                                 break;
2362                         continue;
2363                 }
2365                 while (arg) {
2366                         char *next = strstr(arg, "%(");
2367                         int len = next - arg;
2368                         const char *value;
2370                         if (!next || !replace) {
2371                                 len = strlen(arg);
2372                                 value = "";
2374                         } else {
2375                                 value = format_arg(next);
2377                                 if (!value) {
2378                                         return FALSE;
2379                                 }
2380                         }
2382                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2383                                 return FALSE;
2385                         arg = next && replace ? strchr(next, ')') + 1 : NULL;
2386                 }
2388                 if (!argv_append(dst_argv, buf))
2389                         break;
2390         }
2392         return src_argv[argc] == NULL;
2395 static bool
2396 restore_view_position(struct view *view)
2398         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2399                 return FALSE;
2401         /* Changing the view position cancels the restoring. */
2402         /* FIXME: Changing back to the first line is not detected. */
2403         if (view->offset != 0 || view->lineno != 0) {
2404                 view->p_restore = FALSE;
2405                 return FALSE;
2406         }
2408         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2409             view_is_displayed(view))
2410                 werase(view->win);
2412         view->yoffset = view->p_yoffset;
2413         view->p_restore = FALSE;
2415         return TRUE;
2418 static void
2419 end_update(struct view *view, bool force)
2421         if (!view->pipe)
2422                 return;
2423         while (!view->ops->read(view, NULL))
2424                 if (!force)
2425                         return;
2426         if (force)
2427                 io_kill(view->pipe);
2428         io_done(view->pipe);
2429         view->pipe = NULL;
2432 static void
2433 setup_update(struct view *view, const char *vid)
2435         reset_view(view);
2436         string_copy_rev(view->vid, vid);
2437         view->pipe = &view->io;
2438         view->start_time = time(NULL);
2441 static bool
2442 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2444         view->dir = dir;
2445         return format_argv(&view->argv, argv, replace, !view->prev);
2448 static bool
2449 prepare_update(struct view *view, const char *argv[], const char *dir)
2451         if (view->pipe)
2452                 end_update(view, TRUE);
2453         return prepare_io(view, dir, argv, FALSE);
2456 static bool
2457 start_update(struct view *view, const char **argv, const char *dir)
2459         if (view->pipe)
2460                 io_done(view->pipe);
2461         return prepare_io(view, dir, argv, FALSE) &&
2462                io_run(&view->io, IO_RD, dir, view->argv);
2465 static bool
2466 prepare_update_file(struct view *view, const char *name)
2468         if (view->pipe)
2469                 end_update(view, TRUE);
2470         argv_free(view->argv);
2471         return io_open(&view->io, "%s/%s", opt_cdup[0] ? opt_cdup : ".", name);
2474 static bool
2475 begin_update(struct view *view, bool refresh)
2477         if (view->pipe)
2478                 end_update(view, TRUE);
2480         if (!refresh) {
2481                 if (view->ops->prepare) {
2482                         if (!view->ops->prepare(view))
2483                                 return FALSE;
2484                 } else if (!prepare_io(view, NULL, view->ops->argv, TRUE)) {
2485                         return FALSE;
2486                 }
2488                 /* Put the current ref_* value to the view title ref
2489                  * member. This is needed by the blob view. Most other
2490                  * views sets it automatically after loading because the
2491                  * first line is a commit line. */
2492                 string_copy_rev(view->ref, view->id);
2493         }
2495         if (view->argv && view->argv[0] &&
2496             !io_run(&view->io, IO_RD, view->dir, view->argv))
2497                 return FALSE;
2499         setup_update(view, view->id);
2501         return TRUE;
2504 static bool
2505 update_view(struct view *view)
2507         char out_buffer[BUFSIZ * 2];
2508         char *line;
2509         /* Clear the view and redraw everything since the tree sorting
2510          * might have rearranged things. */
2511         bool redraw = view->lines == 0;
2512         bool can_read = TRUE;
2514         if (!view->pipe)
2515                 return TRUE;
2517         if (!io_can_read(view->pipe)) {
2518                 if (view->lines == 0 && view_is_displayed(view)) {
2519                         time_t secs = time(NULL) - view->start_time;
2521                         if (secs > 1 && secs > view->update_secs) {
2522                                 if (view->update_secs == 0)
2523                                         redraw_view(view);
2524                                 update_view_title(view);
2525                                 view->update_secs = secs;
2526                         }
2527                 }
2528                 return TRUE;
2529         }
2531         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2532                 if (opt_iconv_in != ICONV_NONE) {
2533                         ICONV_CONST char *inbuf = line;
2534                         size_t inlen = strlen(line) + 1;
2536                         char *outbuf = out_buffer;
2537                         size_t outlen = sizeof(out_buffer);
2539                         size_t ret;
2541                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2542                         if (ret != (size_t) -1)
2543                                 line = out_buffer;
2544                 }
2546                 if (!view->ops->read(view, line)) {
2547                         report("Allocation failure");
2548                         end_update(view, TRUE);
2549                         return FALSE;
2550                 }
2551         }
2553         {
2554                 unsigned long lines = view->lines;
2555                 int digits;
2557                 for (digits = 0; lines; digits++)
2558                         lines /= 10;
2560                 /* Keep the displayed view in sync with line number scaling. */
2561                 if (digits != view->digits) {
2562                         view->digits = digits;
2563                         if (opt_line_number || view->type == VIEW_BLAME)
2564                                 redraw = TRUE;
2565                 }
2566         }
2568         if (io_error(view->pipe)) {
2569                 report("Failed to read: %s", io_strerror(view->pipe));
2570                 end_update(view, TRUE);
2572         } else if (io_eof(view->pipe)) {
2573                 if (view_is_displayed(view))
2574                         report("");
2575                 end_update(view, FALSE);
2576         }
2578         if (restore_view_position(view))
2579                 redraw = TRUE;
2581         if (!view_is_displayed(view))
2582                 return TRUE;
2584         if (redraw)
2585                 redraw_view_from(view, 0);
2586         else
2587                 redraw_view_dirty(view);
2589         /* Update the title _after_ the redraw so that if the redraw picks up a
2590          * commit reference in view->ref it'll be available here. */
2591         update_view_title(view);
2592         return TRUE;
2595 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2597 static struct line *
2598 add_line_data(struct view *view, void *data, enum line_type type)
2600         struct line *line;
2602         if (!realloc_lines(&view->line, view->lines, 1))
2603                 return NULL;
2605         line = &view->line[view->lines++];
2606         memset(line, 0, sizeof(*line));
2607         line->type = type;
2608         line->data = data;
2609         line->dirty = 1;
2611         return line;
2614 static struct line *
2615 add_line_text(struct view *view, const char *text, enum line_type type)
2617         char *data = text ? strdup(text) : NULL;
2619         return data ? add_line_data(view, data, type) : NULL;
2622 static struct line *
2623 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2625         char buf[SIZEOF_STR];
2626         va_list args;
2628         va_start(args, fmt);
2629         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2630                 buf[0] = 0;
2631         va_end(args);
2633         return buf[0] ? add_line_text(view, buf, type) : NULL;
2636 /*
2637  * View opening
2638  */
2640 enum open_flags {
2641         OPEN_DEFAULT = 0,       /* Use default view switching. */
2642         OPEN_SPLIT = 1,         /* Split current view. */
2643         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
2644         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
2645         OPEN_PREPARED = 32,     /* Open already prepared command. */
2646 };
2648 static void
2649 open_view(struct view *prev, enum request request, enum open_flags flags)
2651         bool split = !!(flags & OPEN_SPLIT);
2652         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2653         bool nomaximize = !!(flags & OPEN_REFRESH);
2654         struct view *view = VIEW(request);
2655         int nviews = displayed_views();
2656         struct view *base_view = display[0];
2658         if (view == prev && nviews == 1 && !reload) {
2659                 report("Already in %s view", view->name);
2660                 return;
2661         }
2663         if (view->git_dir && !opt_git_dir[0]) {
2664                 report("The %s view is disabled in pager view", view->name);
2665                 return;
2666         }
2668         if (split) {
2669                 display[1] = view;
2670                 current_view = 1;
2671                 view->parent = prev;
2672         } else if (!nomaximize) {
2673                 /* Maximize the current view. */
2674                 memset(display, 0, sizeof(display));
2675                 current_view = 0;
2676                 display[current_view] = view;
2677         }
2679         /* No prev signals that this is the first loaded view. */
2680         if (prev && view != prev) {
2681                 view->prev = prev;
2682         }
2684         /* Resize the view when switching between split- and full-screen,
2685          * or when switching between two different full-screen views. */
2686         if (nviews != displayed_views() ||
2687             (nviews == 1 && base_view != display[0]))
2688                 resize_display();
2690         if (view->ops->open) {
2691                 if (view->pipe)
2692                         end_update(view, TRUE);
2693                 if (!view->ops->open(view)) {
2694                         report("Failed to load %s view", view->name);
2695                         return;
2696                 }
2697                 restore_view_position(view);
2699         } else if ((reload || strcmp(view->vid, view->id)) &&
2700                    !begin_update(view, flags & (OPEN_REFRESH | OPEN_PREPARED))) {
2701                 report("Failed to load %s view", view->name);
2702                 return;
2703         }
2705         if (split && prev->lineno - prev->offset >= prev->height) {
2706                 /* Take the title line into account. */
2707                 int lines = prev->lineno - prev->offset - prev->height + 1;
2709                 /* Scroll the view that was split if the current line is
2710                  * outside the new limited view. */
2711                 do_scroll_view(prev, lines);
2712         }
2714         if (prev && view != prev && split && view_is_displayed(prev)) {
2715                 /* "Blur" the previous view. */
2716                 update_view_title(prev);
2717         }
2719         if (view->pipe && view->lines == 0) {
2720                 /* Clear the old view and let the incremental updating refill
2721                  * the screen. */
2722                 werase(view->win);
2723                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2724                 report("");
2725         } else if (view_is_displayed(view)) {
2726                 redraw_view(view);
2727                 report("");
2728         }
2731 static void
2732 open_external_viewer(const char *argv[], const char *dir)
2734         def_prog_mode();           /* save current tty modes */
2735         endwin();                  /* restore original tty modes */
2736         io_run_fg(argv, dir);
2737         fprintf(stderr, "Press Enter to continue");
2738         getc(opt_tty);
2739         reset_prog_mode();
2740         redraw_display(TRUE);
2743 static void
2744 open_mergetool(const char *file)
2746         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2748         open_external_viewer(mergetool_argv, opt_cdup);
2751 static void
2752 open_editor(const char *file)
2754         const char *editor_argv[] = { "vi", file, NULL };
2755         const char *editor;
2757         editor = getenv("GIT_EDITOR");
2758         if (!editor && *opt_editor)
2759                 editor = opt_editor;
2760         if (!editor)
2761                 editor = getenv("VISUAL");
2762         if (!editor)
2763                 editor = getenv("EDITOR");
2764         if (!editor)
2765                 editor = "vi";
2767         editor_argv[0] = editor;
2768         open_external_viewer(editor_argv, opt_cdup);
2771 static void
2772 open_run_request(enum request request)
2774         struct run_request *req = get_run_request(request);
2775         const char **argv = NULL;
2777         if (!req) {
2778                 report("Unknown run request");
2779                 return;
2780         }
2782         if (format_argv(&argv, req->argv, TRUE, FALSE))
2783                 open_external_viewer(argv, NULL);
2784         if (argv)
2785                 argv_free(argv);
2786         free(argv);
2789 /*
2790  * User request switch noodle
2791  */
2793 static int
2794 view_driver(struct view *view, enum request request)
2796         int i;
2798         if (request == REQ_NONE)
2799                 return TRUE;
2801         if (request > REQ_NONE) {
2802                 open_run_request(request);
2803                 view_request(view, REQ_REFRESH);
2804                 return TRUE;
2805         }
2807         request = view_request(view, request);
2808         if (request == REQ_NONE)
2809                 return TRUE;
2811         switch (request) {
2812         case REQ_MOVE_UP:
2813         case REQ_MOVE_DOWN:
2814         case REQ_MOVE_PAGE_UP:
2815         case REQ_MOVE_PAGE_DOWN:
2816         case REQ_MOVE_FIRST_LINE:
2817         case REQ_MOVE_LAST_LINE:
2818                 move_view(view, request);
2819                 break;
2821         case REQ_SCROLL_FIRST_COL:
2822         case REQ_SCROLL_LEFT:
2823         case REQ_SCROLL_RIGHT:
2824         case REQ_SCROLL_LINE_DOWN:
2825         case REQ_SCROLL_LINE_UP:
2826         case REQ_SCROLL_PAGE_DOWN:
2827         case REQ_SCROLL_PAGE_UP:
2828                 scroll_view(view, request);
2829                 break;
2831         case REQ_VIEW_BLAME:
2832                 if (!opt_file[0]) {
2833                         report("No file chosen, press %s to open tree view",
2834                                get_key(view->keymap, REQ_VIEW_TREE));
2835                         break;
2836                 }
2837                 open_view(view, request, OPEN_DEFAULT);
2838                 break;
2840         case REQ_VIEW_BLOB:
2841                 if (!ref_blob[0]) {
2842                         report("No file chosen, press %s to open tree view",
2843                                get_key(view->keymap, REQ_VIEW_TREE));
2844                         break;
2845                 }
2846                 open_view(view, request, OPEN_DEFAULT);
2847                 break;
2849         case REQ_VIEW_PAGER:
2850                 if (view == NULL) {
2851                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2852                                 die("Failed to open stdin");
2853                         open_view(view, request, OPEN_PREPARED);
2854                         break;
2855                 }
2857                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2858                         report("No pager content, press %s to run command from prompt",
2859                                get_key(view->keymap, REQ_PROMPT));
2860                         break;
2861                 }
2862                 open_view(view, request, OPEN_DEFAULT);
2863                 break;
2865         case REQ_VIEW_STAGE:
2866                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2867                         report("No stage content, press %s to open the status view and choose file",
2868                                get_key(view->keymap, REQ_VIEW_STATUS));
2869                         break;
2870                 }
2871                 open_view(view, request, OPEN_DEFAULT);
2872                 break;
2874         case REQ_VIEW_STATUS:
2875                 if (opt_is_inside_work_tree == FALSE) {
2876                         report("The status view requires a working tree");
2877                         break;
2878                 }
2879                 open_view(view, request, OPEN_DEFAULT);
2880                 break;
2882         case REQ_VIEW_MAIN:
2883         case REQ_VIEW_DIFF:
2884         case REQ_VIEW_LOG:
2885         case REQ_VIEW_TREE:
2886         case REQ_VIEW_HELP:
2887         case REQ_VIEW_BRANCH:
2888                 open_view(view, request, OPEN_DEFAULT);
2889                 break;
2891         case REQ_NEXT:
2892         case REQ_PREVIOUS:
2893                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2895                 if (view->parent) {
2896                         int line;
2898                         view = view->parent;
2899                         line = view->lineno;
2900                         move_view(view, request);
2901                         if (view_is_displayed(view))
2902                                 update_view_title(view);
2903                         if (line != view->lineno)
2904                                 view_request(view, REQ_ENTER);
2905                 } else {
2906                         move_view(view, request);
2907                 }
2908                 break;
2910         case REQ_VIEW_NEXT:
2911         {
2912                 int nviews = displayed_views();
2913                 int next_view = (current_view + 1) % nviews;
2915                 if (next_view == current_view) {
2916                         report("Only one view is displayed");
2917                         break;
2918                 }
2920                 current_view = next_view;
2921                 /* Blur out the title of the previous view. */
2922                 update_view_title(view);
2923                 report("");
2924                 break;
2925         }
2926         case REQ_REFRESH:
2927                 report("Refreshing is not yet supported for the %s view", view->name);
2928                 break;
2930         case REQ_MAXIMIZE:
2931                 if (displayed_views() == 2)
2932                         maximize_view(view);
2933                 break;
2935         case REQ_OPTIONS:
2936         case REQ_TOGGLE_LINENO:
2937         case REQ_TOGGLE_DATE:
2938         case REQ_TOGGLE_AUTHOR:
2939         case REQ_TOGGLE_REV_GRAPH:
2940         case REQ_TOGGLE_REFS:
2941                 toggle_option(request);
2942                 break;
2944         case REQ_TOGGLE_SORT_FIELD:
2945         case REQ_TOGGLE_SORT_ORDER:
2946                 report("Sorting is not yet supported for the %s view", view->name);
2947                 break;
2949         case REQ_SEARCH:
2950         case REQ_SEARCH_BACK:
2951                 search_view(view, request);
2952                 break;
2954         case REQ_FIND_NEXT:
2955         case REQ_FIND_PREV:
2956                 find_next(view, request);
2957                 break;
2959         case REQ_STOP_LOADING:
2960                 foreach_view(view, i) {
2961                         if (view->pipe)
2962                                 report("Stopped loading the %s view", view->name),
2963                         end_update(view, TRUE);
2964                 }
2965                 break;
2967         case REQ_SHOW_VERSION:
2968                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
2969                 return TRUE;
2971         case REQ_SCREEN_REDRAW:
2972                 redraw_display(TRUE);
2973                 break;
2975         case REQ_EDIT:
2976                 report("Nothing to edit");
2977                 break;
2979         case REQ_ENTER:
2980                 report("Nothing to enter");
2981                 break;
2983         case REQ_VIEW_CLOSE:
2984                 /* XXX: Mark closed views by letting view->prev point to the
2985                  * view itself. Parents to closed view should never be
2986                  * followed. */
2987                 if (view->prev && view->prev != view) {
2988                         maximize_view(view->prev);
2989                         view->prev = view;
2990                         break;
2991                 }
2992                 /* Fall-through */
2993         case REQ_QUIT:
2994                 return FALSE;
2996         default:
2997                 report("Unknown key, press %s for help",
2998                        get_key(view->keymap, REQ_VIEW_HELP));
2999                 return TRUE;
3000         }
3002         return TRUE;
3006 /*
3007  * View backend utilities
3008  */
3010 enum sort_field {
3011         ORDERBY_NAME,
3012         ORDERBY_DATE,
3013         ORDERBY_AUTHOR,
3014 };
3016 struct sort_state {
3017         const enum sort_field *fields;
3018         size_t size, current;
3019         bool reverse;
3020 };
3022 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3023 #define get_sort_field(state) ((state).fields[(state).current])
3024 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3026 static void
3027 sort_view(struct view *view, enum request request, struct sort_state *state,
3028           int (*compare)(const void *, const void *))
3030         switch (request) {
3031         case REQ_TOGGLE_SORT_FIELD:
3032                 state->current = (state->current + 1) % state->size;
3033                 break;
3035         case REQ_TOGGLE_SORT_ORDER:
3036                 state->reverse = !state->reverse;
3037                 break;
3038         default:
3039                 die("Not a sort request");
3040         }
3042         qsort(view->line, view->lines, sizeof(*view->line), compare);
3043         redraw_view(view);
3046 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3048 /* Small author cache to reduce memory consumption. It uses binary
3049  * search to lookup or find place to position new entries. No entries
3050  * are ever freed. */
3051 static const char *
3052 get_author(const char *name)
3054         static const char **authors;
3055         static size_t authors_size;
3056         int from = 0, to = authors_size - 1;
3058         while (from <= to) {
3059                 size_t pos = (to + from) / 2;
3060                 int cmp = strcmp(name, authors[pos]);
3062                 if (!cmp)
3063                         return authors[pos];
3065                 if (cmp < 0)
3066                         to = pos - 1;
3067                 else
3068                         from = pos + 1;
3069         }
3071         if (!realloc_authors(&authors, authors_size, 1))
3072                 return NULL;
3073         name = strdup(name);
3074         if (!name)
3075                 return NULL;
3077         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3078         authors[from] = name;
3079         authors_size++;
3081         return name;
3084 static void
3085 parse_timesec(struct time *time, const char *sec)
3087         time->sec = (time_t) atol(sec);
3090 static void
3091 parse_timezone(struct time *time, const char *zone)
3093         long tz;
3095         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3096         tz += ('0' - zone[2]) * 60 * 60;
3097         tz += ('0' - zone[3]) * 60 * 10;
3098         tz += ('0' - zone[4]) * 60;
3100         if (zone[0] == '-')
3101                 tz = -tz;
3103         time->tz = tz;
3104         time->sec -= tz;
3107 /* Parse author lines where the name may be empty:
3108  *      author  <email@address.tld> 1138474660 +0100
3109  */
3110 static void
3111 parse_author_line(char *ident, const char **author, struct time *time)
3113         char *nameend = strchr(ident, '<');
3114         char *emailend = strchr(ident, '>');
3116         if (nameend && emailend)
3117                 *nameend = *emailend = 0;
3118         ident = chomp_string(ident);
3119         if (!*ident) {
3120                 if (nameend)
3121                         ident = chomp_string(nameend + 1);
3122                 if (!*ident)
3123                         ident = "Unknown";
3124         }
3126         *author = get_author(ident);
3128         /* Parse epoch and timezone */
3129         if (emailend && emailend[1] == ' ') {
3130                 char *secs = emailend + 2;
3131                 char *zone = strchr(secs, ' ');
3133                 parse_timesec(time, secs);
3135                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3136                         parse_timezone(time, zone + 1);
3137         }
3140 /*
3141  * Pager backend
3142  */
3144 static bool
3145 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3147         if (opt_line_number && draw_lineno(view, lineno))
3148                 return TRUE;
3150         draw_text(view, line->type, line->data);
3151         return TRUE;
3154 static bool
3155 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3157         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3158         char ref[SIZEOF_STR];
3160         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3161                 return TRUE;
3163         /* This is the only fatal call, since it can "corrupt" the buffer. */
3164         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3165                 return FALSE;
3167         return TRUE;
3170 static void
3171 add_pager_refs(struct view *view, struct line *line)
3173         char buf[SIZEOF_STR];
3174         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3175         struct ref_list *list;
3176         size_t bufpos = 0, i;
3177         const char *sep = "Refs: ";
3178         bool is_tag = FALSE;
3180         assert(line->type == LINE_COMMIT);
3182         list = get_ref_list(commit_id);
3183         if (!list) {
3184                 if (view->type == VIEW_DIFF)
3185                         goto try_add_describe_ref;
3186                 return;
3187         }
3189         for (i = 0; i < list->size; i++) {
3190                 struct ref *ref = list->refs[i];
3191                 const char *fmt = ref->tag    ? "%s[%s]" :
3192                                   ref->remote ? "%s<%s>" : "%s%s";
3194                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3195                         return;
3196                 sep = ", ";
3197                 if (ref->tag)
3198                         is_tag = TRUE;
3199         }
3201         if (!is_tag && view->type == VIEW_DIFF) {
3202 try_add_describe_ref:
3203                 /* Add <tag>-g<commit_id> "fake" reference. */
3204                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3205                         return;
3206         }
3208         if (bufpos == 0)
3209                 return;
3211         add_line_text(view, buf, LINE_PP_REFS);
3214 static bool
3215 pager_read(struct view *view, char *data)
3217         struct line *line;
3219         if (!data)
3220                 return TRUE;
3222         line = add_line_text(view, data, get_line_type(data));
3223         if (!line)
3224                 return FALSE;
3226         if (line->type == LINE_COMMIT &&
3227             (view->type == VIEW_DIFF ||
3228              view->type == VIEW_LOG))
3229                 add_pager_refs(view, line);
3231         return TRUE;
3234 static enum request
3235 pager_request(struct view *view, enum request request, struct line *line)
3237         int split = 0;
3239         if (request != REQ_ENTER)
3240                 return request;
3242         if (line->type == LINE_COMMIT &&
3243            (view->type == VIEW_LOG ||
3244             view->type == VIEW_PAGER)) {
3245                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3246                 split = 1;
3247         }
3249         /* Always scroll the view even if it was split. That way
3250          * you can use Enter to scroll through the log view and
3251          * split open each commit diff. */
3252         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3254         /* FIXME: A minor workaround. Scrolling the view will call report("")
3255          * but if we are scrolling a non-current view this won't properly
3256          * update the view title. */
3257         if (split)
3258                 update_view_title(view);
3260         return REQ_NONE;
3263 static bool
3264 pager_grep(struct view *view, struct line *line)
3266         const char *text[] = { line->data, NULL };
3268         return grep_text(view, text);
3271 static void
3272 pager_select(struct view *view, struct line *line)
3274         if (line->type == LINE_COMMIT) {
3275                 char *text = (char *)line->data + STRING_SIZE("commit ");
3277                 if (view->type != VIEW_PAGER)
3278                         string_copy_rev(view->ref, text);
3279                 string_copy_rev(ref_commit, text);
3280         }
3283 static struct view_ops pager_ops = {
3284         "line",
3285         NULL,
3286         NULL,
3287         pager_read,
3288         pager_draw,
3289         pager_request,
3290         pager_grep,
3291         pager_select,
3292 };
3294 static const char *log_argv[SIZEOF_ARG] = {
3295         "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3296 };
3298 static enum request
3299 log_request(struct view *view, enum request request, struct line *line)
3301         switch (request) {
3302         case REQ_REFRESH:
3303                 load_refs();
3304                 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3305                 return REQ_NONE;
3306         default:
3307                 return pager_request(view, request, line);
3308         }
3311 static struct view_ops log_ops = {
3312         "line",
3313         log_argv,
3314         NULL,
3315         pager_read,
3316         pager_draw,
3317         log_request,
3318         pager_grep,
3319         pager_select,
3320 };
3322 static const char *diff_argv[SIZEOF_ARG] = {
3323         "git", "show", "--pretty=fuller", "--no-color", "--root",
3324                 "--patch-with-stat", "--find-copies-harder", "-C",
3325                 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3326 };
3328 static bool
3329 diff_read(struct view *view, char *data)
3331         if (!data) {
3332                 /* Fall back to retry if no diff will be shown. */
3333                 if (view->lines == 0 && opt_file_argv) {
3334                         int pos = argv_size(view->argv)
3335                                 - argv_size(opt_file_argv) - 1;
3337                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3338                                 for (; view->argv[pos]; pos++) {
3339                                         free((void *) view->argv[pos]);
3340                                         view->argv[pos] = NULL;
3341                                 }
3343                                 if (view->pipe)
3344                                         io_done(view->pipe);
3345                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3346                                         return FALSE;
3347                         }
3348                 }
3349                 return TRUE;
3350         }
3352         return pager_read(view, data);
3355 static struct view_ops diff_ops = {
3356         "line",
3357         diff_argv,
3358         NULL,
3359         diff_read,
3360         pager_draw,
3361         pager_request,
3362         pager_grep,
3363         pager_select,
3364 };
3366 /*
3367  * Help backend
3368  */
3370 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3372 static bool
3373 help_open_keymap_title(struct view *view, enum keymap keymap)
3375         struct line *line;
3377         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3378                                help_keymap_hidden[keymap] ? '+' : '-',
3379                                enum_name(keymap_table[keymap]));
3380         if (line)
3381                 line->other = keymap;
3383         return help_keymap_hidden[keymap];
3386 static void
3387 help_open_keymap(struct view *view, enum keymap keymap)
3389         const char *group = NULL;
3390         char buf[SIZEOF_STR];
3391         size_t bufpos;
3392         bool add_title = TRUE;
3393         int i;
3395         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3396                 const char *key = NULL;
3398                 if (req_info[i].request == REQ_NONE)
3399                         continue;
3401                 if (!req_info[i].request) {
3402                         group = req_info[i].help;
3403                         continue;
3404                 }
3406                 key = get_keys(keymap, req_info[i].request, TRUE);
3407                 if (!key || !*key)
3408                         continue;
3410                 if (add_title && help_open_keymap_title(view, keymap))
3411                         return;
3412                 add_title = FALSE;
3414                 if (group) {
3415                         add_line_text(view, group, LINE_HELP_GROUP);
3416                         group = NULL;
3417                 }
3419                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3420                                 enum_name(req_info[i]), req_info[i].help);
3421         }
3423         group = "External commands:";
3425         for (i = 0; i < run_requests; i++) {
3426                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3427                 const char *key;
3428                 int argc;
3430                 if (!req || req->keymap != keymap)
3431                         continue;
3433                 key = get_key_name(req->key);
3434                 if (!*key)
3435                         key = "(no key defined)";
3437                 if (add_title && help_open_keymap_title(view, keymap))
3438                         return;
3439                 if (group) {
3440                         add_line_text(view, group, LINE_HELP_GROUP);
3441                         group = NULL;
3442                 }
3444                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3445                         if (!string_format_from(buf, &bufpos, "%s%s",
3446                                                 argc ? " " : "", req->argv[argc]))
3447                                 return;
3449                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3450         }
3453 static bool
3454 help_open(struct view *view)
3456         enum keymap keymap;
3458         reset_view(view);
3459         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3460         add_line_text(view, "", LINE_DEFAULT);
3462         for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3463                 help_open_keymap(view, keymap);
3465         return TRUE;
3468 static enum request
3469 help_request(struct view *view, enum request request, struct line *line)
3471         switch (request) {
3472         case REQ_ENTER:
3473                 if (line->type == LINE_HELP_KEYMAP) {
3474                         help_keymap_hidden[line->other] =
3475                                 !help_keymap_hidden[line->other];
3476                         view->p_restore = TRUE;
3477                         open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3478                 }
3480                 return REQ_NONE;
3481         default:
3482                 return pager_request(view, request, line);
3483         }
3486 static struct view_ops help_ops = {
3487         "line",
3488         NULL,
3489         help_open,
3490         NULL,
3491         pager_draw,
3492         help_request,
3493         pager_grep,
3494         pager_select,
3495 };
3498 /*
3499  * Tree backend
3500  */
3502 struct tree_stack_entry {
3503         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3504         unsigned long lineno;           /* Line number to restore */
3505         char *name;                     /* Position of name in opt_path */
3506 };
3508 /* The top of the path stack. */
3509 static struct tree_stack_entry *tree_stack = NULL;
3510 unsigned long tree_lineno = 0;
3512 static void
3513 pop_tree_stack_entry(void)
3515         struct tree_stack_entry *entry = tree_stack;
3517         tree_lineno = entry->lineno;
3518         entry->name[0] = 0;
3519         tree_stack = entry->prev;
3520         free(entry);
3523 static void
3524 push_tree_stack_entry(const char *name, unsigned long lineno)
3526         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3527         size_t pathlen = strlen(opt_path);
3529         if (!entry)
3530                 return;
3532         entry->prev = tree_stack;
3533         entry->name = opt_path + pathlen;
3534         tree_stack = entry;
3536         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3537                 pop_tree_stack_entry();
3538                 return;
3539         }
3541         /* Move the current line to the first tree entry. */
3542         tree_lineno = 1;
3543         entry->lineno = lineno;
3546 /* Parse output from git-ls-tree(1):
3547  *
3548  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3549  */
3551 #define SIZEOF_TREE_ATTR \
3552         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3554 #define SIZEOF_TREE_MODE \
3555         STRING_SIZE("100644 ")
3557 #define TREE_ID_OFFSET \
3558         STRING_SIZE("100644 blob ")
3560 struct tree_entry {
3561         char id[SIZEOF_REV];
3562         mode_t mode;
3563         struct time time;               /* Date from the author ident. */
3564         const char *author;             /* Author of the commit. */
3565         char name[1];
3566 };
3568 static const char *
3569 tree_path(const struct line *line)
3571         return ((struct tree_entry *) line->data)->name;
3574 static int
3575 tree_compare_entry(const struct line *line1, const struct line *line2)
3577         if (line1->type != line2->type)
3578                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3579         return strcmp(tree_path(line1), tree_path(line2));
3582 static const enum sort_field tree_sort_fields[] = {
3583         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3584 };
3585 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3587 static int
3588 tree_compare(const void *l1, const void *l2)
3590         const struct line *line1 = (const struct line *) l1;
3591         const struct line *line2 = (const struct line *) l2;
3592         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3593         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3595         if (line1->type == LINE_TREE_HEAD)
3596                 return -1;
3597         if (line2->type == LINE_TREE_HEAD)
3598                 return 1;
3600         switch (get_sort_field(tree_sort_state)) {
3601         case ORDERBY_DATE:
3602                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3604         case ORDERBY_AUTHOR:
3605                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3607         case ORDERBY_NAME:
3608         default:
3609                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3610         }
3614 static struct line *
3615 tree_entry(struct view *view, enum line_type type, const char *path,
3616            const char *mode, const char *id)
3618         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3619         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3621         if (!entry || !line) {
3622                 free(entry);
3623                 return NULL;
3624         }
3626         strncpy(entry->name, path, strlen(path));
3627         if (mode)
3628                 entry->mode = strtoul(mode, NULL, 8);
3629         if (id)
3630                 string_copy_rev(entry->id, id);
3632         return line;
3635 static bool
3636 tree_read_date(struct view *view, char *text, bool *read_date)
3638         static const char *author_name;
3639         static struct time author_time;
3641         if (!text && *read_date) {
3642                 *read_date = FALSE;
3643                 return TRUE;
3645         } else if (!text) {
3646                 char *path = *opt_path ? opt_path : ".";
3647                 /* Find next entry to process */
3648                 const char *log_file[] = {
3649                         "git", "log", "--no-color", "--pretty=raw",
3650                                 "--cc", "--raw", view->id, "--", path, NULL
3651                 };
3653                 if (!view->lines) {
3654                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3655                         report("Tree is empty");
3656                         return TRUE;
3657                 }
3659                 if (!start_update(view, log_file, opt_cdup)) {
3660                         report("Failed to load tree data");
3661                         return TRUE;
3662                 }
3664                 *read_date = TRUE;
3665                 return FALSE;
3667         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3668                 parse_author_line(text + STRING_SIZE("author "),
3669                                   &author_name, &author_time);
3671         } else if (*text == ':') {
3672                 char *pos;
3673                 size_t annotated = 1;
3674                 size_t i;
3676                 pos = strchr(text, '\t');
3677                 if (!pos)
3678                         return TRUE;
3679                 text = pos + 1;
3680                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3681                         text += strlen(opt_path);
3682                 pos = strchr(text, '/');
3683                 if (pos)
3684                         *pos = 0;
3686                 for (i = 1; i < view->lines; i++) {
3687                         struct line *line = &view->line[i];
3688                         struct tree_entry *entry = line->data;
3690                         annotated += !!entry->author;
3691                         if (entry->author || strcmp(entry->name, text))
3692                                 continue;
3694                         entry->author = author_name;
3695                         entry->time = author_time;
3696                         line->dirty = 1;
3697                         break;
3698                 }
3700                 if (annotated == view->lines)
3701                         io_kill(view->pipe);
3702         }
3703         return TRUE;
3706 static bool
3707 tree_read(struct view *view, char *text)
3709         static bool read_date = FALSE;
3710         struct tree_entry *data;
3711         struct line *entry, *line;
3712         enum line_type type;
3713         size_t textlen = text ? strlen(text) : 0;
3714         char *path = text + SIZEOF_TREE_ATTR;
3716         if (read_date || !text)
3717                 return tree_read_date(view, text, &read_date);
3719         if (textlen <= SIZEOF_TREE_ATTR)
3720                 return FALSE;
3721         if (view->lines == 0 &&
3722             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3723                 return FALSE;
3725         /* Strip the path part ... */
3726         if (*opt_path) {
3727                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3728                 size_t striplen = strlen(opt_path);
3730                 if (pathlen > striplen)
3731                         memmove(path, path + striplen,
3732                                 pathlen - striplen + 1);
3734                 /* Insert "link" to parent directory. */
3735                 if (view->lines == 1 &&
3736                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3737                         return FALSE;
3738         }
3740         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3741         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3742         if (!entry)
3743                 return FALSE;
3744         data = entry->data;
3746         /* Skip "Directory ..." and ".." line. */
3747         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3748                 if (tree_compare_entry(line, entry) <= 0)
3749                         continue;
3751                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3753                 line->data = data;
3754                 line->type = type;
3755                 for (; line <= entry; line++)
3756                         line->dirty = line->cleareol = 1;
3757                 return TRUE;
3758         }
3760         if (tree_lineno > view->lineno) {
3761                 view->lineno = tree_lineno;
3762                 tree_lineno = 0;
3763         }
3765         return TRUE;
3768 static bool
3769 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3771         struct tree_entry *entry = line->data;
3773         if (line->type == LINE_TREE_HEAD) {
3774                 if (draw_text(view, line->type, "Directory path /"))
3775                         return TRUE;
3776         } else {
3777                 if (draw_mode(view, entry->mode))
3778                         return TRUE;
3780                 if (opt_author && draw_author(view, entry->author))
3781                         return TRUE;
3783                 if (opt_date && draw_date(view, &entry->time))
3784                         return TRUE;
3785         }
3787         draw_text(view, line->type, entry->name);
3788         return TRUE;
3791 static void
3792 open_blob_editor(const char *id)
3794         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3795         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3796         int fd = mkstemp(file);
3798         if (fd == -1)
3799                 report("Failed to create temporary file");
3800         else if (!io_run_append(blob_argv, fd))
3801                 report("Failed to save blob data to file");
3802         else
3803                 open_editor(file);
3804         if (fd != -1)
3805                 unlink(file);
3808 static enum request
3809 tree_request(struct view *view, enum request request, struct line *line)
3811         enum open_flags flags;
3812         struct tree_entry *entry = line->data;
3814         switch (request) {
3815         case REQ_VIEW_BLAME:
3816                 if (line->type != LINE_TREE_FILE) {
3817                         report("Blame only supported for files");
3818                         return REQ_NONE;
3819                 }
3821                 string_copy(opt_ref, view->vid);
3822                 return request;
3824         case REQ_EDIT:
3825                 if (line->type != LINE_TREE_FILE) {
3826                         report("Edit only supported for files");
3827                 } else if (!is_head_commit(view->vid)) {
3828                         open_blob_editor(entry->id);
3829                 } else {
3830                         open_editor(opt_file);
3831                 }
3832                 return REQ_NONE;
3834         case REQ_TOGGLE_SORT_FIELD:
3835         case REQ_TOGGLE_SORT_ORDER:
3836                 sort_view(view, request, &tree_sort_state, tree_compare);
3837                 return REQ_NONE;
3839         case REQ_PARENT:
3840                 if (!*opt_path) {
3841                         /* quit view if at top of tree */
3842                         return REQ_VIEW_CLOSE;
3843                 }
3844                 /* fake 'cd  ..' */
3845                 line = &view->line[1];
3846                 break;
3848         case REQ_ENTER:
3849                 break;
3851         default:
3852                 return request;
3853         }
3855         /* Cleanup the stack if the tree view is at a different tree. */
3856         while (!*opt_path && tree_stack)
3857                 pop_tree_stack_entry();
3859         switch (line->type) {
3860         case LINE_TREE_DIR:
3861                 /* Depending on whether it is a subdirectory or parent link
3862                  * mangle the path buffer. */
3863                 if (line == &view->line[1] && *opt_path) {
3864                         pop_tree_stack_entry();
3866                 } else {
3867                         const char *basename = tree_path(line);
3869                         push_tree_stack_entry(basename, view->lineno);
3870                 }
3872                 /* Trees and subtrees share the same ID, so they are not not
3873                  * unique like blobs. */
3874                 flags = OPEN_RELOAD;
3875                 request = REQ_VIEW_TREE;
3876                 break;
3878         case LINE_TREE_FILE:
3879                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3880                 request = REQ_VIEW_BLOB;
3881                 break;
3883         default:
3884                 return REQ_NONE;
3885         }
3887         open_view(view, request, flags);
3888         if (request == REQ_VIEW_TREE)
3889                 view->lineno = tree_lineno;
3891         return REQ_NONE;
3894 static bool
3895 tree_grep(struct view *view, struct line *line)
3897         struct tree_entry *entry = line->data;
3898         const char *text[] = {
3899                 entry->name,
3900                 opt_author ? entry->author : "",
3901                 mkdate(&entry->time, opt_date),
3902                 NULL
3903         };
3905         return grep_text(view, text);
3908 static void
3909 tree_select(struct view *view, struct line *line)
3911         struct tree_entry *entry = line->data;
3913         if (line->type == LINE_TREE_FILE) {
3914                 string_copy_rev(ref_blob, entry->id);
3915                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3917         } else if (line->type != LINE_TREE_DIR) {
3918                 return;
3919         }
3921         string_copy_rev(view->ref, entry->id);
3924 static bool
3925 tree_prepare(struct view *view)
3927         if (view->lines == 0 && opt_prefix[0]) {
3928                 char *pos = opt_prefix;
3930                 while (pos && *pos) {
3931                         char *end = strchr(pos, '/');
3933                         if (end)
3934                                 *end = 0;
3935                         push_tree_stack_entry(pos, 0);
3936                         pos = end;
3937                         if (end) {
3938                                 *end = '/';
3939                                 pos++;
3940                         }
3941                 }
3943         } else if (strcmp(view->vid, view->id)) {
3944                 opt_path[0] = 0;
3945         }
3947         return prepare_io(view, opt_cdup, view->ops->argv, TRUE);
3950 static const char *tree_argv[SIZEOF_ARG] = {
3951         "git", "ls-tree", "%(commit)", "%(directory)", NULL
3952 };
3954 static struct view_ops tree_ops = {
3955         "file",
3956         tree_argv,
3957         NULL,
3958         tree_read,
3959         tree_draw,
3960         tree_request,
3961         tree_grep,
3962         tree_select,
3963         tree_prepare,
3964 };
3966 static bool
3967 blob_read(struct view *view, char *line)
3969         if (!line)
3970                 return TRUE;
3971         return add_line_text(view, line, LINE_DEFAULT) != NULL;
3974 static enum request
3975 blob_request(struct view *view, enum request request, struct line *line)
3977         switch (request) {
3978         case REQ_EDIT:
3979                 open_blob_editor(view->vid);
3980                 return REQ_NONE;
3981         default:
3982                 return pager_request(view, request, line);
3983         }
3986 static const char *blob_argv[SIZEOF_ARG] = {
3987         "git", "cat-file", "blob", "%(blob)", NULL
3988 };
3990 static struct view_ops blob_ops = {
3991         "line",
3992         blob_argv,
3993         NULL,
3994         blob_read,
3995         pager_draw,
3996         blob_request,
3997         pager_grep,
3998         pager_select,
3999 };
4001 /*
4002  * Blame backend
4003  *
4004  * Loading the blame view is a two phase job:
4005  *
4006  *  1. File content is read either using opt_file from the
4007  *     filesystem or using git-cat-file.
4008  *  2. Then blame information is incrementally added by
4009  *     reading output from git-blame.
4010  */
4012 struct blame_commit {
4013         char id[SIZEOF_REV];            /* SHA1 ID. */
4014         char title[128];                /* First line of the commit message. */
4015         const char *author;             /* Author of the commit. */
4016         struct time time;               /* Date from the author ident. */
4017         char filename[128];             /* Name of file. */
4018         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4019         char parent_filename[128];      /* Parent/previous name of file. */
4020 };
4022 struct blame {
4023         struct blame_commit *commit;
4024         unsigned long lineno;
4025         char text[1];
4026 };
4028 static bool
4029 blame_open(struct view *view)
4031         char path[SIZEOF_STR];
4032         size_t i;
4034         if (!view->prev && *opt_prefix) {
4035                 string_copy(path, opt_file);
4036                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4037                         return FALSE;
4038         }
4040         if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4041                 const char *blame_cat_file_argv[] = {
4042                         "git", "cat-file", "blob", path, NULL
4043                 };
4045                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4046                     !start_update(view, blame_cat_file_argv, opt_cdup))
4047                         return FALSE;
4048         }
4050         /* First pass: remove multiple references to the same commit. */
4051         for (i = 0; i < view->lines; i++) {
4052                 struct blame *blame = view->line[i].data;
4054                 if (blame->commit && blame->commit->id[0])
4055                         blame->commit->id[0] = 0;
4056                 else
4057                         blame->commit = NULL;
4058         }
4060         /* Second pass: free existing references. */
4061         for (i = 0; i < view->lines; i++) {
4062                 struct blame *blame = view->line[i].data;
4064                 if (blame->commit)
4065                         free(blame->commit);
4066         }
4068         setup_update(view, opt_file);
4069         string_format(view->ref, "%s ...", opt_file);
4071         return TRUE;
4074 static struct blame_commit *
4075 get_blame_commit(struct view *view, const char *id)
4077         size_t i;
4079         for (i = 0; i < view->lines; i++) {
4080                 struct blame *blame = view->line[i].data;
4082                 if (!blame->commit)
4083                         continue;
4085                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4086                         return blame->commit;
4087         }
4089         {
4090                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4092                 if (commit)
4093                         string_ncopy(commit->id, id, SIZEOF_REV);
4094                 return commit;
4095         }
4098 static bool
4099 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4101         const char *pos = *posref;
4103         *posref = NULL;
4104         pos = strchr(pos + 1, ' ');
4105         if (!pos || !isdigit(pos[1]))
4106                 return FALSE;
4107         *number = atoi(pos + 1);
4108         if (*number < min || *number > max)
4109                 return FALSE;
4111         *posref = pos;
4112         return TRUE;
4115 static struct blame_commit *
4116 parse_blame_commit(struct view *view, const char *text, int *blamed)
4118         struct blame_commit *commit;
4119         struct blame *blame;
4120         const char *pos = text + SIZEOF_REV - 2;
4121         size_t orig_lineno = 0;
4122         size_t lineno;
4123         size_t group;
4125         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4126                 return NULL;
4128         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4129             !parse_number(&pos, &lineno, 1, view->lines) ||
4130             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4131                 return NULL;
4133         commit = get_blame_commit(view, text);
4134         if (!commit)
4135                 return NULL;
4137         *blamed += group;
4138         while (group--) {
4139                 struct line *line = &view->line[lineno + group - 1];
4141                 blame = line->data;
4142                 blame->commit = commit;
4143                 blame->lineno = orig_lineno + group - 1;
4144                 line->dirty = 1;
4145         }
4147         return commit;
4150 static bool
4151 blame_read_file(struct view *view, const char *line, bool *read_file)
4153         if (!line) {
4154                 const char *blame_argv[] = {
4155                         "git", "blame", "--incremental",
4156                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4157                 };
4159                 if (view->lines == 0 && !view->prev)
4160                         die("No blame exist for %s", view->vid);
4162                 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4163                         report("Failed to load blame data");
4164                         return TRUE;
4165                 }
4167                 *read_file = FALSE;
4168                 return FALSE;
4170         } else {
4171                 size_t linelen = strlen(line);
4172                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4174                 if (!blame)
4175                         return FALSE;
4177                 blame->commit = NULL;
4178                 strncpy(blame->text, line, linelen);
4179                 blame->text[linelen] = 0;
4180                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4181         }
4184 static bool
4185 match_blame_header(const char *name, char **line)
4187         size_t namelen = strlen(name);
4188         bool matched = !strncmp(name, *line, namelen);
4190         if (matched)
4191                 *line += namelen;
4193         return matched;
4196 static bool
4197 blame_read(struct view *view, char *line)
4199         static struct blame_commit *commit = NULL;
4200         static int blamed = 0;
4201         static bool read_file = TRUE;
4203         if (read_file)
4204                 return blame_read_file(view, line, &read_file);
4206         if (!line) {
4207                 /* Reset all! */
4208                 commit = NULL;
4209                 blamed = 0;
4210                 read_file = TRUE;
4211                 string_format(view->ref, "%s", view->vid);
4212                 if (view_is_displayed(view)) {
4213                         update_view_title(view);
4214                         redraw_view_from(view, 0);
4215                 }
4216                 return TRUE;
4217         }
4219         if (!commit) {
4220                 commit = parse_blame_commit(view, line, &blamed);
4221                 string_format(view->ref, "%s %2d%%", view->vid,
4222                               view->lines ? blamed * 100 / view->lines : 0);
4224         } else if (match_blame_header("author ", &line)) {
4225                 commit->author = get_author(line);
4227         } else if (match_blame_header("author-time ", &line)) {
4228                 parse_timesec(&commit->time, line);
4230         } else if (match_blame_header("author-tz ", &line)) {
4231                 parse_timezone(&commit->time, line);
4233         } else if (match_blame_header("summary ", &line)) {
4234                 string_ncopy(commit->title, line, strlen(line));
4236         } else if (match_blame_header("previous ", &line)) {
4237                 if (strlen(line) <= SIZEOF_REV)
4238                         return FALSE;
4239                 string_copy_rev(commit->parent_id, line);
4240                 line += SIZEOF_REV;
4241                 string_ncopy(commit->parent_filename, line, strlen(line));
4243         } else if (match_blame_header("filename ", &line)) {
4244                 string_ncopy(commit->filename, line, strlen(line));
4245                 commit = NULL;
4246         }
4248         return TRUE;
4251 static bool
4252 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4254         struct blame *blame = line->data;
4255         struct time *time = NULL;
4256         const char *id = NULL, *author = NULL;
4258         if (blame->commit && *blame->commit->filename) {
4259                 id = blame->commit->id;
4260                 author = blame->commit->author;
4261                 time = &blame->commit->time;
4262         }
4264         if (opt_date && draw_date(view, time))
4265                 return TRUE;
4267         if (opt_author && draw_author(view, author))
4268                 return TRUE;
4270         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4271                 return TRUE;
4273         if (draw_lineno(view, lineno))
4274                 return TRUE;
4276         draw_text(view, LINE_DEFAULT, blame->text);
4277         return TRUE;
4280 static bool
4281 check_blame_commit(struct blame *blame, bool check_null_id)
4283         if (!blame->commit)
4284                 report("Commit data not loaded yet");
4285         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4286                 report("No commit exist for the selected line");
4287         else
4288                 return TRUE;
4289         return FALSE;
4292 static void
4293 setup_blame_parent_line(struct view *view, struct blame *blame)
4295         char from[SIZEOF_REF + SIZEOF_STR];
4296         char to[SIZEOF_REF + SIZEOF_STR];
4297         const char *diff_tree_argv[] = {
4298                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4299                         "-U0", from, to, "--", NULL
4300         };
4301         struct io io;
4302         int parent_lineno = -1;
4303         int blamed_lineno = -1;
4304         char *line;
4306         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4307             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4308             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4309                 return;
4311         while ((line = io_get(&io, '\n', TRUE))) {
4312                 if (*line == '@') {
4313                         char *pos = strchr(line, '+');
4315                         parent_lineno = atoi(line + 4);
4316                         if (pos)
4317                                 blamed_lineno = atoi(pos + 1);
4319                 } else if (*line == '+' && parent_lineno != -1) {
4320                         if (blame->lineno == blamed_lineno - 1 &&
4321                             !strcmp(blame->text, line + 1)) {
4322                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4323                                 break;
4324                         }
4325                         blamed_lineno++;
4326                 }
4327         }
4329         io_done(&io);
4332 static enum request
4333 blame_request(struct view *view, enum request request, struct line *line)
4335         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4336         struct blame *blame = line->data;
4338         switch (request) {
4339         case REQ_VIEW_BLAME:
4340                 if (check_blame_commit(blame, TRUE)) {
4341                         string_copy(opt_ref, blame->commit->id);
4342                         string_copy(opt_file, blame->commit->filename);
4343                         if (blame->lineno)
4344                                 view->lineno = blame->lineno;
4345                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4346                 }
4347                 break;
4349         case REQ_PARENT:
4350                 if (!check_blame_commit(blame, TRUE))
4351                         break;
4352                 if (!*blame->commit->parent_id) {
4353                         report("The selected commit has no parents");
4354                 } else {
4355                         string_copy_rev(opt_ref, blame->commit->parent_id);
4356                         string_copy(opt_file, blame->commit->parent_filename);
4357                         setup_blame_parent_line(view, blame);
4358                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4359                 }
4360                 break;
4362         case REQ_ENTER:
4363                 if (!check_blame_commit(blame, FALSE))
4364                         break;
4366                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4367                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4368                         break;
4370                 if (!strcmp(blame->commit->id, NULL_ID)) {
4371                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4372                         const char *diff_index_argv[] = {
4373                                 "git", "diff-index", "--root", "--patch-with-stat",
4374                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4375                         };
4377                         if (!*blame->commit->parent_id) {
4378                                 diff_index_argv[1] = "diff";
4379                                 diff_index_argv[2] = "--no-color";
4380                                 diff_index_argv[6] = "--";
4381                                 diff_index_argv[7] = "/dev/null";
4382                         }
4384                         if (!prepare_update(diff, diff_index_argv, NULL)) {
4385                                 report("Failed to allocate diff command");
4386                                 break;
4387                         }
4388                         flags |= OPEN_PREPARED;
4389                 }
4391                 open_view(view, REQ_VIEW_DIFF, flags);
4392                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4393                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4394                 break;
4396         default:
4397                 return request;
4398         }
4400         return REQ_NONE;
4403 static bool
4404 blame_grep(struct view *view, struct line *line)
4406         struct blame *blame = line->data;
4407         struct blame_commit *commit = blame->commit;
4408         const char *text[] = {
4409                 blame->text,
4410                 commit ? commit->title : "",
4411                 commit ? commit->id : "",
4412                 commit && opt_author ? commit->author : "",
4413                 commit ? mkdate(&commit->time, opt_date) : "",
4414                 NULL
4415         };
4417         return grep_text(view, text);
4420 static void
4421 blame_select(struct view *view, struct line *line)
4423         struct blame *blame = line->data;
4424         struct blame_commit *commit = blame->commit;
4426         if (!commit)
4427                 return;
4429         if (!strcmp(commit->id, NULL_ID))
4430                 string_ncopy(ref_commit, "HEAD", 4);
4431         else
4432                 string_copy_rev(ref_commit, commit->id);
4435 static struct view_ops blame_ops = {
4436         "line",
4437         NULL,
4438         blame_open,
4439         blame_read,
4440         blame_draw,
4441         blame_request,
4442         blame_grep,
4443         blame_select,
4444 };
4446 /*
4447  * Branch backend
4448  */
4450 struct branch {
4451         const char *author;             /* Author of the last commit. */
4452         struct time time;               /* Date of the last activity. */
4453         const struct ref *ref;          /* Name and commit ID information. */
4454 };
4456 static const struct ref branch_all;
4458 static const enum sort_field branch_sort_fields[] = {
4459         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4460 };
4461 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4463 static int
4464 branch_compare(const void *l1, const void *l2)
4466         const struct branch *branch1 = ((const struct line *) l1)->data;
4467         const struct branch *branch2 = ((const struct line *) l2)->data;
4469         switch (get_sort_field(branch_sort_state)) {
4470         case ORDERBY_DATE:
4471                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4473         case ORDERBY_AUTHOR:
4474                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4476         case ORDERBY_NAME:
4477         default:
4478                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4479         }
4482 static bool
4483 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4485         struct branch *branch = line->data;
4486         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4488         if (opt_date && draw_date(view, &branch->time))
4489                 return TRUE;
4491         if (opt_author && draw_author(view, branch->author))
4492                 return TRUE;
4494         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4495         return TRUE;
4498 static enum request
4499 branch_request(struct view *view, enum request request, struct line *line)
4501         struct branch *branch = line->data;
4503         switch (request) {
4504         case REQ_REFRESH:
4505                 load_refs();
4506                 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4507                 return REQ_NONE;
4509         case REQ_TOGGLE_SORT_FIELD:
4510         case REQ_TOGGLE_SORT_ORDER:
4511                 sort_view(view, request, &branch_sort_state, branch_compare);
4512                 return REQ_NONE;
4514         case REQ_ENTER:
4515         {
4516                 const struct ref *ref = branch->ref;
4517                 const char *all_branches_argv[] = {
4518                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4519                               "--topo-order",
4520                               ref == &branch_all ? "--all" : ref->name, NULL
4521                 };
4522                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4524                 if (!prepare_update(main_view, all_branches_argv, NULL))
4525                         report("Failed to load view of all branches");
4526                 else
4527                         open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4528                 return REQ_NONE;
4529         }
4530         default:
4531                 return request;
4532         }
4535 static bool
4536 branch_read(struct view *view, char *line)
4538         static char id[SIZEOF_REV];
4539         struct branch *reference;
4540         size_t i;
4542         if (!line)
4543                 return TRUE;
4545         switch (get_line_type(line)) {
4546         case LINE_COMMIT:
4547                 string_copy_rev(id, line + STRING_SIZE("commit "));
4548                 return TRUE;
4550         case LINE_AUTHOR:
4551                 for (i = 0, reference = NULL; i < view->lines; i++) {
4552                         struct branch *branch = view->line[i].data;
4554                         if (strcmp(branch->ref->id, id))
4555                                 continue;
4557                         view->line[i].dirty = TRUE;
4558                         if (reference) {
4559                                 branch->author = reference->author;
4560                                 branch->time = reference->time;
4561                                 continue;
4562                         }
4564                         parse_author_line(line + STRING_SIZE("author "),
4565                                           &branch->author, &branch->time);
4566                         reference = branch;
4567                 }
4568                 return TRUE;
4570         default:
4571                 return TRUE;
4572         }
4576 static bool
4577 branch_open_visitor(void *data, const struct ref *ref)
4579         struct view *view = data;
4580         struct branch *branch;
4582         if (ref->tag || ref->ltag || ref->remote)
4583                 return TRUE;
4585         branch = calloc(1, sizeof(*branch));
4586         if (!branch)
4587                 return FALSE;
4589         branch->ref = ref;
4590         return !!add_line_data(view, branch, LINE_DEFAULT);
4593 static bool
4594 branch_open(struct view *view)
4596         const char *branch_log[] = {
4597                 "git", "log", "--no-color", "--pretty=raw",
4598                         "--simplify-by-decoration", "--all", NULL
4599         };
4601         if (!start_update(view, branch_log, NULL)) {
4602                 report("Failed to load branch data");
4603                 return TRUE;
4604         }
4606         setup_update(view, view->id);
4607         branch_open_visitor(view, &branch_all);
4608         foreach_ref(branch_open_visitor, view);
4609         view->p_restore = TRUE;
4611         return TRUE;
4614 static bool
4615 branch_grep(struct view *view, struct line *line)
4617         struct branch *branch = line->data;
4618         const char *text[] = {
4619                 branch->ref->name,
4620                 branch->author,
4621                 NULL
4622         };
4624         return grep_text(view, text);
4627 static void
4628 branch_select(struct view *view, struct line *line)
4630         struct branch *branch = line->data;
4632         string_copy_rev(view->ref, branch->ref->id);
4633         string_copy_rev(ref_commit, branch->ref->id);
4634         string_copy_rev(ref_head, branch->ref->id);
4635         string_copy_rev(ref_branch, branch->ref->name);
4638 static struct view_ops branch_ops = {
4639         "branch",
4640         NULL,
4641         branch_open,
4642         branch_read,
4643         branch_draw,
4644         branch_request,
4645         branch_grep,
4646         branch_select,
4647 };
4649 /*
4650  * Status backend
4651  */
4653 struct status {
4654         char status;
4655         struct {
4656                 mode_t mode;
4657                 char rev[SIZEOF_REV];
4658                 char name[SIZEOF_STR];
4659         } old;
4660         struct {
4661                 mode_t mode;
4662                 char rev[SIZEOF_REV];
4663                 char name[SIZEOF_STR];
4664         } new;
4665 };
4667 static char status_onbranch[SIZEOF_STR];
4668 static struct status stage_status;
4669 static enum line_type stage_line_type;
4670 static size_t stage_chunks;
4671 static int *stage_chunk;
4673 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4675 /* This should work even for the "On branch" line. */
4676 static inline bool
4677 status_has_none(struct view *view, struct line *line)
4679         return line < view->line + view->lines && !line[1].data;
4682 /* Get fields from the diff line:
4683  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4684  */
4685 static inline bool
4686 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4688         const char *old_mode = buf +  1;
4689         const char *new_mode = buf +  8;
4690         const char *old_rev  = buf + 15;
4691         const char *new_rev  = buf + 56;
4692         const char *status   = buf + 97;
4694         if (bufsize < 98 ||
4695             old_mode[-1] != ':' ||
4696             new_mode[-1] != ' ' ||
4697             old_rev[-1]  != ' ' ||
4698             new_rev[-1]  != ' ' ||
4699             status[-1]   != ' ')
4700                 return FALSE;
4702         file->status = *status;
4704         string_copy_rev(file->old.rev, old_rev);
4705         string_copy_rev(file->new.rev, new_rev);
4707         file->old.mode = strtoul(old_mode, NULL, 8);
4708         file->new.mode = strtoul(new_mode, NULL, 8);
4710         file->old.name[0] = file->new.name[0] = 0;
4712         return TRUE;
4715 static bool
4716 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4718         struct status *unmerged = NULL;
4719         char *buf;
4720         struct io io;
4722         if (!io_run(&io, IO_RD, opt_cdup, argv))
4723                 return FALSE;
4725         add_line_data(view, NULL, type);
4727         while ((buf = io_get(&io, 0, TRUE))) {
4728                 struct status *file = unmerged;
4730                 if (!file) {
4731                         file = calloc(1, sizeof(*file));
4732                         if (!file || !add_line_data(view, file, type))
4733                                 goto error_out;
4734                 }
4736                 /* Parse diff info part. */
4737                 if (status) {
4738                         file->status = status;
4739                         if (status == 'A')
4740                                 string_copy(file->old.rev, NULL_ID);
4742                 } else if (!file->status || file == unmerged) {
4743                         if (!status_get_diff(file, buf, strlen(buf)))
4744                                 goto error_out;
4746                         buf = io_get(&io, 0, TRUE);
4747                         if (!buf)
4748                                 break;
4750                         /* Collapse all modified entries that follow an
4751                          * associated unmerged entry. */
4752                         if (unmerged == file) {
4753                                 unmerged->status = 'U';
4754                                 unmerged = NULL;
4755                         } else if (file->status == 'U') {
4756                                 unmerged = file;
4757                         }
4758                 }
4760                 /* Grab the old name for rename/copy. */
4761                 if (!*file->old.name &&
4762                     (file->status == 'R' || file->status == 'C')) {
4763                         string_ncopy(file->old.name, buf, strlen(buf));
4765                         buf = io_get(&io, 0, TRUE);
4766                         if (!buf)
4767                                 break;
4768                 }
4770                 /* git-ls-files just delivers a NUL separated list of
4771                  * file names similar to the second half of the
4772                  * git-diff-* output. */
4773                 string_ncopy(file->new.name, buf, strlen(buf));
4774                 if (!*file->old.name)
4775                         string_copy(file->old.name, file->new.name);
4776                 file = NULL;
4777         }
4779         if (io_error(&io)) {
4780 error_out:
4781                 io_done(&io);
4782                 return FALSE;
4783         }
4785         if (!view->line[view->lines - 1].data)
4786                 add_line_data(view, NULL, LINE_STAT_NONE);
4788         io_done(&io);
4789         return TRUE;
4792 /* Don't show unmerged entries in the staged section. */
4793 static const char *status_diff_index_argv[] = {
4794         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4795                              "--cached", "-M", "HEAD", NULL
4796 };
4798 static const char *status_diff_files_argv[] = {
4799         "git", "diff-files", "-z", NULL
4800 };
4802 static const char *status_list_other_argv[] = {
4803         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4804 };
4806 static const char *status_list_no_head_argv[] = {
4807         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4808 };
4810 static const char *update_index_argv[] = {
4811         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4812 };
4814 /* Restore the previous line number to stay in the context or select a
4815  * line with something that can be updated. */
4816 static void
4817 status_restore(struct view *view)
4819         if (view->p_lineno >= view->lines)
4820                 view->p_lineno = view->lines - 1;
4821         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4822                 view->p_lineno++;
4823         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4824                 view->p_lineno--;
4826         /* If the above fails, always skip the "On branch" line. */
4827         if (view->p_lineno < view->lines)
4828                 view->lineno = view->p_lineno;
4829         else
4830                 view->lineno = 1;
4832         if (view->lineno < view->offset)
4833                 view->offset = view->lineno;
4834         else if (view->offset + view->height <= view->lineno)
4835                 view->offset = view->lineno - view->height + 1;
4837         view->p_restore = FALSE;
4840 static void
4841 status_update_onbranch(void)
4843         static const char *paths[][2] = {
4844                 { "rebase-apply/rebasing",      "Rebasing" },
4845                 { "rebase-apply/applying",      "Applying mailbox" },
4846                 { "rebase-apply/",              "Rebasing mailbox" },
4847                 { "rebase-merge/interactive",   "Interactive rebase" },
4848                 { "rebase-merge/",              "Rebase merge" },
4849                 { "MERGE_HEAD",                 "Merging" },
4850                 { "BISECT_LOG",                 "Bisecting" },
4851                 { "HEAD",                       "On branch" },
4852         };
4853         char buf[SIZEOF_STR];
4854         struct stat stat;
4855         int i;
4857         if (is_initial_commit()) {
4858                 string_copy(status_onbranch, "Initial commit");
4859                 return;
4860         }
4862         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4863                 char *head = opt_head;
4865                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4866                     lstat(buf, &stat) < 0)
4867                         continue;
4869                 if (!*opt_head) {
4870                         struct io io;
4872                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4873                             io_read_buf(&io, buf, sizeof(buf))) {
4874                                 head = buf;
4875                                 if (!prefixcmp(head, "refs/heads/"))
4876                                         head += STRING_SIZE("refs/heads/");
4877                         }
4878                 }
4880                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4881                         string_copy(status_onbranch, opt_head);
4882                 return;
4883         }
4885         string_copy(status_onbranch, "Not currently on any branch");
4888 /* First parse staged info using git-diff-index(1), then parse unstaged
4889  * info using git-diff-files(1), and finally untracked files using
4890  * git-ls-files(1). */
4891 static bool
4892 status_open(struct view *view)
4894         reset_view(view);
4896         add_line_data(view, NULL, LINE_STAT_HEAD);
4897         status_update_onbranch();
4899         io_run_bg(update_index_argv);
4901         if (is_initial_commit()) {
4902                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4903                         return FALSE;
4904         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4905                 return FALSE;
4906         }
4908         if (!opt_untracked_dirs_content)
4909                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4911         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4912             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4913                 return FALSE;
4915         /* Restore the exact position or use the specialized restore
4916          * mode? */
4917         if (!view->p_restore)
4918                 status_restore(view);
4919         return TRUE;
4922 static bool
4923 status_draw(struct view *view, struct line *line, unsigned int lineno)
4925         struct status *status = line->data;
4926         enum line_type type;
4927         const char *text;
4929         if (!status) {
4930                 switch (line->type) {
4931                 case LINE_STAT_STAGED:
4932                         type = LINE_STAT_SECTION;
4933                         text = "Changes to be committed:";
4934                         break;
4936                 case LINE_STAT_UNSTAGED:
4937                         type = LINE_STAT_SECTION;
4938                         text = "Changed but not updated:";
4939                         break;
4941                 case LINE_STAT_UNTRACKED:
4942                         type = LINE_STAT_SECTION;
4943                         text = "Untracked files:";
4944                         break;
4946                 case LINE_STAT_NONE:
4947                         type = LINE_DEFAULT;
4948                         text = "  (no files)";
4949                         break;
4951                 case LINE_STAT_HEAD:
4952                         type = LINE_STAT_HEAD;
4953                         text = status_onbranch;
4954                         break;
4956                 default:
4957                         return FALSE;
4958                 }
4959         } else {
4960                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
4962                 buf[0] = status->status;
4963                 if (draw_text(view, line->type, buf))
4964                         return TRUE;
4965                 type = LINE_DEFAULT;
4966                 text = status->new.name;
4967         }
4969         draw_text(view, type, text);
4970         return TRUE;
4973 static enum request
4974 status_load_error(struct view *view, struct view *stage, const char *path)
4976         if (displayed_views() == 2 || display[current_view] != view)
4977                 maximize_view(view);
4978         report("Failed to load '%s': %s", path, io_strerror(&stage->io));
4979         return REQ_NONE;
4982 static enum request
4983 status_enter(struct view *view, struct line *line)
4985         struct status *status = line->data;
4986         const char *oldpath = status ? status->old.name : NULL;
4987         /* Diffs for unmerged entries are empty when passing the new
4988          * path, so leave it empty. */
4989         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
4990         const char *info;
4991         enum open_flags split;
4992         struct view *stage = VIEW(REQ_VIEW_STAGE);
4994         if (line->type == LINE_STAT_NONE ||
4995             (!status && line[1].type == LINE_STAT_NONE)) {
4996                 report("No file to diff");
4997                 return REQ_NONE;
4998         }
5000         switch (line->type) {
5001         case LINE_STAT_STAGED:
5002                 if (is_initial_commit()) {
5003                         const char *no_head_diff_argv[] = {
5004                                 "git", "diff", "--no-color", "--patch-with-stat",
5005                                         "--", "/dev/null", newpath, NULL
5006                         };
5008                         if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5009                                 return status_load_error(view, stage, newpath);
5010                 } else {
5011                         const char *index_show_argv[] = {
5012                                 "git", "diff-index", "--root", "--patch-with-stat",
5013                                         "-C", "-M", "--cached", "HEAD", "--",
5014                                         oldpath, newpath, NULL
5015                         };
5017                         if (!prepare_update(stage, index_show_argv, opt_cdup))
5018                                 return status_load_error(view, stage, newpath);
5019                 }
5021                 if (status)
5022                         info = "Staged changes to %s";
5023                 else
5024                         info = "Staged changes";
5025                 break;
5027         case LINE_STAT_UNSTAGED:
5028         {
5029                 const char *files_show_argv[] = {
5030                         "git", "diff-files", "--root", "--patch-with-stat",
5031                                 "-C", "-M", "--", oldpath, newpath, NULL
5032                 };
5034                 if (!prepare_update(stage, files_show_argv, opt_cdup))
5035                         return status_load_error(view, stage, newpath);
5036                 if (status)
5037                         info = "Unstaged changes to %s";
5038                 else
5039                         info = "Unstaged changes";
5040                 break;
5041         }
5042         case LINE_STAT_UNTRACKED:
5043                 if (!newpath) {
5044                         report("No file to show");
5045                         return REQ_NONE;
5046                 }
5048                 if (!suffixcmp(status->new.name, -1, "/")) {
5049                         report("Cannot display a directory");
5050                         return REQ_NONE;
5051                 }
5053                 if (!prepare_update_file(stage, newpath))
5054                         return status_load_error(view, stage, newpath);
5055                 info = "Untracked file %s";
5056                 break;
5058         case LINE_STAT_HEAD:
5059                 return REQ_NONE;
5061         default:
5062                 die("line type %d not handled in switch", line->type);
5063         }
5065         split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5066         open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5067         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5068                 if (status) {
5069                         stage_status = *status;
5070                 } else {
5071                         memset(&stage_status, 0, sizeof(stage_status));
5072                 }
5074                 stage_line_type = line->type;
5075                 stage_chunks = 0;
5076                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5077         }
5079         return REQ_NONE;
5082 static bool
5083 status_exists(struct status *status, enum line_type type)
5085         struct view *view = VIEW(REQ_VIEW_STATUS);
5086         unsigned long lineno;
5088         for (lineno = 0; lineno < view->lines; lineno++) {
5089                 struct line *line = &view->line[lineno];
5090                 struct status *pos = line->data;
5092                 if (line->type != type)
5093                         continue;
5094                 if (!pos && (!status || !status->status) && line[1].data) {
5095                         select_view_line(view, lineno);
5096                         return TRUE;
5097                 }
5098                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5099                         select_view_line(view, lineno);
5100                         return TRUE;
5101                 }
5102         }
5104         return FALSE;
5108 static bool
5109 status_update_prepare(struct io *io, enum line_type type)
5111         const char *staged_argv[] = {
5112                 "git", "update-index", "-z", "--index-info", NULL
5113         };
5114         const char *others_argv[] = {
5115                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5116         };
5118         switch (type) {
5119         case LINE_STAT_STAGED:
5120                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5122         case LINE_STAT_UNSTAGED:
5123         case LINE_STAT_UNTRACKED:
5124                 return io_run(io, IO_WR, opt_cdup, others_argv);
5126         default:
5127                 die("line type %d not handled in switch", type);
5128                 return FALSE;
5129         }
5132 static bool
5133 status_update_write(struct io *io, struct status *status, enum line_type type)
5135         char buf[SIZEOF_STR];
5136         size_t bufsize = 0;
5138         switch (type) {
5139         case LINE_STAT_STAGED:
5140                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5141                                         status->old.mode,
5142                                         status->old.rev,
5143                                         status->old.name, 0))
5144                         return FALSE;
5145                 break;
5147         case LINE_STAT_UNSTAGED:
5148         case LINE_STAT_UNTRACKED:
5149                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5150                         return FALSE;
5151                 break;
5153         default:
5154                 die("line type %d not handled in switch", type);
5155         }
5157         return io_write(io, buf, bufsize);
5160 static bool
5161 status_update_file(struct status *status, enum line_type type)
5163         struct io io;
5164         bool result;
5166         if (!status_update_prepare(&io, type))
5167                 return FALSE;
5169         result = status_update_write(&io, status, type);
5170         return io_done(&io) && result;
5173 static bool
5174 status_update_files(struct view *view, struct line *line)
5176         char buf[sizeof(view->ref)];
5177         struct io io;
5178         bool result = TRUE;
5179         struct line *pos = view->line + view->lines;
5180         int files = 0;
5181         int file, done;
5182         int cursor_y = -1, cursor_x = -1;
5184         if (!status_update_prepare(&io, line->type))
5185                 return FALSE;
5187         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5188                 files++;
5190         string_copy(buf, view->ref);
5191         getsyx(cursor_y, cursor_x);
5192         for (file = 0, done = 5; result && file < files; line++, file++) {
5193                 int almost_done = file * 100 / files;
5195                 if (almost_done > done) {
5196                         done = almost_done;
5197                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5198                                       file, files, done);
5199                         update_view_title(view);
5200                         setsyx(cursor_y, cursor_x);
5201                         doupdate();
5202                 }
5203                 result = status_update_write(&io, line->data, line->type);
5204         }
5205         string_copy(view->ref, buf);
5207         return io_done(&io) && result;
5210 static bool
5211 status_update(struct view *view)
5213         struct line *line = &view->line[view->lineno];
5215         assert(view->lines);
5217         if (!line->data) {
5218                 /* This should work even for the "On branch" line. */
5219                 if (line < view->line + view->lines && !line[1].data) {
5220                         report("Nothing to update");
5221                         return FALSE;
5222                 }
5224                 if (!status_update_files(view, line + 1)) {
5225                         report("Failed to update file status");
5226                         return FALSE;
5227                 }
5229         } else if (!status_update_file(line->data, line->type)) {
5230                 report("Failed to update file status");
5231                 return FALSE;
5232         }
5234         return TRUE;
5237 static bool
5238 status_revert(struct status *status, enum line_type type, bool has_none)
5240         if (!status || type != LINE_STAT_UNSTAGED) {
5241                 if (type == LINE_STAT_STAGED) {
5242                         report("Cannot revert changes to staged files");
5243                 } else if (type == LINE_STAT_UNTRACKED) {
5244                         report("Cannot revert changes to untracked files");
5245                 } else if (has_none) {
5246                         report("Nothing to revert");
5247                 } else {
5248                         report("Cannot revert changes to multiple files");
5249                 }
5251         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5252                 char mode[10] = "100644";
5253                 const char *reset_argv[] = {
5254                         "git", "update-index", "--cacheinfo", mode,
5255                                 status->old.rev, status->old.name, NULL
5256                 };
5257                 const char *checkout_argv[] = {
5258                         "git", "checkout", "--", status->old.name, NULL
5259                 };
5261                 if (status->status == 'U') {
5262                         string_format(mode, "%5o", status->old.mode);
5264                         if (status->old.mode == 0 && status->new.mode == 0) {
5265                                 reset_argv[2] = "--force-remove";
5266                                 reset_argv[3] = status->old.name;
5267                                 reset_argv[4] = NULL;
5268                         }
5270                         if (!io_run_fg(reset_argv, opt_cdup))
5271                                 return FALSE;
5272                         if (status->old.mode == 0 && status->new.mode == 0)
5273                                 return TRUE;
5274                 }
5276                 return io_run_fg(checkout_argv, opt_cdup);
5277         }
5279         return FALSE;
5282 static enum request
5283 status_request(struct view *view, enum request request, struct line *line)
5285         struct status *status = line->data;
5287         switch (request) {
5288         case REQ_STATUS_UPDATE:
5289                 if (!status_update(view))
5290                         return REQ_NONE;
5291                 break;
5293         case REQ_STATUS_REVERT:
5294                 if (!status_revert(status, line->type, status_has_none(view, line)))
5295                         return REQ_NONE;
5296                 break;
5298         case REQ_STATUS_MERGE:
5299                 if (!status || status->status != 'U') {
5300                         report("Merging only possible for files with unmerged status ('U').");
5301                         return REQ_NONE;
5302                 }
5303                 open_mergetool(status->new.name);
5304                 break;
5306         case REQ_EDIT:
5307                 if (!status)
5308                         return request;
5309                 if (status->status == 'D') {
5310                         report("File has been deleted.");
5311                         return REQ_NONE;
5312                 }
5314                 open_editor(status->new.name);
5315                 break;
5317         case REQ_VIEW_BLAME:
5318                 if (status)
5319                         opt_ref[0] = 0;
5320                 return request;
5322         case REQ_ENTER:
5323                 /* After returning the status view has been split to
5324                  * show the stage view. No further reloading is
5325                  * necessary. */
5326                 return status_enter(view, line);
5328         case REQ_REFRESH:
5329                 /* Simply reload the view. */
5330                 break;
5332         default:
5333                 return request;
5334         }
5336         open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5338         return REQ_NONE;
5341 static void
5342 status_select(struct view *view, struct line *line)
5344         struct status *status = line->data;
5345         char file[SIZEOF_STR] = "all files";
5346         const char *text;
5347         const char *key;
5349         if (status && !string_format(file, "'%s'", status->new.name))
5350                 return;
5352         if (!status && line[1].type == LINE_STAT_NONE)
5353                 line++;
5355         switch (line->type) {
5356         case LINE_STAT_STAGED:
5357                 text = "Press %s to unstage %s for commit";
5358                 break;
5360         case LINE_STAT_UNSTAGED:
5361                 text = "Press %s to stage %s for commit";
5362                 break;
5364         case LINE_STAT_UNTRACKED:
5365                 text = "Press %s to stage %s for addition";
5366                 break;
5368         case LINE_STAT_HEAD:
5369         case LINE_STAT_NONE:
5370                 text = "Nothing to update";
5371                 break;
5373         default:
5374                 die("line type %d not handled in switch", line->type);
5375         }
5377         if (status && status->status == 'U') {
5378                 text = "Press %s to resolve conflict in %s";
5379                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5381         } else {
5382                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5383         }
5385         string_format(view->ref, text, key, file);
5386         if (status)
5387                 string_copy(opt_file, status->new.name);
5390 static bool
5391 status_grep(struct view *view, struct line *line)
5393         struct status *status = line->data;
5395         if (status) {
5396                 const char buf[2] = { status->status, 0 };
5397                 const char *text[] = { status->new.name, buf, NULL };
5399                 return grep_text(view, text);
5400         }
5402         return FALSE;
5405 static struct view_ops status_ops = {
5406         "file",
5407         NULL,
5408         status_open,
5409         NULL,
5410         status_draw,
5411         status_request,
5412         status_grep,
5413         status_select,
5414 };
5417 static bool
5418 stage_diff_write(struct io *io, struct line *line, struct line *end)
5420         while (line < end) {
5421                 if (!io_write(io, line->data, strlen(line->data)) ||
5422                     !io_write(io, "\n", 1))
5423                         return FALSE;
5424                 line++;
5425                 if (line->type == LINE_DIFF_CHUNK ||
5426                     line->type == LINE_DIFF_HEADER)
5427                         break;
5428         }
5430         return TRUE;
5433 static struct line *
5434 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5436         for (; view->line < line; line--)
5437                 if (line->type == type)
5438                         return line;
5440         return NULL;
5443 static bool
5444 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5446         const char *apply_argv[SIZEOF_ARG] = {
5447                 "git", "apply", "--whitespace=nowarn", NULL
5448         };
5449         struct line *diff_hdr;
5450         struct io io;
5451         int argc = 3;
5453         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5454         if (!diff_hdr)
5455                 return FALSE;
5457         if (!revert)
5458                 apply_argv[argc++] = "--cached";
5459         if (revert || stage_line_type == LINE_STAT_STAGED)
5460                 apply_argv[argc++] = "-R";
5461         apply_argv[argc++] = "-";
5462         apply_argv[argc++] = NULL;
5463         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5464                 return FALSE;
5466         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5467             !stage_diff_write(&io, chunk, view->line + view->lines))
5468                 chunk = NULL;
5470         io_done(&io);
5471         io_run_bg(update_index_argv);
5473         return chunk ? TRUE : FALSE;
5476 static bool
5477 stage_update(struct view *view, struct line *line)
5479         struct line *chunk = NULL;
5481         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5482                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5484         if (chunk) {
5485                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5486                         report("Failed to apply chunk");
5487                         return FALSE;
5488                 }
5490         } else if (!stage_status.status) {
5491                 view = VIEW(REQ_VIEW_STATUS);
5493                 for (line = view->line; line < view->line + view->lines; line++)
5494                         if (line->type == stage_line_type)
5495                                 break;
5497                 if (!status_update_files(view, line + 1)) {
5498                         report("Failed to update files");
5499                         return FALSE;
5500                 }
5502         } else if (!status_update_file(&stage_status, stage_line_type)) {
5503                 report("Failed to update file");
5504                 return FALSE;
5505         }
5507         return TRUE;
5510 static bool
5511 stage_revert(struct view *view, struct line *line)
5513         struct line *chunk = NULL;
5515         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5516                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5518         if (chunk) {
5519                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5520                         return FALSE;
5522                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5523                         report("Failed to revert chunk");
5524                         return FALSE;
5525                 }
5526                 return TRUE;
5528         } else {
5529                 return status_revert(stage_status.status ? &stage_status : NULL,
5530                                      stage_line_type, FALSE);
5531         }
5535 static void
5536 stage_next(struct view *view, struct line *line)
5538         int i;
5540         if (!stage_chunks) {
5541                 for (line = view->line; line < view->line + view->lines; line++) {
5542                         if (line->type != LINE_DIFF_CHUNK)
5543                                 continue;
5545                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5546                                 report("Allocation failure");
5547                                 return;
5548                         }
5550                         stage_chunk[stage_chunks++] = line - view->line;
5551                 }
5552         }
5554         for (i = 0; i < stage_chunks; i++) {
5555                 if (stage_chunk[i] > view->lineno) {
5556                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5557                         report("Chunk %d of %d", i + 1, stage_chunks);
5558                         return;
5559                 }
5560         }
5562         report("No next chunk found");
5565 static enum request
5566 stage_request(struct view *view, enum request request, struct line *line)
5568         switch (request) {
5569         case REQ_STATUS_UPDATE:
5570                 if (!stage_update(view, line))
5571                         return REQ_NONE;
5572                 break;
5574         case REQ_STATUS_REVERT:
5575                 if (!stage_revert(view, line))
5576                         return REQ_NONE;
5577                 break;
5579         case REQ_STAGE_NEXT:
5580                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5581                         report("File is untracked; press %s to add",
5582                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5583                         return REQ_NONE;
5584                 }
5585                 stage_next(view, line);
5586                 return REQ_NONE;
5588         case REQ_EDIT:
5589                 if (!stage_status.new.name[0])
5590                         return request;
5591                 if (stage_status.status == 'D') {
5592                         report("File has been deleted.");
5593                         return REQ_NONE;
5594                 }
5596                 open_editor(stage_status.new.name);
5597                 break;
5599         case REQ_REFRESH:
5600                 /* Reload everything ... */
5601                 break;
5603         case REQ_VIEW_BLAME:
5604                 if (stage_status.new.name[0]) {
5605                         string_copy(opt_file, stage_status.new.name);
5606                         opt_ref[0] = 0;
5607                 }
5608                 return request;
5610         case REQ_ENTER:
5611                 return pager_request(view, request, line);
5613         default:
5614                 return request;
5615         }
5617         VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
5618         open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
5620         /* Check whether the staged entry still exists, and close the
5621          * stage view if it doesn't. */
5622         if (!status_exists(&stage_status, stage_line_type)) {
5623                 status_restore(VIEW(REQ_VIEW_STATUS));
5624                 return REQ_VIEW_CLOSE;
5625         }
5627         if (stage_line_type == LINE_STAT_UNTRACKED) {
5628                 if (!suffixcmp(stage_status.new.name, -1, "/")) {
5629                         report("Cannot display a directory");
5630                         return REQ_NONE;
5631                 }
5633                 if (!prepare_update_file(view, stage_status.new.name)) {
5634                         report("Failed to open file: %s", strerror(errno));
5635                         return REQ_NONE;
5636                 }
5637         }
5638         open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
5640         return REQ_NONE;
5643 static struct view_ops stage_ops = {
5644         "line",
5645         NULL,
5646         NULL,
5647         pager_read,
5648         pager_draw,
5649         stage_request,
5650         pager_grep,
5651         pager_select,
5652 };
5655 /*
5656  * Revision graph
5657  */
5659 struct commit {
5660         char id[SIZEOF_REV];            /* SHA1 ID. */
5661         char title[128];                /* First line of the commit message. */
5662         const char *author;             /* Author of the commit. */
5663         struct time time;               /* Date from the author ident. */
5664         struct ref_list *refs;          /* Repository references. */
5665         chtype graph[SIZEOF_REVGRAPH];  /* Ancestry chain graphics. */
5666         size_t graph_size;              /* The width of the graph array. */
5667         bool has_parents;               /* Rewritten --parents seen. */
5668 };
5670 /* Size of rev graph with no  "padding" columns */
5671 #define SIZEOF_REVITEMS (SIZEOF_REVGRAPH - (SIZEOF_REVGRAPH / 2))
5673 struct rev_graph {
5674         struct rev_graph *prev, *next, *parents;
5675         char rev[SIZEOF_REVITEMS][SIZEOF_REV];
5676         size_t size;
5677         struct commit *commit;
5678         size_t pos;
5679         unsigned int boundary:1;
5680 };
5682 /* Parents of the commit being visualized. */
5683 static struct rev_graph graph_parents[4];
5685 /* The current stack of revisions on the graph. */
5686 static struct rev_graph graph_stacks[4] = {
5687         { &graph_stacks[3], &graph_stacks[1], &graph_parents[0] },
5688         { &graph_stacks[0], &graph_stacks[2], &graph_parents[1] },
5689         { &graph_stacks[1], &graph_stacks[3], &graph_parents[2] },
5690         { &graph_stacks[2], &graph_stacks[0], &graph_parents[3] },
5691 };
5693 static inline bool
5694 graph_parent_is_merge(struct rev_graph *graph)
5696         return graph->parents->size > 1;
5699 static inline void
5700 append_to_rev_graph(struct rev_graph *graph, chtype symbol)
5702         struct commit *commit = graph->commit;
5704         if (commit->graph_size < ARRAY_SIZE(commit->graph) - 1)
5705                 commit->graph[commit->graph_size++] = symbol;
5708 static void
5709 clear_rev_graph(struct rev_graph *graph)
5711         graph->boundary = 0;
5712         graph->size = graph->pos = 0;
5713         graph->commit = NULL;
5714         memset(graph->parents, 0, sizeof(*graph->parents));
5717 static void
5718 done_rev_graph(struct rev_graph *graph)
5720         if (graph_parent_is_merge(graph) &&
5721             graph->pos < graph->size - 1 &&
5722             graph->next->size == graph->size + graph->parents->size - 1) {
5723                 size_t i = graph->pos + graph->parents->size - 1;
5725                 graph->commit->graph_size = i * 2;
5726                 while (i < graph->next->size - 1) {
5727                         append_to_rev_graph(graph, ' ');
5728                         append_to_rev_graph(graph, '\\');
5729                         i++;
5730                 }
5731         }
5733         clear_rev_graph(graph);
5736 static void
5737 push_rev_graph(struct rev_graph *graph, const char *parent)
5739         int i;
5741         /* "Collapse" duplicate parents lines.
5742          *
5743          * FIXME: This needs to also update update the drawn graph but
5744          * for now it just serves as a method for pruning graph lines. */
5745         for (i = 0; i < graph->size; i++)
5746                 if (!strncmp(graph->rev[i], parent, SIZEOF_REV))
5747                         return;
5749         if (graph->size < SIZEOF_REVITEMS) {
5750                 string_copy_rev(graph->rev[graph->size++], parent);
5751         }
5754 static chtype
5755 get_rev_graph_symbol(struct rev_graph *graph)
5757         chtype symbol;
5759         if (graph->boundary)
5760                 symbol = REVGRAPH_BOUND;
5761         else if (graph->parents->size == 0)
5762                 symbol = REVGRAPH_INIT;
5763         else if (graph_parent_is_merge(graph))
5764                 symbol = REVGRAPH_MERGE;
5765         else if (graph->pos >= graph->size)
5766                 symbol = REVGRAPH_BRANCH;
5767         else
5768                 symbol = REVGRAPH_COMMIT;
5770         return symbol;
5773 static void
5774 draw_rev_graph(struct rev_graph *graph)
5776         struct rev_filler {
5777                 chtype separator, line;
5778         };
5779         enum { DEFAULT, RSHARP, RDIAG, LDIAG };
5780         static struct rev_filler fillers[] = {
5781                 { ' ',  '|' },
5782                 { '`',  '.' },
5783                 { '\'', ' ' },
5784                 { '/',  ' ' },
5785         };
5786         chtype symbol = get_rev_graph_symbol(graph);
5787         struct rev_filler *filler;
5788         size_t i;
5790         fillers[DEFAULT].line = opt_line_graphics ? ACS_VLINE : '|';
5791         filler = &fillers[DEFAULT];
5793         for (i = 0; i < graph->pos; i++) {
5794                 append_to_rev_graph(graph, filler->line);
5795                 if (graph_parent_is_merge(graph->prev) &&
5796                     graph->prev->pos == i)
5797                         filler = &fillers[RSHARP];
5799                 append_to_rev_graph(graph, filler->separator);
5800         }
5802         /* Place the symbol for this revision. */
5803         append_to_rev_graph(graph, symbol);
5805         if (graph->prev->size > graph->size)
5806                 filler = &fillers[RDIAG];
5807         else
5808                 filler = &fillers[DEFAULT];
5810         i++;
5812         for (; i < graph->size; i++) {
5813                 append_to_rev_graph(graph, filler->separator);
5814                 append_to_rev_graph(graph, filler->line);
5815                 if (graph_parent_is_merge(graph->prev) &&
5816                     i < graph->prev->pos + graph->parents->size)
5817                         filler = &fillers[RSHARP];
5818                 if (graph->prev->size > graph->size)
5819                         filler = &fillers[LDIAG];
5820         }
5822         if (graph->prev->size > graph->size) {
5823                 append_to_rev_graph(graph, filler->separator);
5824                 if (filler->line != ' ')
5825                         append_to_rev_graph(graph, filler->line);
5826         }
5829 /* Prepare the next rev graph */
5830 static void
5831 prepare_rev_graph(struct rev_graph *graph)
5833         size_t i;
5835         /* First, traverse all lines of revisions up to the active one. */
5836         for (graph->pos = 0; graph->pos < graph->size; graph->pos++) {
5837                 if (!strcmp(graph->rev[graph->pos], graph->commit->id))
5838                         break;
5840                 push_rev_graph(graph->next, graph->rev[graph->pos]);
5841         }
5843         /* Interleave the new revision parent(s). */
5844         for (i = 0; !graph->boundary && i < graph->parents->size; i++)
5845                 push_rev_graph(graph->next, graph->parents->rev[i]);
5847         /* Lastly, put any remaining revisions. */
5848         for (i = graph->pos + 1; i < graph->size; i++)
5849                 push_rev_graph(graph->next, graph->rev[i]);
5852 static void
5853 update_rev_graph(struct view *view, struct rev_graph *graph)
5855         /* If this is the finalizing update ... */
5856         if (graph->commit)
5857                 prepare_rev_graph(graph);
5859         /* Graph visualization needs a one rev look-ahead,
5860          * so the first update doesn't visualize anything. */
5861         if (!graph->prev->commit)
5862                 return;
5864         if (view->lines > 2)
5865                 view->line[view->lines - 3].dirty = 1;
5866         if (view->lines > 1)
5867                 view->line[view->lines - 2].dirty = 1;
5868         draw_rev_graph(graph->prev);
5869         done_rev_graph(graph->prev->prev);
5873 /*
5874  * Main view backend
5875  */
5877 static const char *main_argv[SIZEOF_ARG] = {
5878         "git", "log", "--no-color", "--pretty=raw", "--parents",
5879                 "--topo-order", "%(diffargs)", "%(revargs)",
5880                 "--", "%(fileargs)", NULL
5881 };
5883 static bool
5884 main_draw(struct view *view, struct line *line, unsigned int lineno)
5886         struct commit *commit = line->data;
5888         if (!commit->author)
5889                 return FALSE;
5891         if (opt_date && draw_date(view, &commit->time))
5892                 return TRUE;
5894         if (opt_author && draw_author(view, commit->author))
5895                 return TRUE;
5897         if (opt_rev_graph && commit->graph_size &&
5898             draw_graphic(view, LINE_MAIN_REVGRAPH, commit->graph, commit->graph_size))
5899                 return TRUE;
5901         if (opt_show_refs && commit->refs) {
5902                 size_t i;
5904                 for (i = 0; i < commit->refs->size; i++) {
5905                         struct ref *ref = commit->refs->refs[i];
5906                         enum line_type type;
5908                         if (ref->head)
5909                                 type = LINE_MAIN_HEAD;
5910                         else if (ref->ltag)
5911                                 type = LINE_MAIN_LOCAL_TAG;
5912                         else if (ref->tag)
5913                                 type = LINE_MAIN_TAG;
5914                         else if (ref->tracked)
5915                                 type = LINE_MAIN_TRACKED;
5916                         else if (ref->remote)
5917                                 type = LINE_MAIN_REMOTE;
5918                         else
5919                                 type = LINE_MAIN_REF;
5921                         if (draw_text(view, type, "[") ||
5922                             draw_text(view, type, ref->name) ||
5923                             draw_text(view, type, "]"))
5924                                 return TRUE;
5926                         if (draw_text(view, LINE_DEFAULT, " "))
5927                                 return TRUE;
5928                 }
5929         }
5931         draw_text(view, LINE_DEFAULT, commit->title);
5932         return TRUE;
5935 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5936 static bool
5937 main_read(struct view *view, char *line)
5939         static struct rev_graph *graph = graph_stacks;
5940         enum line_type type;
5941         struct commit *commit;
5943         if (!line) {
5944                 int i;
5946                 if (!view->lines && !view->prev)
5947                         die("No revisions match the given arguments.");
5948                 if (view->lines > 0) {
5949                         commit = view->line[view->lines - 1].data;
5950                         view->line[view->lines - 1].dirty = 1;
5951                         if (!commit->author) {
5952                                 view->lines--;
5953                                 free(commit);
5954                                 graph->commit = NULL;
5955                         }
5956                 }
5957                 update_rev_graph(view, graph);
5959                 for (i = 0; i < ARRAY_SIZE(graph_stacks); i++)
5960                         clear_rev_graph(&graph_stacks[i]);
5961                 return TRUE;
5962         }
5964         type = get_line_type(line);
5965         if (type == LINE_COMMIT) {
5966                 commit = calloc(1, sizeof(struct commit));
5967                 if (!commit)
5968                         return FALSE;
5970                 line += STRING_SIZE("commit ");
5971                 if (*line == '-') {
5972                         graph->boundary = 1;
5973                         line++;
5974                 }
5976                 string_copy_rev(commit->id, line);
5977                 commit->refs = get_ref_list(commit->id);
5978                 graph->commit = commit;
5979                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5981                 while ((line = strchr(line, ' '))) {
5982                         line++;
5983                         push_rev_graph(graph->parents, line);
5984                         commit->has_parents = TRUE;
5985                 }
5986                 return TRUE;
5987         }
5989         if (!view->lines)
5990                 return TRUE;
5991         commit = view->line[view->lines - 1].data;
5993         switch (type) {
5994         case LINE_PARENT:
5995                 if (commit->has_parents)
5996                         break;
5997                 push_rev_graph(graph->parents, line + STRING_SIZE("parent "));
5998                 break;
6000         case LINE_AUTHOR:
6001                 parse_author_line(line + STRING_SIZE("author "),
6002                                   &commit->author, &commit->time);
6003                 update_rev_graph(view, graph);
6004                 graph = graph->next;
6005                 break;
6007         default:
6008                 /* Fill in the commit title if it has not already been set. */
6009                 if (commit->title[0])
6010                         break;
6012                 /* Require titles to start with a non-space character at the
6013                  * offset used by git log. */
6014                 if (strncmp(line, "    ", 4))
6015                         break;
6016                 line += 4;
6017                 /* Well, if the title starts with a whitespace character,
6018                  * try to be forgiving.  Otherwise we end up with no title. */
6019                 while (isspace(*line))
6020                         line++;
6021                 if (*line == '\0')
6022                         break;
6023                 /* FIXME: More graceful handling of titles; append "..." to
6024                  * shortened titles, etc. */
6026                 string_expand(commit->title, sizeof(commit->title), line, 1);
6027                 view->line[view->lines - 1].dirty = 1;
6028         }
6030         return TRUE;
6033 static enum request
6034 main_request(struct view *view, enum request request, struct line *line)
6036         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6038         switch (request) {
6039         case REQ_ENTER:
6040                 if (view_is_displayed(view) && display[0] != view)
6041                         maximize_view(view);
6042                 open_view(view, REQ_VIEW_DIFF, flags);
6043                 break;
6044         case REQ_REFRESH:
6045                 load_refs();
6046                 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
6047                 break;
6048         default:
6049                 return request;
6050         }
6052         return REQ_NONE;
6055 static bool
6056 grep_refs(struct ref_list *list, regex_t *regex)
6058         regmatch_t pmatch;
6059         size_t i;
6061         if (!opt_show_refs || !list)
6062                 return FALSE;
6064         for (i = 0; i < list->size; i++) {
6065                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6066                         return TRUE;
6067         }
6069         return FALSE;
6072 static bool
6073 main_grep(struct view *view, struct line *line)
6075         struct commit *commit = line->data;
6076         const char *text[] = {
6077                 commit->title,
6078                 opt_author ? commit->author : "",
6079                 mkdate(&commit->time, opt_date),
6080                 NULL
6081         };
6083         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6086 static void
6087 main_select(struct view *view, struct line *line)
6089         struct commit *commit = line->data;
6091         string_copy_rev(view->ref, commit->id);
6092         string_copy_rev(ref_commit, view->ref);
6095 static struct view_ops main_ops = {
6096         "commit",
6097         main_argv,
6098         NULL,
6099         main_read,
6100         main_draw,
6101         main_request,
6102         main_grep,
6103         main_select,
6104 };
6107 /*
6108  * Status management
6109  */
6111 /* Whether or not the curses interface has been initialized. */
6112 static bool cursed = FALSE;
6114 /* Terminal hacks and workarounds. */
6115 static bool use_scroll_redrawwin;
6116 static bool use_scroll_status_wclear;
6118 /* The status window is used for polling keystrokes. */
6119 static WINDOW *status_win;
6121 /* Reading from the prompt? */
6122 static bool input_mode = FALSE;
6124 static bool status_empty = FALSE;
6126 /* Update status and title window. */
6127 static void
6128 report(const char *msg, ...)
6130         struct view *view = display[current_view];
6132         if (input_mode)
6133                 return;
6135         if (!view) {
6136                 char buf[SIZEOF_STR];
6137                 va_list args;
6139                 va_start(args, msg);
6140                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6141                         buf[sizeof(buf) - 1] = 0;
6142                         buf[sizeof(buf) - 2] = '.';
6143                         buf[sizeof(buf) - 3] = '.';
6144                         buf[sizeof(buf) - 4] = '.';
6145                 }
6146                 va_end(args);
6147                 die("%s", buf);
6148         }
6150         if (!status_empty || *msg) {
6151                 va_list args;
6153                 va_start(args, msg);
6155                 wmove(status_win, 0, 0);
6156                 if (view->has_scrolled && use_scroll_status_wclear)
6157                         wclear(status_win);
6158                 if (*msg) {
6159                         vwprintw(status_win, msg, args);
6160                         status_empty = FALSE;
6161                 } else {
6162                         status_empty = TRUE;
6163                 }
6164                 wclrtoeol(status_win);
6165                 wnoutrefresh(status_win);
6167                 va_end(args);
6168         }
6170         update_view_title(view);
6173 static void
6174 init_display(void)
6176         const char *term;
6177         int x, y;
6179         /* Initialize the curses library */
6180         if (isatty(STDIN_FILENO)) {
6181                 cursed = !!initscr();
6182                 opt_tty = stdin;
6183         } else {
6184                 /* Leave stdin and stdout alone when acting as a pager. */
6185                 opt_tty = fopen("/dev/tty", "r+");
6186                 if (!opt_tty)
6187                         die("Failed to open /dev/tty");
6188                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6189         }
6191         if (!cursed)
6192                 die("Failed to initialize curses");
6194         nonl();         /* Disable conversion and detect newlines from input. */
6195         cbreak();       /* Take input chars one at a time, no wait for \n */
6196         noecho();       /* Don't echo input */
6197         leaveok(stdscr, FALSE);
6199         if (has_colors())
6200                 init_colors();
6202         getmaxyx(stdscr, y, x);
6203         status_win = newwin(1, x, y - 1, 0);
6204         if (!status_win)
6205                 die("Failed to create status window");
6207         /* Enable keyboard mapping */
6208         keypad(status_win, TRUE);
6209         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6211 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6212         set_tabsize(opt_tab_size);
6213 #else
6214         TABSIZE = opt_tab_size;
6215 #endif
6217         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6218         if (term && !strcmp(term, "gnome-terminal")) {
6219                 /* In the gnome-terminal-emulator, the message from
6220                  * scrolling up one line when impossible followed by
6221                  * scrolling down one line causes corruption of the
6222                  * status line. This is fixed by calling wclear. */
6223                 use_scroll_status_wclear = TRUE;
6224                 use_scroll_redrawwin = FALSE;
6226         } else if (term && !strcmp(term, "xrvt-xpm")) {
6227                 /* No problems with full optimizations in xrvt-(unicode)
6228                  * and aterm. */
6229                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6231         } else {
6232                 /* When scrolling in (u)xterm the last line in the
6233                  * scrolling direction will update slowly. */
6234                 use_scroll_redrawwin = TRUE;
6235                 use_scroll_status_wclear = FALSE;
6236         }
6239 static int
6240 get_input(int prompt_position)
6242         struct view *view;
6243         int i, key, cursor_y, cursor_x;
6245         if (prompt_position)
6246                 input_mode = TRUE;
6248         while (TRUE) {
6249                 bool loading = FALSE;
6251                 foreach_view (view, i) {
6252                         update_view(view);
6253                         if (view_is_displayed(view) && view->has_scrolled &&
6254                             use_scroll_redrawwin)
6255                                 redrawwin(view->win);
6256                         view->has_scrolled = FALSE;
6257                         if (view->pipe)
6258                                 loading = TRUE;
6259                 }
6261                 /* Update the cursor position. */
6262                 if (prompt_position) {
6263                         getbegyx(status_win, cursor_y, cursor_x);
6264                         cursor_x = prompt_position;
6265                 } else {
6266                         view = display[current_view];
6267                         getbegyx(view->win, cursor_y, cursor_x);
6268                         cursor_x = view->width - 1;
6269                         cursor_y += view->lineno - view->offset;
6270                 }
6271                 setsyx(cursor_y, cursor_x);
6273                 /* Refresh, accept single keystroke of input */
6274                 doupdate();
6275                 nodelay(status_win, loading);
6276                 key = wgetch(status_win);
6278                 /* wgetch() with nodelay() enabled returns ERR when
6279                  * there's no input. */
6280                 if (key == ERR) {
6282                 } else if (key == KEY_RESIZE) {
6283                         int height, width;
6285                         getmaxyx(stdscr, height, width);
6287                         wresize(status_win, 1, width);
6288                         mvwin(status_win, height - 1, 0);
6289                         wnoutrefresh(status_win);
6290                         resize_display();
6291                         redraw_display(TRUE);
6293                 } else {
6294                         input_mode = FALSE;
6295                         return key;
6296                 }
6297         }
6300 static char *
6301 prompt_input(const char *prompt, input_handler handler, void *data)
6303         enum input_status status = INPUT_OK;
6304         static char buf[SIZEOF_STR];
6305         size_t pos = 0;
6307         buf[pos] = 0;
6309         while (status == INPUT_OK || status == INPUT_SKIP) {
6310                 int key;
6312                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6313                 wclrtoeol(status_win);
6315                 key = get_input(pos + 1);
6316                 switch (key) {
6317                 case KEY_RETURN:
6318                 case KEY_ENTER:
6319                 case '\n':
6320                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6321                         break;
6323                 case KEY_BACKSPACE:
6324                         if (pos > 0)
6325                                 buf[--pos] = 0;
6326                         else
6327                                 status = INPUT_CANCEL;
6328                         break;
6330                 case KEY_ESC:
6331                         status = INPUT_CANCEL;
6332                         break;
6334                 default:
6335                         if (pos >= sizeof(buf)) {
6336                                 report("Input string too long");
6337                                 return NULL;
6338                         }
6340                         status = handler(data, buf, key);
6341                         if (status == INPUT_OK)
6342                                 buf[pos++] = (char) key;
6343                 }
6344         }
6346         /* Clear the status window */
6347         status_empty = FALSE;
6348         report("");
6350         if (status == INPUT_CANCEL)
6351                 return NULL;
6353         buf[pos++] = 0;
6355         return buf;
6358 static enum input_status
6359 prompt_yesno_handler(void *data, char *buf, int c)
6361         if (c == 'y' || c == 'Y')
6362                 return INPUT_STOP;
6363         if (c == 'n' || c == 'N')
6364                 return INPUT_CANCEL;
6365         return INPUT_SKIP;
6368 static bool
6369 prompt_yesno(const char *prompt)
6371         char prompt2[SIZEOF_STR];
6373         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6374                 return FALSE;
6376         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6379 static enum input_status
6380 read_prompt_handler(void *data, char *buf, int c)
6382         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6385 static char *
6386 read_prompt(const char *prompt)
6388         return prompt_input(prompt, read_prompt_handler, NULL);
6391 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6393         enum input_status status = INPUT_OK;
6394         int size = 0;
6396         while (items[size].text)
6397                 size++;
6399         while (status == INPUT_OK) {
6400                 const struct menu_item *item = &items[*selected];
6401                 int key;
6402                 int i;
6404                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6405                           prompt, *selected + 1, size);
6406                 if (item->hotkey)
6407                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6408                 wprintw(status_win, "%s", item->text);
6409                 wclrtoeol(status_win);
6411                 key = get_input(COLS - 1);
6412                 switch (key) {
6413                 case KEY_RETURN:
6414                 case KEY_ENTER:
6415                 case '\n':
6416                         status = INPUT_STOP;
6417                         break;
6419                 case KEY_LEFT:
6420                 case KEY_UP:
6421                         *selected = *selected - 1;
6422                         if (*selected < 0)
6423                                 *selected = size - 1;
6424                         break;
6426                 case KEY_RIGHT:
6427                 case KEY_DOWN:
6428                         *selected = (*selected + 1) % size;
6429                         break;
6431                 case KEY_ESC:
6432                         status = INPUT_CANCEL;
6433                         break;
6435                 default:
6436                         for (i = 0; items[i].text; i++)
6437                                 if (items[i].hotkey == key) {
6438                                         *selected = i;
6439                                         status = INPUT_STOP;
6440                                         break;
6441                                 }
6442                 }
6443         }
6445         /* Clear the status window */
6446         status_empty = FALSE;
6447         report("");
6449         return status != INPUT_CANCEL;
6452 /*
6453  * Repository properties
6454  */
6456 static struct ref **refs = NULL;
6457 static size_t refs_size = 0;
6458 static struct ref *refs_head = NULL;
6460 static struct ref_list **ref_lists = NULL;
6461 static size_t ref_lists_size = 0;
6463 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6464 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6465 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6467 static int
6468 compare_refs(const void *ref1_, const void *ref2_)
6470         const struct ref *ref1 = *(const struct ref **)ref1_;
6471         const struct ref *ref2 = *(const struct ref **)ref2_;
6473         if (ref1->tag != ref2->tag)
6474                 return ref2->tag - ref1->tag;
6475         if (ref1->ltag != ref2->ltag)
6476                 return ref2->ltag - ref2->ltag;
6477         if (ref1->head != ref2->head)
6478                 return ref2->head - ref1->head;
6479         if (ref1->tracked != ref2->tracked)
6480                 return ref2->tracked - ref1->tracked;
6481         if (ref1->remote != ref2->remote)
6482                 return ref2->remote - ref1->remote;
6483         return strcmp(ref1->name, ref2->name);
6486 static void
6487 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6489         size_t i;
6491         for (i = 0; i < refs_size; i++)
6492                 if (!visitor(data, refs[i]))
6493                         break;
6496 static struct ref *
6497 get_ref_head()
6499         return refs_head;
6502 static struct ref_list *
6503 get_ref_list(const char *id)
6505         struct ref_list *list;
6506         size_t i;
6508         for (i = 0; i < ref_lists_size; i++)
6509                 if (!strcmp(id, ref_lists[i]->id))
6510                         return ref_lists[i];
6512         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6513                 return NULL;
6514         list = calloc(1, sizeof(*list));
6515         if (!list)
6516                 return NULL;
6518         for (i = 0; i < refs_size; i++) {
6519                 if (!strcmp(id, refs[i]->id) &&
6520                     realloc_refs_list(&list->refs, list->size, 1))
6521                         list->refs[list->size++] = refs[i];
6522         }
6524         if (!list->refs) {
6525                 free(list);
6526                 return NULL;
6527         }
6529         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6530         ref_lists[ref_lists_size++] = list;
6531         return list;
6534 static int
6535 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6537         struct ref *ref = NULL;
6538         bool tag = FALSE;
6539         bool ltag = FALSE;
6540         bool remote = FALSE;
6541         bool tracked = FALSE;
6542         bool head = FALSE;
6543         int from = 0, to = refs_size - 1;
6545         if (!prefixcmp(name, "refs/tags/")) {
6546                 if (!suffixcmp(name, namelen, "^{}")) {
6547                         namelen -= 3;
6548                         name[namelen] = 0;
6549                 } else {
6550                         ltag = TRUE;
6551                 }
6553                 tag = TRUE;
6554                 namelen -= STRING_SIZE("refs/tags/");
6555                 name    += STRING_SIZE("refs/tags/");
6557         } else if (!prefixcmp(name, "refs/remotes/")) {
6558                 remote = TRUE;
6559                 namelen -= STRING_SIZE("refs/remotes/");
6560                 name    += STRING_SIZE("refs/remotes/");
6561                 tracked  = !strcmp(opt_remote, name);
6563         } else if (!prefixcmp(name, "refs/heads/")) {
6564                 namelen -= STRING_SIZE("refs/heads/");
6565                 name    += STRING_SIZE("refs/heads/");
6566                 if (!strncmp(opt_head, name, namelen))
6567                         return OK;
6569         } else if (!strcmp(name, "HEAD")) {
6570                 head     = TRUE;
6571                 if (*opt_head) {
6572                         namelen  = strlen(opt_head);
6573                         name     = opt_head;
6574                 }
6575         }
6577         /* If we are reloading or it's an annotated tag, replace the
6578          * previous SHA1 with the resolved commit id; relies on the fact
6579          * git-ls-remote lists the commit id of an annotated tag right
6580          * before the commit id it points to. */
6581         while (from <= to) {
6582                 size_t pos = (to + from) / 2;
6583                 int cmp = strcmp(name, refs[pos]->name);
6585                 if (!cmp) {
6586                         ref = refs[pos];
6587                         break;
6588                 }
6590                 if (cmp < 0)
6591                         to = pos - 1;
6592                 else
6593                         from = pos + 1;
6594         }
6596         if (!ref) {
6597                 if (!realloc_refs(&refs, refs_size, 1))
6598                         return ERR;
6599                 ref = calloc(1, sizeof(*ref) + namelen);
6600                 if (!ref)
6601                         return ERR;
6602                 memmove(refs + from + 1, refs + from,
6603                         (refs_size - from) * sizeof(*refs));
6604                 refs[from] = ref;
6605                 strncpy(ref->name, name, namelen);
6606                 refs_size++;
6607         }
6609         ref->head = head;
6610         ref->tag = tag;
6611         ref->ltag = ltag;
6612         ref->remote = remote;
6613         ref->tracked = tracked;
6614         string_copy_rev(ref->id, id);
6616         if (head)
6617                 refs_head = ref;
6618         return OK;
6621 static int
6622 load_refs(void)
6624         const char *head_argv[] = {
6625                 "git", "symbolic-ref", "HEAD", NULL
6626         };
6627         static const char *ls_remote_argv[SIZEOF_ARG] = {
6628                 "git", "ls-remote", opt_git_dir, NULL
6629         };
6630         static bool init = FALSE;
6631         size_t i;
6633         if (!init) {
6634                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6635                         die("TIG_LS_REMOTE contains too many arguments");
6636                 init = TRUE;
6637         }
6639         if (!*opt_git_dir)
6640                 return OK;
6642         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6643             !prefixcmp(opt_head, "refs/heads/")) {
6644                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6646                 memmove(opt_head, offset, strlen(offset) + 1);
6647         }
6649         refs_head = NULL;
6650         for (i = 0; i < refs_size; i++)
6651                 refs[i]->id[0] = 0;
6653         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6654                 return ERR;
6656         /* Update the ref lists to reflect changes. */
6657         for (i = 0; i < ref_lists_size; i++) {
6658                 struct ref_list *list = ref_lists[i];
6659                 size_t old, new;
6661                 for (old = new = 0; old < list->size; old++)
6662                         if (!strcmp(list->id, list->refs[old]->id))
6663                                 list->refs[new++] = list->refs[old];
6664                 list->size = new;
6665         }
6667         return OK;
6670 static void
6671 set_remote_branch(const char *name, const char *value, size_t valuelen)
6673         if (!strcmp(name, ".remote")) {
6674                 string_ncopy(opt_remote, value, valuelen);
6676         } else if (*opt_remote && !strcmp(name, ".merge")) {
6677                 size_t from = strlen(opt_remote);
6679                 if (!prefixcmp(value, "refs/heads/"))
6680                         value += STRING_SIZE("refs/heads/");
6682                 if (!string_format_from(opt_remote, &from, "/%s", value))
6683                         opt_remote[0] = 0;
6684         }
6687 static void
6688 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6690         const char *argv[SIZEOF_ARG] = { name, "=" };
6691         int argc = 1 + (cmd == option_set_command);
6692         enum option_code error;
6694         if (!argv_from_string(argv, &argc, value))
6695                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6696         else
6697                 error = cmd(argc, argv);
6699         if (error != OPT_OK)
6700                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6703 static bool
6704 set_environment_variable(const char *name, const char *value)
6706         size_t len = strlen(name) + 1 + strlen(value) + 1;
6707         char *env = malloc(len);
6709         if (env &&
6710             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6711             putenv(env) == 0)
6712                 return TRUE;
6713         free(env);
6714         return FALSE;
6717 static void
6718 set_work_tree(const char *value)
6720         char cwd[SIZEOF_STR];
6722         if (!getcwd(cwd, sizeof(cwd)))
6723                 die("Failed to get cwd path: %s", strerror(errno));
6724         if (chdir(opt_git_dir) < 0)
6725                 die("Failed to chdir(%s): %s", strerror(errno));
6726         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6727                 die("Failed to get git path: %s", strerror(errno));
6728         if (chdir(cwd) < 0)
6729                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6730         if (chdir(value) < 0)
6731                 die("Failed to chdir(%s): %s", value, strerror(errno));
6732         if (!getcwd(cwd, sizeof(cwd)))
6733                 die("Failed to get cwd path: %s", strerror(errno));
6734         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6735                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6736         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6737                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6738         opt_is_inside_work_tree = TRUE;
6741 static int
6742 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6744         if (!strcmp(name, "i18n.commitencoding"))
6745                 string_ncopy(opt_encoding, value, valuelen);
6747         else if (!strcmp(name, "core.editor"))
6748                 string_ncopy(opt_editor, value, valuelen);
6750         else if (!strcmp(name, "core.worktree"))
6751                 set_work_tree(value);
6753         else if (!prefixcmp(name, "tig.color."))
6754                 set_repo_config_option(name + 10, value, option_color_command);
6756         else if (!prefixcmp(name, "tig.bind."))
6757                 set_repo_config_option(name + 9, value, option_bind_command);
6759         else if (!prefixcmp(name, "tig."))
6760                 set_repo_config_option(name + 4, value, option_set_command);
6762         else if (*opt_head && !prefixcmp(name, "branch.") &&
6763                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6764                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6766         return OK;
6769 static int
6770 load_git_config(void)
6772         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6774         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6777 static int
6778 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6780         if (!opt_git_dir[0]) {
6781                 string_ncopy(opt_git_dir, name, namelen);
6783         } else if (opt_is_inside_work_tree == -1) {
6784                 /* This can be 3 different values depending on the
6785                  * version of git being used. If git-rev-parse does not
6786                  * understand --is-inside-work-tree it will simply echo
6787                  * the option else either "true" or "false" is printed.
6788                  * Default to true for the unknown case. */
6789                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6791         } else if (*name == '.') {
6792                 string_ncopy(opt_cdup, name, namelen);
6794         } else {
6795                 string_ncopy(opt_prefix, name, namelen);
6796         }
6798         return OK;
6801 static int
6802 load_repo_info(void)
6804         const char *rev_parse_argv[] = {
6805                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6806                         "--show-cdup", "--show-prefix", NULL
6807         };
6809         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6813 /*
6814  * Main
6815  */
6817 static const char usage[] =
6818 "tig " TIG_VERSION " (" __DATE__ ")\n"
6819 "\n"
6820 "Usage: tig        [options] [revs] [--] [paths]\n"
6821 "   or: tig show   [options] [revs] [--] [paths]\n"
6822 "   or: tig blame  [rev] path\n"
6823 "   or: tig status\n"
6824 "   or: tig <      [git command output]\n"
6825 "\n"
6826 "Options:\n"
6827 "  -v, --version   Show version and exit\n"
6828 "  -h, --help      Show help message and exit";
6830 static void __NORETURN
6831 quit(int sig)
6833         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6834         if (cursed)
6835                 endwin();
6836         exit(0);
6839 static void __NORETURN
6840 die(const char *err, ...)
6842         va_list args;
6844         endwin();
6846         va_start(args, err);
6847         fputs("tig: ", stderr);
6848         vfprintf(stderr, err, args);
6849         fputs("\n", stderr);
6850         va_end(args);
6852         exit(1);
6855 static void
6856 warn(const char *msg, ...)
6858         va_list args;
6860         va_start(args, msg);
6861         fputs("tig warning: ", stderr);
6862         vfprintf(stderr, msg, args);
6863         fputs("\n", stderr);
6864         va_end(args);
6867 static int
6868 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6870         const char ***filter_args = data;
6872         return argv_append(filter_args, name) ? OK : ERR;
6875 static void
6876 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6878         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6879         const char **all_argv = NULL;
6881         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6882             !argv_append_array(&all_argv, argv) ||
6883             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6884                 die("Failed to split arguments");
6885         argv_free(all_argv);
6886         free(all_argv);
6889 static void
6890 filter_options(const char *argv[])
6892         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6893         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6894         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6897 static enum request
6898 parse_options(int argc, const char *argv[])
6900         enum request request = REQ_VIEW_MAIN;
6901         const char *subcommand;
6902         bool seen_dashdash = FALSE;
6903         const char **filter_argv = NULL;
6904         int i;
6906         if (!isatty(STDIN_FILENO))
6907                 return REQ_VIEW_PAGER;
6909         if (argc <= 1)
6910                 return REQ_VIEW_MAIN;
6912         subcommand = argv[1];
6913         if (!strcmp(subcommand, "status")) {
6914                 if (argc > 2)
6915                         warn("ignoring arguments after `%s'", subcommand);
6916                 return REQ_VIEW_STATUS;
6918         } else if (!strcmp(subcommand, "blame")) {
6919                 if (argc <= 2 || argc > 4)
6920                         die("invalid number of options to blame\n\n%s", usage);
6922                 i = 2;
6923                 if (argc == 4) {
6924                         string_ncopy(opt_ref, argv[i], strlen(argv[i]));
6925                         i++;
6926                 }
6928                 string_ncopy(opt_file, argv[i], strlen(argv[i]));
6929                 return REQ_VIEW_BLAME;
6931         } else if (!strcmp(subcommand, "show")) {
6932                 request = REQ_VIEW_DIFF;
6934         } else {
6935                 subcommand = NULL;
6936         }
6938         for (i = 1 + !!subcommand; i < argc; i++) {
6939                 const char *opt = argv[i];
6941                 if (seen_dashdash) {
6942                         argv_append(&opt_file_argv, opt);
6943                         continue;
6945                 } else if (!strcmp(opt, "--")) {
6946                         seen_dashdash = TRUE;
6947                         continue;
6949                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6950                         printf("tig version %s\n", TIG_VERSION);
6951                         quit(0);
6953                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6954                         printf("%s\n", usage);
6955                         quit(0);
6957                 } else if (!strcmp(opt, "--all")) {
6958                         argv_append(&opt_rev_argv, opt);
6959                         continue;
6960                 }
6962                 if (!argv_append(&filter_argv, opt))
6963                         die("command too long");
6964         }
6966         if (filter_argv)
6967                 filter_options(filter_argv);
6969         return request;
6972 int
6973 main(int argc, const char *argv[])
6975         const char *codeset = "UTF-8";
6976         enum request request = parse_options(argc, argv);
6977         struct view *view;
6978         size_t i;
6980         signal(SIGINT, quit);
6981         signal(SIGPIPE, SIG_IGN);
6983         if (setlocale(LC_ALL, "")) {
6984                 codeset = nl_langinfo(CODESET);
6985         }
6987         if (load_repo_info() == ERR)
6988                 die("Failed to load repo info.");
6990         if (load_options() == ERR)
6991                 die("Failed to load user config.");
6993         if (load_git_config() == ERR)
6994                 die("Failed to load repo config.");
6996         /* Require a git repository unless when running in pager mode. */
6997         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6998                 die("Not a git repository");
7000         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
7001                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
7002                 if (opt_iconv_in == ICONV_NONE)
7003                         die("Failed to initialize character set conversion");
7004         }
7006         if (codeset && strcmp(codeset, "UTF-8")) {
7007                 opt_iconv_out = iconv_open(codeset, "UTF-8");
7008                 if (opt_iconv_out == ICONV_NONE)
7009                         die("Failed to initialize character set conversion");
7010         }
7012         if (load_refs() == ERR)
7013                 die("Failed to load refs.");
7015         foreach_view (view, i) {
7016                 if (getenv(view->cmd_env))
7017                         warn("Use of the %s environment variable is deprecated,"
7018                              " use options or TIG_DIFF_ARGS instead",
7019                              view->cmd_env);
7020                 if (!argv_from_env(view->ops->argv, view->cmd_env))
7021                         die("Too many arguments in the `%s` environment variable",
7022                             view->cmd_env);
7023         }
7025         init_display();
7027         while (view_driver(display[current_view], request)) {
7028                 int key = get_input(0);
7030                 view = display[current_view];
7031                 request = get_keybinding(view->keymap, key);
7033                 /* Some low-level request handling. This keeps access to
7034                  * status_win restricted. */
7035                 switch (request) {
7036                 case REQ_NONE:
7037                         report("Unknown key, press %s for help",
7038                                get_key(view->keymap, REQ_VIEW_HELP));
7039                         break;
7040                 case REQ_PROMPT:
7041                 {
7042                         char *cmd = read_prompt(":");
7044                         if (cmd && isdigit(*cmd)) {
7045                                 int lineno = view->lineno + 1;
7047                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
7048                                         select_view_line(view, lineno - 1);
7049                                         report("");
7050                                 } else {
7051                                         report("Unable to parse '%s' as a line number", cmd);
7052                                 }
7054                         } else if (cmd) {
7055                                 struct view *next = VIEW(REQ_VIEW_PAGER);
7056                                 const char *argv[SIZEOF_ARG] = { "git" };
7057                                 int argc = 1;
7059                                 /* When running random commands, initially show the
7060                                  * command in the title. However, it maybe later be
7061                                  * overwritten if a commit line is selected. */
7062                                 string_ncopy(next->ref, cmd, strlen(cmd));
7064                                 if (!argv_from_string(argv, &argc, cmd)) {
7065                                         report("Too many arguments");
7066                                 } else if (!prepare_update(next, argv, NULL)) {
7067                                         report("Failed to format command");
7068                                 } else {
7069                                         open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7070                                 }
7071                         }
7073                         request = REQ_NONE;
7074                         break;
7075                 }
7076                 case REQ_SEARCH:
7077                 case REQ_SEARCH_BACK:
7078                 {
7079                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
7080                         char *search = read_prompt(prompt);
7082                         if (search)
7083                                 string_ncopy(opt_search, search, strlen(search));
7084                         else if (*opt_search)
7085                                 request = request == REQ_SEARCH ?
7086                                         REQ_FIND_NEXT :
7087                                         REQ_FIND_PREV;
7088                         else
7089                                 request = REQ_NONE;
7090                         break;
7091                 }
7092                 default:
7093                         break;
7094                 }
7095         }
7097         quit(0);
7099         return 0;