Code

open_view: Use maximize_view to prepare non-split displays
[tig.git] / tig.c
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU General Public License as
5  * published by the Free Software Foundation; either version 2 of
6  * the License, or (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24         char id[SIZEOF_REV];    /* Commit SHA1 ID */
25         unsigned int head:1;    /* Is it the current HEAD? */
26         unsigned int tag:1;     /* Is it a tag? */
27         unsigned int ltag:1;    /* If so, is the tag local? */
28         unsigned int remote:1;  /* Is it a remote ref? */
29         unsigned int tracked:1; /* Is it the remote for the current HEAD? */
30         char name[1];           /* Ref name; tag or head names are shortened. */
31 };
33 struct ref_list {
34         char id[SIZEOF_REV];    /* Commit SHA1 ID */
35         size_t size;            /* Number of refs. */
36         struct ref **refs;      /* References for this ID. */
37 };
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45         INPUT_OK,
46         INPUT_SKIP,
47         INPUT_STOP,
48         INPUT_CANCEL
49 };
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57         int hotkey;
58         const char *text;
59         void *data;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 enum graphic {
65         GRAPHIC_ASCII = 0,
66         GRAPHIC_DEFAULT,
67         GRAPHIC_UTF8
68 };
70 static const struct enum_map graphic_map[] = {
71 #define GRAPHIC_(name) ENUM_MAP(#name, GRAPHIC_##name)
72         GRAPHIC_(ASCII),
73         GRAPHIC_(DEFAULT),
74         GRAPHIC_(UTF8)
75 #undef  GRAPHIC_
76 };
78 #define DATE_INFO \
79         DATE_(NO), \
80         DATE_(DEFAULT), \
81         DATE_(LOCAL), \
82         DATE_(RELATIVE), \
83         DATE_(SHORT)
85 enum date {
86 #define DATE_(name) DATE_##name
87         DATE_INFO
88 #undef  DATE_
89 };
91 static const struct enum_map date_map[] = {
92 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
93         DATE_INFO
94 #undef  DATE_
95 };
97 struct time {
98         time_t sec;
99         int tz;
100 };
102 static inline int timecmp(const struct time *t1, const struct time *t2)
104         return t1->sec - t2->sec;
107 static const char *
108 mkdate(const struct time *time, enum date date)
110         static char buf[DATE_COLS + 1];
111         static const struct enum_map reldate[] = {
112                 { "second", 1,                  60 * 2 },
113                 { "minute", 60,                 60 * 60 * 2 },
114                 { "hour",   60 * 60,            60 * 60 * 24 * 2 },
115                 { "day",    60 * 60 * 24,       60 * 60 * 24 * 7 * 2 },
116                 { "week",   60 * 60 * 24 * 7,   60 * 60 * 24 * 7 * 5 },
117                 { "month",  60 * 60 * 24 * 30,  60 * 60 * 24 * 30 * 12 },
118         };
119         struct tm tm;
121         if (!date || !time || !time->sec)
122                 return "";
124         if (date == DATE_RELATIVE) {
125                 struct timeval now;
126                 time_t date = time->sec + time->tz;
127                 time_t seconds;
128                 int i;
130                 gettimeofday(&now, NULL);
131                 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
132                 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
133                         if (seconds >= reldate[i].value)
134                                 continue;
136                         seconds /= reldate[i].namelen;
137                         if (!string_format(buf, "%ld %s%s %s",
138                                            seconds, reldate[i].name,
139                                            seconds > 1 ? "s" : "",
140                                            now.tv_sec >= date ? "ago" : "ahead"))
141                                 break;
142                         return buf;
143                 }
144         }
146         if (date == DATE_LOCAL) {
147                 time_t date = time->sec + time->tz;
148                 localtime_r(&date, &tm);
149         }
150         else {
151                 gmtime_r(&time->sec, &tm);
152         }
153         return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
157 #define AUTHOR_VALUES \
158         AUTHOR_(NO), \
159         AUTHOR_(FULL), \
160         AUTHOR_(ABBREVIATED)
162 enum author {
163 #define AUTHOR_(name) AUTHOR_##name
164         AUTHOR_VALUES,
165 #undef  AUTHOR_
166         AUTHOR_DEFAULT = AUTHOR_FULL
167 };
169 static const struct enum_map author_map[] = {
170 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
171         AUTHOR_VALUES
172 #undef  AUTHOR_
173 };
175 static const char *
176 get_author_initials(const char *author)
178         static char initials[AUTHOR_COLS * 6 + 1];
179         size_t pos = 0;
180         const char *end = strchr(author, '\0');
182 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
184         memset(initials, 0, sizeof(initials));
185         while (author < end) {
186                 unsigned char bytes;
187                 size_t i;
189                 while (is_initial_sep(*author))
190                         author++;
192                 bytes = utf8_char_length(author, end);
193                 if (bytes < sizeof(initials) - 1 - pos) {
194                         while (bytes--) {
195                                 initials[pos++] = *author++;
196                         }
197                 }
199                 for (i = pos; author < end && !is_initial_sep(*author); author++) {
200                         if (i < sizeof(initials) - 1)
201                                 initials[i++] = *author;
202                 }
204                 initials[i++] = 0;
205         }
207         return initials;
211 /*
212  * User requests
213  */
215 #define REQ_INFO \
216         /* XXX: Keep the view request first and in sync with views[]. */ \
217         REQ_GROUP("View switching") \
218         REQ_(VIEW_MAIN,         "Show main view"), \
219         REQ_(VIEW_DIFF,         "Show diff view"), \
220         REQ_(VIEW_LOG,          "Show log view"), \
221         REQ_(VIEW_TREE,         "Show tree view"), \
222         REQ_(VIEW_BLOB,         "Show blob view"), \
223         REQ_(VIEW_BLAME,        "Show blame view"), \
224         REQ_(VIEW_BRANCH,       "Show branch view"), \
225         REQ_(VIEW_HELP,         "Show help page"), \
226         REQ_(VIEW_PAGER,        "Show pager view"), \
227         REQ_(VIEW_STATUS,       "Show status view"), \
228         REQ_(VIEW_STAGE,        "Show stage view"), \
229         \
230         REQ_GROUP("View manipulation") \
231         REQ_(ENTER,             "Enter current line and scroll"), \
232         REQ_(NEXT,              "Move to next"), \
233         REQ_(PREVIOUS,          "Move to previous"), \
234         REQ_(PARENT,            "Move to parent"), \
235         REQ_(VIEW_NEXT,         "Move focus to next view"), \
236         REQ_(REFRESH,           "Reload and refresh"), \
237         REQ_(MAXIMIZE,          "Maximize the current view"), \
238         REQ_(VIEW_CLOSE,        "Close the current view"), \
239         REQ_(QUIT,              "Close all views and quit"), \
240         \
241         REQ_GROUP("View specific requests") \
242         REQ_(STATUS_UPDATE,     "Update file status"), \
243         REQ_(STATUS_REVERT,     "Revert file changes"), \
244         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
245         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
246         \
247         REQ_GROUP("Cursor navigation") \
248         REQ_(MOVE_UP,           "Move cursor one line up"), \
249         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
250         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
251         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
252         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
253         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
254         \
255         REQ_GROUP("Scrolling") \
256         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
257         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
258         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
259         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
260         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
261         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
262         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
263         \
264         REQ_GROUP("Searching") \
265         REQ_(SEARCH,            "Search the view"), \
266         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
267         REQ_(FIND_NEXT,         "Find next search match"), \
268         REQ_(FIND_PREV,         "Find previous search match"), \
269         \
270         REQ_GROUP("Option manipulation") \
271         REQ_(OPTIONS,           "Open option menu"), \
272         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
273         REQ_(TOGGLE_DATE,       "Toggle date display"), \
274         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
275         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
276         REQ_(TOGGLE_GRAPHIC,    "Toggle (line) graphics mode"), \
277         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
278         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
279         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
280         \
281         REQ_GROUP("Misc") \
282         REQ_(PROMPT,            "Bring up the prompt"), \
283         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
284         REQ_(SHOW_VERSION,      "Show version information"), \
285         REQ_(STOP_LOADING,      "Stop all loading views"), \
286         REQ_(EDIT,              "Open in editor"), \
287         REQ_(NONE,              "Do nothing")
290 /* User action requests. */
291 enum request {
292 #define REQ_GROUP(help)
293 #define REQ_(req, help) REQ_##req
295         /* Offset all requests to avoid conflicts with ncurses getch values. */
296         REQ_UNKNOWN = KEY_MAX + 1,
297         REQ_OFFSET,
298         REQ_INFO
300 #undef  REQ_GROUP
301 #undef  REQ_
302 };
304 struct request_info {
305         enum request request;
306         const char *name;
307         int namelen;
308         const char *help;
309 };
311 static const struct request_info req_info[] = {
312 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
313 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
314         REQ_INFO
315 #undef  REQ_GROUP
316 #undef  REQ_
317 };
319 static enum request
320 get_request(const char *name)
322         int namelen = strlen(name);
323         int i;
325         for (i = 0; i < ARRAY_SIZE(req_info); i++)
326                 if (enum_equals(req_info[i], name, namelen))
327                         return req_info[i].request;
329         return REQ_UNKNOWN;
333 /*
334  * Options
335  */
337 /* Option and state variables. */
338 static enum graphic opt_line_graphics   = GRAPHIC_DEFAULT;
339 static enum date opt_date               = DATE_DEFAULT;
340 static enum author opt_author           = AUTHOR_DEFAULT;
341 static bool opt_rev_graph               = TRUE;
342 static bool opt_line_number             = FALSE;
343 static bool opt_show_refs               = TRUE;
344 static bool opt_untracked_dirs_content  = TRUE;
345 static int opt_num_interval             = 5;
346 static double opt_hscroll               = 0.50;
347 static double opt_scale_split_view      = 2.0 / 3.0;
348 static int opt_tab_size                 = 8;
349 static int opt_author_cols              = AUTHOR_COLS;
350 static char opt_path[SIZEOF_STR]        = "";
351 static char opt_file[SIZEOF_STR]        = "";
352 static char opt_ref[SIZEOF_REF]         = "";
353 static char opt_head[SIZEOF_REF]        = "";
354 static char opt_remote[SIZEOF_REF]      = "";
355 static char opt_encoding[20]            = "UTF-8";
356 static iconv_t opt_iconv_in             = ICONV_NONE;
357 static iconv_t opt_iconv_out            = ICONV_NONE;
358 static char opt_search[SIZEOF_STR]      = "";
359 static char opt_cdup[SIZEOF_STR]        = "";
360 static char opt_prefix[SIZEOF_STR]      = "";
361 static char opt_git_dir[SIZEOF_STR]     = "";
362 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
363 static char opt_editor[SIZEOF_STR]      = "";
364 static FILE *opt_tty                    = NULL;
365 static const char **opt_diff_argv       = NULL;
366 static const char **opt_rev_argv        = NULL;
367 static const char **opt_file_argv       = NULL;
368 static const char **opt_blame_argv      = NULL;
370 #define is_initial_commit()     (!get_ref_head())
371 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
374 /*
375  * Line-oriented content detection.
376  */
378 #define LINE_INFO \
379 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
380 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
381 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
382 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
383 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
384 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
385 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
386 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
387 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
388 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
389 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
390 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
391 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
392 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
393 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
394 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
395 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
396 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
397 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
398 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
399 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
400 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
401 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
402 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
403 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
404 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
405 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
406 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
407 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
408 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
409 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
410 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
411 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
412 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
413 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
414 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
415 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
416 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
417 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
418 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
419 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
420 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
421 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
422 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
423 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
424 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
425 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
426 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
427 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
428 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
429 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
430 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
431 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
432 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
433 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
434 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
435 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
436 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
437 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
438 LINE(GRAPH_LINE_0, "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
439 LINE(GRAPH_LINE_1, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
440 LINE(GRAPH_LINE_2, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
441 LINE(GRAPH_LINE_3, "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
442 LINE(GRAPH_LINE_4, "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
443 LINE(GRAPH_LINE_5, "",                  COLOR_WHITE,    COLOR_DEFAULT,  0), \
444 LINE(GRAPH_LINE_6, "",                  COLOR_RED,      COLOR_DEFAULT,  0), \
445 LINE(GRAPH_COMMIT, "",                  COLOR_BLUE,     COLOR_DEFAULT,  0)
447 enum line_type {
448 #define LINE(type, line, fg, bg, attr) \
449         LINE_##type
450         LINE_INFO,
451         LINE_NONE
452 #undef  LINE
453 };
455 struct line_info {
456         const char *name;       /* Option name. */
457         int namelen;            /* Size of option name. */
458         const char *line;       /* The start of line to match. */
459         int linelen;            /* Size of string to match. */
460         int fg, bg, attr;       /* Color and text attributes for the lines. */
461 };
463 static struct line_info line_info[] = {
464 #define LINE(type, line, fg, bg, attr) \
465         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
466         LINE_INFO
467 #undef  LINE
468 };
470 static enum line_type
471 get_line_type(const char *line)
473         int linelen = strlen(line);
474         enum line_type type;
476         for (type = 0; type < ARRAY_SIZE(line_info); type++)
477                 /* Case insensitive search matches Signed-off-by lines better. */
478                 if (linelen >= line_info[type].linelen &&
479                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
480                         return type;
482         return LINE_DEFAULT;
485 static inline int
486 get_line_attr(enum line_type type)
488         assert(type < ARRAY_SIZE(line_info));
489         return COLOR_PAIR(type) | line_info[type].attr;
492 static struct line_info *
493 get_line_info(const char *name)
495         size_t namelen = strlen(name);
496         enum line_type type;
498         for (type = 0; type < ARRAY_SIZE(line_info); type++)
499                 if (enum_equals(line_info[type], name, namelen))
500                         return &line_info[type];
502         return NULL;
505 static void
506 init_colors(void)
508         int default_bg = line_info[LINE_DEFAULT].bg;
509         int default_fg = line_info[LINE_DEFAULT].fg;
510         enum line_type type;
512         start_color();
514         if (assume_default_colors(default_fg, default_bg) == ERR) {
515                 default_bg = COLOR_BLACK;
516                 default_fg = COLOR_WHITE;
517         }
519         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
520                 struct line_info *info = &line_info[type];
521                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
522                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
524                 init_pair(type, fg, bg);
525         }
528 struct line {
529         enum line_type type;
531         /* State flags */
532         unsigned int selected:1;
533         unsigned int dirty:1;
534         unsigned int cleareol:1;
535         unsigned int other:16;
537         void *data;             /* User data */
538 };
541 /*
542  * Keys
543  */
545 struct keybinding {
546         int alias;
547         enum request request;
548 };
550 static struct keybinding default_keybindings[] = {
551         /* View switching */
552         { 'm',          REQ_VIEW_MAIN },
553         { 'd',          REQ_VIEW_DIFF },
554         { 'l',          REQ_VIEW_LOG },
555         { 't',          REQ_VIEW_TREE },
556         { 'f',          REQ_VIEW_BLOB },
557         { 'B',          REQ_VIEW_BLAME },
558         { 'H',          REQ_VIEW_BRANCH },
559         { 'p',          REQ_VIEW_PAGER },
560         { 'h',          REQ_VIEW_HELP },
561         { 'S',          REQ_VIEW_STATUS },
562         { 'c',          REQ_VIEW_STAGE },
564         /* View manipulation */
565         { 'q',          REQ_VIEW_CLOSE },
566         { KEY_TAB,      REQ_VIEW_NEXT },
567         { KEY_RETURN,   REQ_ENTER },
568         { KEY_UP,       REQ_PREVIOUS },
569         { KEY_CTL('P'), REQ_PREVIOUS },
570         { KEY_DOWN,     REQ_NEXT },
571         { KEY_CTL('N'), REQ_NEXT },
572         { 'R',          REQ_REFRESH },
573         { KEY_F(5),     REQ_REFRESH },
574         { 'O',          REQ_MAXIMIZE },
576         /* Cursor navigation */
577         { 'k',          REQ_MOVE_UP },
578         { 'j',          REQ_MOVE_DOWN },
579         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
580         { KEY_END,      REQ_MOVE_LAST_LINE },
581         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
582         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
583         { ' ',          REQ_MOVE_PAGE_DOWN },
584         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
585         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
586         { 'b',          REQ_MOVE_PAGE_UP },
587         { '-',          REQ_MOVE_PAGE_UP },
589         /* Scrolling */
590         { '|',          REQ_SCROLL_FIRST_COL },
591         { KEY_LEFT,     REQ_SCROLL_LEFT },
592         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
593         { KEY_IC,       REQ_SCROLL_LINE_UP },
594         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
595         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
596         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
597         { 'w',          REQ_SCROLL_PAGE_UP },
598         { 's',          REQ_SCROLL_PAGE_DOWN },
600         /* Searching */
601         { '/',          REQ_SEARCH },
602         { '?',          REQ_SEARCH_BACK },
603         { 'n',          REQ_FIND_NEXT },
604         { 'N',          REQ_FIND_PREV },
606         /* Misc */
607         { 'Q',          REQ_QUIT },
608         { 'z',          REQ_STOP_LOADING },
609         { 'v',          REQ_SHOW_VERSION },
610         { 'r',          REQ_SCREEN_REDRAW },
611         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
612         { 'o',          REQ_OPTIONS },
613         { '.',          REQ_TOGGLE_LINENO },
614         { 'D',          REQ_TOGGLE_DATE },
615         { 'A',          REQ_TOGGLE_AUTHOR },
616         { 'g',          REQ_TOGGLE_REV_GRAPH },
617         { '~',          REQ_TOGGLE_GRAPHIC },
618         { 'F',          REQ_TOGGLE_REFS },
619         { 'I',          REQ_TOGGLE_SORT_ORDER },
620         { 'i',          REQ_TOGGLE_SORT_FIELD },
621         { ':',          REQ_PROMPT },
622         { 'u',          REQ_STATUS_UPDATE },
623         { '!',          REQ_STATUS_REVERT },
624         { 'M',          REQ_STATUS_MERGE },
625         { '@',          REQ_STAGE_NEXT },
626         { ',',          REQ_PARENT },
627         { 'e',          REQ_EDIT },
628 };
630 #define KEYMAP_INFO \
631         KEYMAP_(GENERIC), \
632         KEYMAP_(MAIN), \
633         KEYMAP_(DIFF), \
634         KEYMAP_(LOG), \
635         KEYMAP_(TREE), \
636         KEYMAP_(BLOB), \
637         KEYMAP_(BLAME), \
638         KEYMAP_(BRANCH), \
639         KEYMAP_(PAGER), \
640         KEYMAP_(HELP), \
641         KEYMAP_(STATUS), \
642         KEYMAP_(STAGE)
644 enum keymap {
645 #define KEYMAP_(name) KEYMAP_##name
646         KEYMAP_INFO
647 #undef  KEYMAP_
648 };
650 static const struct enum_map keymap_table[] = {
651 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
652         KEYMAP_INFO
653 #undef  KEYMAP_
654 };
656 #define set_keymap(map, name) map_enum(map, keymap_table, name)
658 struct keybinding_table {
659         struct keybinding *data;
660         size_t size;
661 };
663 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
665 static void
666 add_keybinding(enum keymap keymap, enum request request, int key)
668         struct keybinding_table *table = &keybindings[keymap];
669         size_t i;
671         for (i = 0; i < keybindings[keymap].size; i++) {
672                 if (keybindings[keymap].data[i].alias == key) {
673                         keybindings[keymap].data[i].request = request;
674                         return;
675                 }
676         }
678         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
679         if (!table->data)
680                 die("Failed to allocate keybinding");
681         table->data[table->size].alias = key;
682         table->data[table->size++].request = request;
684         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
685                 int i;
687                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
688                         if (default_keybindings[i].alias == key)
689                                 default_keybindings[i].request = REQ_NONE;
690         }
693 /* Looks for a key binding first in the given map, then in the generic map, and
694  * lastly in the default keybindings. */
695 static enum request
696 get_keybinding(enum keymap keymap, int key)
698         size_t i;
700         for (i = 0; i < keybindings[keymap].size; i++)
701                 if (keybindings[keymap].data[i].alias == key)
702                         return keybindings[keymap].data[i].request;
704         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
705                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
706                         return keybindings[KEYMAP_GENERIC].data[i].request;
708         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
709                 if (default_keybindings[i].alias == key)
710                         return default_keybindings[i].request;
712         return (enum request) key;
716 struct key {
717         const char *name;
718         int value;
719 };
721 static const struct key key_table[] = {
722         { "Enter",      KEY_RETURN },
723         { "Space",      ' ' },
724         { "Backspace",  KEY_BACKSPACE },
725         { "Tab",        KEY_TAB },
726         { "Escape",     KEY_ESC },
727         { "Left",       KEY_LEFT },
728         { "Right",      KEY_RIGHT },
729         { "Up",         KEY_UP },
730         { "Down",       KEY_DOWN },
731         { "Insert",     KEY_IC },
732         { "Delete",     KEY_DC },
733         { "Hash",       '#' },
734         { "Home",       KEY_HOME },
735         { "End",        KEY_END },
736         { "PageUp",     KEY_PPAGE },
737         { "PageDown",   KEY_NPAGE },
738         { "F1",         KEY_F(1) },
739         { "F2",         KEY_F(2) },
740         { "F3",         KEY_F(3) },
741         { "F4",         KEY_F(4) },
742         { "F5",         KEY_F(5) },
743         { "F6",         KEY_F(6) },
744         { "F7",         KEY_F(7) },
745         { "F8",         KEY_F(8) },
746         { "F9",         KEY_F(9) },
747         { "F10",        KEY_F(10) },
748         { "F11",        KEY_F(11) },
749         { "F12",        KEY_F(12) },
750 };
752 static int
753 get_key_value(const char *name)
755         int i;
757         for (i = 0; i < ARRAY_SIZE(key_table); i++)
758                 if (!strcasecmp(key_table[i].name, name))
759                         return key_table[i].value;
761         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
762                 return (int)name[1] & 0x1f;
763         if (strlen(name) == 1 && isprint(*name))
764                 return (int) *name;
765         return ERR;
768 static const char *
769 get_key_name(int key_value)
771         static char key_char[] = "'X'\0";
772         const char *seq = NULL;
773         int key;
775         for (key = 0; key < ARRAY_SIZE(key_table); key++)
776                 if (key_table[key].value == key_value)
777                         seq = key_table[key].name;
779         if (seq == NULL && key_value < 0x7f) {
780                 char *s = key_char + 1;
782                 if (key_value >= 0x20) {
783                         *s++ = key_value;
784                 } else {
785                         *s++ = '^';
786                         *s++ = 0x40 | (key_value & 0x1f);
787                 }
788                 *s++ = '\'';
789                 *s++ = '\0';
790                 seq = key_char;
791         }
793         return seq ? seq : "(no key)";
796 static bool
797 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
799         const char *sep = *pos > 0 ? ", " : "";
800         const char *keyname = get_key_name(keybinding->alias);
802         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
805 static bool
806 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
807                            enum keymap keymap, bool all)
809         int i;
811         for (i = 0; i < keybindings[keymap].size; i++) {
812                 if (keybindings[keymap].data[i].request == request) {
813                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
814                                 return FALSE;
815                         if (!all)
816                                 break;
817                 }
818         }
820         return TRUE;
823 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
825 static const char *
826 get_keys(enum keymap keymap, enum request request, bool all)
828         static char buf[BUFSIZ];
829         size_t pos = 0;
830         int i;
832         buf[pos] = 0;
834         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
835                 return "Too many keybindings!";
836         if (pos > 0 && !all)
837                 return buf;
839         if (keymap != KEYMAP_GENERIC) {
840                 /* Only the generic keymap includes the default keybindings when
841                  * listing all keys. */
842                 if (all)
843                         return buf;
845                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
846                         return "Too many keybindings!";
847                 if (pos)
848                         return buf;
849         }
851         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
852                 if (default_keybindings[i].request == request) {
853                         if (!append_key(buf, &pos, &default_keybindings[i]))
854                                 return "Too many keybindings!";
855                         if (!all)
856                                 return buf;
857                 }
858         }
860         return buf;
863 struct run_request {
864         enum keymap keymap;
865         int key;
866         const char **argv;
867 };
869 static struct run_request *run_request;
870 static size_t run_requests;
872 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
874 static enum request
875 add_run_request(enum keymap keymap, int key, const char **argv)
877         struct run_request *req;
879         if (!realloc_run_requests(&run_request, run_requests, 1))
880                 return REQ_NONE;
882         req = &run_request[run_requests];
883         req->keymap = keymap;
884         req->key = key;
885         req->argv = NULL;
887         if (!argv_copy(&req->argv, argv))
888                 return REQ_NONE;
890         return REQ_NONE + ++run_requests;
893 static struct run_request *
894 get_run_request(enum request request)
896         if (request <= REQ_NONE)
897                 return NULL;
898         return &run_request[request - REQ_NONE - 1];
901 static void
902 add_builtin_run_requests(void)
904         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
905         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
906         const char *commit[] = { "git", "commit", NULL };
907         const char *gc[] = { "git", "gc", NULL };
908         struct run_request reqs[] = {
909                 { KEYMAP_MAIN,    'C', cherry_pick },
910                 { KEYMAP_STATUS,  'C', commit },
911                 { KEYMAP_BRANCH,  'C', checkout },
912                 { KEYMAP_GENERIC, 'G', gc },
913         };
914         int i;
916         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
917                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
919                 if (req != reqs[i].key)
920                         continue;
921                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
922                 if (req != REQ_NONE)
923                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
924         }
927 /*
928  * User config file handling.
929  */
931 #define OPT_ERR_INFO \
932         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
933         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
934         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
935         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
936         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
937         OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
938         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
939         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
940         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
941         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
942         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
943         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
944         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
945         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
946         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
947         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
948         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
950 enum option_code {
951 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
952         OPT_ERR_INFO
953 #undef  OPT_ERR_
954         OPT_OK
955 };
957 static const char *option_errors[] = {
958 #define OPT_ERR_(name, msg) msg
959         OPT_ERR_INFO
960 #undef  OPT_ERR_
961 };
963 static const struct enum_map color_map[] = {
964 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
965         COLOR_MAP(DEFAULT),
966         COLOR_MAP(BLACK),
967         COLOR_MAP(BLUE),
968         COLOR_MAP(CYAN),
969         COLOR_MAP(GREEN),
970         COLOR_MAP(MAGENTA),
971         COLOR_MAP(RED),
972         COLOR_MAP(WHITE),
973         COLOR_MAP(YELLOW),
974 };
976 static const struct enum_map attr_map[] = {
977 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
978         ATTR_MAP(NORMAL),
979         ATTR_MAP(BLINK),
980         ATTR_MAP(BOLD),
981         ATTR_MAP(DIM),
982         ATTR_MAP(REVERSE),
983         ATTR_MAP(STANDOUT),
984         ATTR_MAP(UNDERLINE),
985 };
987 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
989 static enum option_code
990 parse_step(double *opt, const char *arg)
992         *opt = atoi(arg);
993         if (!strchr(arg, '%'))
994                 return OPT_OK;
996         /* "Shift down" so 100% and 1 does not conflict. */
997         *opt = (*opt - 1) / 100;
998         if (*opt >= 1.0) {
999                 *opt = 0.99;
1000                 return OPT_ERR_INVALID_STEP_VALUE;
1001         }
1002         if (*opt < 0.0) {
1003                 *opt = 1;
1004                 return OPT_ERR_INVALID_STEP_VALUE;
1005         }
1006         return OPT_OK;
1009 static enum option_code
1010 parse_int(int *opt, const char *arg, int min, int max)
1012         int value = atoi(arg);
1014         if (min <= value && value <= max) {
1015                 *opt = value;
1016                 return OPT_OK;
1017         }
1019         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1022 static bool
1023 set_color(int *color, const char *name)
1025         if (map_enum(color, color_map, name))
1026                 return TRUE;
1027         if (!prefixcmp(name, "color"))
1028                 return parse_int(color, name + 5, 0, 255) == OK;
1029         return FALSE;
1032 /* Wants: object fgcolor bgcolor [attribute] */
1033 static enum option_code
1034 option_color_command(int argc, const char *argv[])
1036         struct line_info *info;
1038         if (argc < 3)
1039                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1041         info = get_line_info(argv[0]);
1042         if (!info) {
1043                 static const struct enum_map obsolete[] = {
1044                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1045                         ENUM_MAP("main-date",   LINE_DATE),
1046                         ENUM_MAP("main-author", LINE_AUTHOR),
1047                 };
1048                 int index;
1050                 if (!map_enum(&index, obsolete, argv[0]))
1051                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1052                 info = &line_info[index];
1053         }
1055         if (!set_color(&info->fg, argv[1]) ||
1056             !set_color(&info->bg, argv[2]))
1057                 return OPT_ERR_UNKNOWN_COLOR;
1059         info->attr = 0;
1060         while (argc-- > 3) {
1061                 int attr;
1063                 if (!set_attribute(&attr, argv[argc]))
1064                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1065                 info->attr |= attr;
1066         }
1068         return OPT_OK;
1071 static enum option_code
1072 parse_bool(bool *opt, const char *arg)
1074         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1075                 ? TRUE : FALSE;
1076         return OPT_OK;
1079 static enum option_code
1080 parse_enum_do(unsigned int *opt, const char *arg,
1081               const struct enum_map *map, size_t map_size)
1083         bool is_true;
1085         assert(map_size > 1);
1087         if (map_enum_do(map, map_size, (int *) opt, arg))
1088                 return OPT_OK;
1090         parse_bool(&is_true, arg);
1091         *opt = is_true ? map[1].value : map[0].value;
1092         return OPT_OK;
1095 #define parse_enum(opt, arg, map) \
1096         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1098 static enum option_code
1099 parse_string(char *opt, const char *arg, size_t optsize)
1101         int arglen = strlen(arg);
1103         switch (arg[0]) {
1104         case '\"':
1105         case '\'':
1106                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1107                         return OPT_ERR_UNMATCHED_QUOTATION;
1108                 arg += 1; arglen -= 2;
1109         default:
1110                 string_ncopy_do(opt, optsize, arg, arglen);
1111                 return OPT_OK;
1112         }
1115 static enum option_code
1116 parse_args(const char ***args, const char *argv[])
1118         if (*args == NULL && !argv_copy(args, argv))
1119                 return OPT_ERR_OUT_OF_MEMORY;
1120         return OPT_OK;
1123 /* Wants: name = value */
1124 static enum option_code
1125 option_set_command(int argc, const char *argv[])
1127         if (argc < 3)
1128                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1130         if (strcmp(argv[1], "="))
1131                 return OPT_ERR_NO_VALUE_ASSIGNED;
1133         if (!strcmp(argv[0], "blame-options"))
1134                 return parse_args(&opt_blame_argv, argv + 2);
1136         if (argc != 3)
1137                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1139         if (!strcmp(argv[0], "show-author"))
1140                 return parse_enum(&opt_author, argv[2], author_map);
1142         if (!strcmp(argv[0], "show-date"))
1143                 return parse_enum(&opt_date, argv[2], date_map);
1145         if (!strcmp(argv[0], "show-rev-graph"))
1146                 return parse_bool(&opt_rev_graph, argv[2]);
1148         if (!strcmp(argv[0], "show-refs"))
1149                 return parse_bool(&opt_show_refs, argv[2]);
1151         if (!strcmp(argv[0], "show-line-numbers"))
1152                 return parse_bool(&opt_line_number, argv[2]);
1154         if (!strcmp(argv[0], "line-graphics"))
1155                 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1157         if (!strcmp(argv[0], "line-number-interval"))
1158                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1160         if (!strcmp(argv[0], "author-width"))
1161                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1163         if (!strcmp(argv[0], "horizontal-scroll"))
1164                 return parse_step(&opt_hscroll, argv[2]);
1166         if (!strcmp(argv[0], "split-view-height"))
1167                 return parse_step(&opt_scale_split_view, argv[2]);
1169         if (!strcmp(argv[0], "tab-size"))
1170                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1172         if (!strcmp(argv[0], "commit-encoding"))
1173                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1175         if (!strcmp(argv[0], "status-untracked-dirs"))
1176                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1178         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1181 /* Wants: mode request key */
1182 static enum option_code
1183 option_bind_command(int argc, const char *argv[])
1185         enum request request;
1186         int keymap = -1;
1187         int key;
1189         if (argc < 3)
1190                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1192         if (!set_keymap(&keymap, argv[0]))
1193                 return OPT_ERR_UNKNOWN_KEY_MAP;
1195         key = get_key_value(argv[1]);
1196         if (key == ERR)
1197                 return OPT_ERR_UNKNOWN_KEY;
1199         request = get_request(argv[2]);
1200         if (request == REQ_UNKNOWN) {
1201                 static const struct enum_map obsolete[] = {
1202                         ENUM_MAP("cherry-pick",         REQ_NONE),
1203                         ENUM_MAP("screen-resize",       REQ_NONE),
1204                         ENUM_MAP("tree-parent",         REQ_PARENT),
1205                 };
1206                 int alias;
1208                 if (map_enum(&alias, obsolete, argv[2])) {
1209                         if (alias != REQ_NONE)
1210                                 add_keybinding(keymap, alias, key);
1211                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1212                 }
1213         }
1214         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1215                 request = add_run_request(keymap, key, argv + 2);
1216         if (request == REQ_UNKNOWN)
1217                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1219         add_keybinding(keymap, request, key);
1221         return OPT_OK;
1224 static enum option_code
1225 set_option(const char *opt, char *value)
1227         const char *argv[SIZEOF_ARG];
1228         int argc = 0;
1230         if (!argv_from_string(argv, &argc, value))
1231                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1233         if (!strcmp(opt, "color"))
1234                 return option_color_command(argc, argv);
1236         if (!strcmp(opt, "set"))
1237                 return option_set_command(argc, argv);
1239         if (!strcmp(opt, "bind"))
1240                 return option_bind_command(argc, argv);
1242         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1245 struct config_state {
1246         int lineno;
1247         bool errors;
1248 };
1250 static int
1251 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1253         struct config_state *config = data;
1254         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1256         config->lineno++;
1258         /* Check for comment markers, since read_properties() will
1259          * only ensure opt and value are split at first " \t". */
1260         optlen = strcspn(opt, "#");
1261         if (optlen == 0)
1262                 return OK;
1264         if (opt[optlen] == 0) {
1265                 /* Look for comment endings in the value. */
1266                 size_t len = strcspn(value, "#");
1268                 if (len < valuelen) {
1269                         valuelen = len;
1270                         value[valuelen] = 0;
1271                 }
1273                 status = set_option(opt, value);
1274         }
1276         if (status != OPT_OK) {
1277                 warn("Error on line %d, near '%.*s': %s",
1278                      config->lineno, (int) optlen, opt, option_errors[status]);
1279                 config->errors = TRUE;
1280         }
1282         /* Always keep going if errors are encountered. */
1283         return OK;
1286 static void
1287 load_option_file(const char *path)
1289         struct config_state config = { 0, FALSE };
1290         struct io io;
1292         /* It's OK that the file doesn't exist. */
1293         if (!io_open(&io, "%s", path))
1294                 return;
1296         if (io_load(&io, " \t", read_option, &config) == ERR ||
1297             config.errors == TRUE)
1298                 warn("Errors while loading %s.", path);
1301 static int
1302 load_options(void)
1304         const char *home = getenv("HOME");
1305         const char *tigrc_user = getenv("TIGRC_USER");
1306         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1307         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1308         char buf[SIZEOF_STR];
1310         if (!tigrc_system)
1311                 tigrc_system = SYSCONFDIR "/tigrc";
1312         load_option_file(tigrc_system);
1314         if (!tigrc_user) {
1315                 if (!home || !string_format(buf, "%s/.tigrc", home))
1316                         return ERR;
1317                 tigrc_user = buf;
1318         }
1319         load_option_file(tigrc_user);
1321         /* Add _after_ loading config files to avoid adding run requests
1322          * that conflict with keybindings. */
1323         add_builtin_run_requests();
1325         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1326                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1327                 int argc = 0;
1329                 if (!string_format(buf, "%s", tig_diff_opts) ||
1330                     !argv_from_string(diff_opts, &argc, buf))
1331                         die("TIG_DIFF_OPTS contains too many arguments");
1332                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1333                         die("Failed to format TIG_DIFF_OPTS arguments");
1334         }
1336         return OK;
1340 /*
1341  * The viewer
1342  */
1344 struct view;
1345 struct view_ops;
1347 /* The display array of active views and the index of the current view. */
1348 static struct view *display[2];
1349 static WINDOW *display_win[2];
1350 static WINDOW *display_title[2];
1351 static unsigned int current_view;
1353 #define foreach_displayed_view(view, i) \
1354         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1356 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1358 /* Current head and commit ID */
1359 static char ref_blob[SIZEOF_REF]        = "";
1360 static char ref_commit[SIZEOF_REF]      = "HEAD";
1361 static char ref_head[SIZEOF_REF]        = "HEAD";
1362 static char ref_branch[SIZEOF_REF]      = "";
1364 enum view_type {
1365         VIEW_MAIN,
1366         VIEW_DIFF,
1367         VIEW_LOG,
1368         VIEW_TREE,
1369         VIEW_BLOB,
1370         VIEW_BLAME,
1371         VIEW_BRANCH,
1372         VIEW_HELP,
1373         VIEW_PAGER,
1374         VIEW_STATUS,
1375         VIEW_STAGE,
1376 };
1378 struct view {
1379         enum view_type type;    /* View type */
1380         const char *name;       /* View name */
1381         const char *id;         /* Points to either of ref_{head,commit,blob} */
1383         struct view_ops *ops;   /* View operations */
1385         enum keymap keymap;     /* What keymap does this view have */
1386         bool git_dir;           /* Whether the view requires a git directory. */
1388         char ref[SIZEOF_REF];   /* Hovered commit reference */
1389         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1391         int height, width;      /* The width and height of the main window */
1392         WINDOW *win;            /* The main window */
1394         /* Navigation */
1395         unsigned long offset;   /* Offset of the window top */
1396         unsigned long yoffset;  /* Offset from the window side. */
1397         unsigned long lineno;   /* Current line number */
1398         unsigned long p_offset; /* Previous offset of the window top */
1399         unsigned long p_yoffset;/* Previous offset from the window side */
1400         unsigned long p_lineno; /* Previous current line number */
1401         bool p_restore;         /* Should the previous position be restored. */
1403         /* Searching */
1404         char grep[SIZEOF_STR];  /* Search string */
1405         regex_t *regex;         /* Pre-compiled regexp */
1407         /* If non-NULL, points to the view that opened this view. If this view
1408          * is closed tig will switch back to the parent view. */
1409         struct view *parent;
1410         struct view *prev;
1412         /* Buffering */
1413         size_t lines;           /* Total number of lines */
1414         struct line *line;      /* Line index */
1415         unsigned int digits;    /* Number of digits in the lines member. */
1417         /* Drawing */
1418         struct line *curline;   /* Line currently being drawn. */
1419         enum line_type curtype; /* Attribute currently used for drawing. */
1420         unsigned long col;      /* Column when drawing. */
1421         bool has_scrolled;      /* View was scrolled. */
1423         /* Loading */
1424         const char **argv;      /* Shell command arguments. */
1425         const char *dir;        /* Directory from which to execute. */
1426         struct io io;
1427         struct io *pipe;
1428         time_t start_time;
1429         time_t update_secs;
1430 };
1432 enum open_flags {
1433         OPEN_DEFAULT = 0,       /* Use default view switching. */
1434         OPEN_SPLIT = 1,         /* Split current view. */
1435         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1436         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
1437         OPEN_PREPARED = 32,     /* Open already prepared command. */
1438 };
1440 struct view_ops {
1441         /* What type of content being displayed. Used in the title bar. */
1442         const char *type;
1443         /* Open and reads in all view content. */
1444         bool (*open)(struct view *view, enum open_flags flags);
1445         /* Read one line; updates view->line. */
1446         bool (*read)(struct view *view, char *data);
1447         /* Draw one line; @lineno must be < view->height. */
1448         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1449         /* Depending on view handle a special requests. */
1450         enum request (*request)(struct view *view, enum request request, struct line *line);
1451         /* Search for regexp in a line. */
1452         bool (*grep)(struct view *view, struct line *line);
1453         /* Select line */
1454         void (*select)(struct view *view, struct line *line);
1455 };
1457 static struct view_ops blame_ops;
1458 static struct view_ops blob_ops;
1459 static struct view_ops diff_ops;
1460 static struct view_ops help_ops;
1461 static struct view_ops log_ops;
1462 static struct view_ops main_ops;
1463 static struct view_ops pager_ops;
1464 static struct view_ops stage_ops;
1465 static struct view_ops status_ops;
1466 static struct view_ops tree_ops;
1467 static struct view_ops branch_ops;
1469 #define VIEW_STR(type, name, ref, ops, map, git) \
1470         { type, name, ref, ops, map, git }
1472 #define VIEW_(id, name, ops, git, ref) \
1473         VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1475 static struct view views[] = {
1476         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1477         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1478         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1479         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1480         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1481         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1482         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1483         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1484         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1485         VIEW_(STATUS, "status", &status_ops, TRUE,  ""),
1486         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1487 };
1489 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1491 #define foreach_view(view, i) \
1492         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1494 #define view_is_displayed(view) \
1495         (view == display[0] || view == display[1])
1497 static enum request
1498 view_request(struct view *view, enum request request)
1500         if (!view || !view->lines)
1501                 return request;
1502         return view->ops->request(view, request, &view->line[view->lineno]);
1506 /*
1507  * View drawing.
1508  */
1510 static inline void
1511 set_view_attr(struct view *view, enum line_type type)
1513         if (!view->curline->selected && view->curtype != type) {
1514                 (void) wattrset(view->win, get_line_attr(type));
1515                 wchgat(view->win, -1, 0, type, NULL);
1516                 view->curtype = type;
1517         }
1520 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1522 static bool
1523 draw_chars(struct view *view, enum line_type type, const char *string,
1524            int max_len, bool use_tilde)
1526         static char out_buffer[BUFSIZ * 2];
1527         int len = 0;
1528         int col = 0;
1529         int trimmed = FALSE;
1530         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1532         if (max_len <= 0)
1533                 return VIEW_MAX_LEN(view) <= 0;
1535         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1537         set_view_attr(view, type);
1538         if (len > 0) {
1539                 if (opt_iconv_out != ICONV_NONE) {
1540                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1541                         size_t inlen = len + 1;
1543                         char *outbuf = out_buffer;
1544                         size_t outlen = sizeof(out_buffer);
1546                         size_t ret;
1548                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1549                         if (ret != (size_t) -1) {
1550                                 string = out_buffer;
1551                                 len = sizeof(out_buffer) - outlen;
1552                         }
1553                 }
1555                 waddnstr(view->win, string, len);
1557                 if (trimmed && use_tilde) {
1558                         set_view_attr(view, LINE_DELIMITER);
1559                         waddch(view->win, '~');
1560                         col++;
1561                 }
1562         }
1564         view->col += col;
1565         return VIEW_MAX_LEN(view) <= 0;
1568 static bool
1569 draw_space(struct view *view, enum line_type type, int max, int spaces)
1571         static char space[] = "                    ";
1573         spaces = MIN(max, spaces);
1575         while (spaces > 0) {
1576                 int len = MIN(spaces, sizeof(space) - 1);
1578                 if (draw_chars(view, type, space, len, FALSE))
1579                         return TRUE;
1580                 spaces -= len;
1581         }
1583         return VIEW_MAX_LEN(view) <= 0;
1586 static bool
1587 draw_text(struct view *view, enum line_type type, const char *string)
1589         char text[SIZEOF_STR];
1591         do {
1592                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1594                 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1595                         return TRUE;
1596                 string += pos;
1597         } while (*string);
1599         return VIEW_MAX_LEN(view) <= 0;
1602 static bool
1603 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1605         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1606         int max = VIEW_MAX_LEN(view);
1607         int i;
1609         if (max < size)
1610                 size = max;
1612         set_view_attr(view, type);
1613         /* Using waddch() instead of waddnstr() ensures that
1614          * they'll be rendered correctly for the cursor line. */
1615         for (i = skip; i < size; i++)
1616                 waddch(view->win, graphic[i]);
1618         view->col += size;
1619         if (separator) {
1620                 if (size < max && skip <= size)
1621                         waddch(view->win, ' ');
1622                 view->col++;
1623         }
1625         return VIEW_MAX_LEN(view) <= 0;
1628 static bool
1629 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1631         int max = MIN(VIEW_MAX_LEN(view), len);
1632         int col = view->col;
1634         if (!text) 
1635                 return draw_space(view, type, max, max);
1637         return draw_chars(view, type, text, max - 1, trim)
1638             || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1641 static bool
1642 draw_date(struct view *view, struct time *time)
1644         const char *date = mkdate(time, opt_date);
1645         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1647         if (opt_date == DATE_NO)
1648                 return FALSE;
1650         return draw_field(view, LINE_DATE, date, cols, FALSE);
1653 static bool
1654 draw_author(struct view *view, const char *author)
1656         bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1657         bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1659         if (opt_author == AUTHOR_NO)
1660                 return FALSE;
1662         if (abbreviate && author)
1663                 author = get_author_initials(author);
1665         return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1668 static bool
1669 draw_mode(struct view *view, mode_t mode)
1671         const char *str;
1673         if (S_ISDIR(mode))
1674                 str = "drwxr-xr-x";
1675         else if (S_ISLNK(mode))
1676                 str = "lrwxrwxrwx";
1677         else if (S_ISGITLINK(mode))
1678                 str = "m---------";
1679         else if (S_ISREG(mode) && mode & S_IXUSR)
1680                 str = "-rwxr-xr-x";
1681         else if (S_ISREG(mode))
1682                 str = "-rw-r--r--";
1683         else
1684                 str = "----------";
1686         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1689 static bool
1690 draw_lineno(struct view *view, unsigned int lineno)
1692         char number[10];
1693         int digits3 = view->digits < 3 ? 3 : view->digits;
1694         int max = MIN(VIEW_MAX_LEN(view), digits3);
1695         char *text = NULL;
1696         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1698         lineno += view->offset + 1;
1699         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1700                 static char fmt[] = "%1ld";
1702                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1703                 if (string_format(number, fmt, lineno))
1704                         text = number;
1705         }
1706         if (text)
1707                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1708         else
1709                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1710         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1713 static bool
1714 draw_view_line(struct view *view, unsigned int lineno)
1716         struct line *line;
1717         bool selected = (view->offset + lineno == view->lineno);
1719         assert(view_is_displayed(view));
1721         if (view->offset + lineno >= view->lines)
1722                 return FALSE;
1724         line = &view->line[view->offset + lineno];
1726         wmove(view->win, lineno, 0);
1727         if (line->cleareol)
1728                 wclrtoeol(view->win);
1729         view->col = 0;
1730         view->curline = line;
1731         view->curtype = LINE_NONE;
1732         line->selected = FALSE;
1733         line->dirty = line->cleareol = 0;
1735         if (selected) {
1736                 set_view_attr(view, LINE_CURSOR);
1737                 line->selected = TRUE;
1738                 view->ops->select(view, line);
1739         }
1741         return view->ops->draw(view, line, lineno);
1744 static void
1745 redraw_view_dirty(struct view *view)
1747         bool dirty = FALSE;
1748         int lineno;
1750         for (lineno = 0; lineno < view->height; lineno++) {
1751                 if (view->offset + lineno >= view->lines)
1752                         break;
1753                 if (!view->line[view->offset + lineno].dirty)
1754                         continue;
1755                 dirty = TRUE;
1756                 if (!draw_view_line(view, lineno))
1757                         break;
1758         }
1760         if (!dirty)
1761                 return;
1762         wnoutrefresh(view->win);
1765 static void
1766 redraw_view_from(struct view *view, int lineno)
1768         assert(0 <= lineno && lineno < view->height);
1770         for (; lineno < view->height; lineno++) {
1771                 if (!draw_view_line(view, lineno))
1772                         break;
1773         }
1775         wnoutrefresh(view->win);
1778 static void
1779 redraw_view(struct view *view)
1781         werase(view->win);
1782         redraw_view_from(view, 0);
1786 static void
1787 update_view_title(struct view *view)
1789         char buf[SIZEOF_STR];
1790         char state[SIZEOF_STR];
1791         size_t bufpos = 0, statelen = 0;
1792         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1794         assert(view_is_displayed(view));
1796         if (view->type != VIEW_STATUS && view->lines) {
1797                 unsigned int view_lines = view->offset + view->height;
1798                 unsigned int lines = view->lines
1799                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1800                                    : 0;
1802                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1803                                    view->ops->type,
1804                                    view->lineno + 1,
1805                                    view->lines,
1806                                    lines);
1808         }
1810         if (view->pipe) {
1811                 time_t secs = time(NULL) - view->start_time;
1813                 /* Three git seconds are a long time ... */
1814                 if (secs > 2)
1815                         string_format_from(state, &statelen, " loading %lds", secs);
1816         }
1818         string_format_from(buf, &bufpos, "[%s]", view->name);
1819         if (*view->ref && bufpos < view->width) {
1820                 size_t refsize = strlen(view->ref);
1821                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1823                 if (minsize < view->width)
1824                         refsize = view->width - minsize + 7;
1825                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1826         }
1828         if (statelen && bufpos < view->width) {
1829                 string_format_from(buf, &bufpos, "%s", state);
1830         }
1832         if (view == display[current_view])
1833                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1834         else
1835                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1837         mvwaddnstr(window, 0, 0, buf, bufpos);
1838         wclrtoeol(window);
1839         wnoutrefresh(window);
1842 static int
1843 apply_step(double step, int value)
1845         if (step >= 1)
1846                 return (int) step;
1847         value *= step + 0.01;
1848         return value ? value : 1;
1851 static void
1852 resize_display(void)
1854         int offset, i;
1855         struct view *base = display[0];
1856         struct view *view = display[1] ? display[1] : display[0];
1858         /* Setup window dimensions */
1860         getmaxyx(stdscr, base->height, base->width);
1862         /* Make room for the status window. */
1863         base->height -= 1;
1865         if (view != base) {
1866                 /* Horizontal split. */
1867                 view->width   = base->width;
1868                 view->height  = apply_step(opt_scale_split_view, base->height);
1869                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1870                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1871                 base->height -= view->height;
1873                 /* Make room for the title bar. */
1874                 view->height -= 1;
1875         }
1877         /* Make room for the title bar. */
1878         base->height -= 1;
1880         offset = 0;
1882         foreach_displayed_view (view, i) {
1883                 if (!display_win[i]) {
1884                         display_win[i] = newwin(view->height, view->width, offset, 0);
1885                         if (!display_win[i])
1886                                 die("Failed to create %s view", view->name);
1888                         scrollok(display_win[i], FALSE);
1890                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1891                         if (!display_title[i])
1892                                 die("Failed to create title window");
1894                 } else {
1895                         wresize(display_win[i], view->height, view->width);
1896                         mvwin(display_win[i],   offset, 0);
1897                         mvwin(display_title[i], offset + view->height, 0);
1898                 }
1900                 view->win = display_win[i];
1902                 offset += view->height + 1;
1903         }
1906 static void
1907 redraw_display(bool clear)
1909         struct view *view;
1910         int i;
1912         foreach_displayed_view (view, i) {
1913                 if (clear)
1914                         wclear(view->win);
1915                 redraw_view(view);
1916                 update_view_title(view);
1917         }
1921 /*
1922  * Option management
1923  */
1925 #define TOGGLE_MENU \
1926         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1927         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1928         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1929         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1930         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1931         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1933 static void
1934 toggle_option(enum request request)
1936         const struct {
1937                 enum request request;
1938                 const struct enum_map *map;
1939                 size_t map_size;
1940         } data[] = {            
1941 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1942                 TOGGLE_MENU
1943 #undef  TOGGLE_
1944         };
1945         const struct menu_item menu[] = {
1946 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1947                 TOGGLE_MENU
1948 #undef  TOGGLE_
1949                 { 0 }
1950         };
1951         int i = 0;
1953         if (request == REQ_OPTIONS) {
1954                 if (!prompt_menu("Toggle option", menu, &i))
1955                         return;
1956         } else {
1957                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1958                         i++;
1959                 if (i >= ARRAY_SIZE(data))
1960                         die("Invalid request (%d)", request);
1961         }
1963         if (data[i].map != NULL) {
1964                 unsigned int *opt = menu[i].data;
1966                 *opt = (*opt + 1) % data[i].map_size;
1967                 redraw_display(FALSE);
1968                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1970         } else {
1971                 bool *option = menu[i].data;
1973                 *option = !*option;
1974                 redraw_display(FALSE);
1975                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1976         }
1979 static void
1980 maximize_view(struct view *view, bool redraw)
1982         memset(display, 0, sizeof(display));
1983         current_view = 0;
1984         display[current_view] = view;
1985         resize_display();
1986         if (redraw) {
1987                 redraw_display(FALSE);
1988                 report("");
1989         }
1993 /*
1994  * Navigation
1995  */
1997 static bool
1998 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2000         if (lineno >= view->lines)
2001                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2003         if (offset > lineno || offset + view->height <= lineno) {
2004                 unsigned long half = view->height / 2;
2006                 if (lineno > half)
2007                         offset = lineno - half;
2008                 else
2009                         offset = 0;
2010         }
2012         if (offset != view->offset || lineno != view->lineno) {
2013                 view->offset = offset;
2014                 view->lineno = lineno;
2015                 return TRUE;
2016         }
2018         return FALSE;
2021 /* Scrolling backend */
2022 static void
2023 do_scroll_view(struct view *view, int lines)
2025         bool redraw_current_line = FALSE;
2027         /* The rendering expects the new offset. */
2028         view->offset += lines;
2030         assert(0 <= view->offset && view->offset < view->lines);
2031         assert(lines);
2033         /* Move current line into the view. */
2034         if (view->lineno < view->offset) {
2035                 view->lineno = view->offset;
2036                 redraw_current_line = TRUE;
2037         } else if (view->lineno >= view->offset + view->height) {
2038                 view->lineno = view->offset + view->height - 1;
2039                 redraw_current_line = TRUE;
2040         }
2042         assert(view->offset <= view->lineno && view->lineno < view->lines);
2044         /* Redraw the whole screen if scrolling is pointless. */
2045         if (view->height < ABS(lines)) {
2046                 redraw_view(view);
2048         } else {
2049                 int line = lines > 0 ? view->height - lines : 0;
2050                 int end = line + ABS(lines);
2052                 scrollok(view->win, TRUE);
2053                 wscrl(view->win, lines);
2054                 scrollok(view->win, FALSE);
2056                 while (line < end && draw_view_line(view, line))
2057                         line++;
2059                 if (redraw_current_line)
2060                         draw_view_line(view, view->lineno - view->offset);
2061                 wnoutrefresh(view->win);
2062         }
2064         view->has_scrolled = TRUE;
2065         report("");
2068 /* Scroll frontend */
2069 static void
2070 scroll_view(struct view *view, enum request request)
2072         int lines = 1;
2074         assert(view_is_displayed(view));
2076         switch (request) {
2077         case REQ_SCROLL_FIRST_COL:
2078                 view->yoffset = 0;
2079                 redraw_view_from(view, 0);
2080                 report("");
2081                 return;
2082         case REQ_SCROLL_LEFT:
2083                 if (view->yoffset == 0) {
2084                         report("Cannot scroll beyond the first column");
2085                         return;
2086                 }
2087                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2088                         view->yoffset = 0;
2089                 else
2090                         view->yoffset -= apply_step(opt_hscroll, view->width);
2091                 redraw_view_from(view, 0);
2092                 report("");
2093                 return;
2094         case REQ_SCROLL_RIGHT:
2095                 view->yoffset += apply_step(opt_hscroll, view->width);
2096                 redraw_view(view);
2097                 report("");
2098                 return;
2099         case REQ_SCROLL_PAGE_DOWN:
2100                 lines = view->height;
2101         case REQ_SCROLL_LINE_DOWN:
2102                 if (view->offset + lines > view->lines)
2103                         lines = view->lines - view->offset;
2105                 if (lines == 0 || view->offset + view->height >= view->lines) {
2106                         report("Cannot scroll beyond the last line");
2107                         return;
2108                 }
2109                 break;
2111         case REQ_SCROLL_PAGE_UP:
2112                 lines = view->height;
2113         case REQ_SCROLL_LINE_UP:
2114                 if (lines > view->offset)
2115                         lines = view->offset;
2117                 if (lines == 0) {
2118                         report("Cannot scroll beyond the first line");
2119                         return;
2120                 }
2122                 lines = -lines;
2123                 break;
2125         default:
2126                 die("request %d not handled in switch", request);
2127         }
2129         do_scroll_view(view, lines);
2132 /* Cursor moving */
2133 static void
2134 move_view(struct view *view, enum request request)
2136         int scroll_steps = 0;
2137         int steps;
2139         switch (request) {
2140         case REQ_MOVE_FIRST_LINE:
2141                 steps = -view->lineno;
2142                 break;
2144         case REQ_MOVE_LAST_LINE:
2145                 steps = view->lines - view->lineno - 1;
2146                 break;
2148         case REQ_MOVE_PAGE_UP:
2149                 steps = view->height > view->lineno
2150                       ? -view->lineno : -view->height;
2151                 break;
2153         case REQ_MOVE_PAGE_DOWN:
2154                 steps = view->lineno + view->height >= view->lines
2155                       ? view->lines - view->lineno - 1 : view->height;
2156                 break;
2158         case REQ_MOVE_UP:
2159                 steps = -1;
2160                 break;
2162         case REQ_MOVE_DOWN:
2163                 steps = 1;
2164                 break;
2166         default:
2167                 die("request %d not handled in switch", request);
2168         }
2170         if (steps <= 0 && view->lineno == 0) {
2171                 report("Cannot move beyond the first line");
2172                 return;
2174         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2175                 report("Cannot move beyond the last line");
2176                 return;
2177         }
2179         /* Move the current line */
2180         view->lineno += steps;
2181         assert(0 <= view->lineno && view->lineno < view->lines);
2183         /* Check whether the view needs to be scrolled */
2184         if (view->lineno < view->offset ||
2185             view->lineno >= view->offset + view->height) {
2186                 scroll_steps = steps;
2187                 if (steps < 0 && -steps > view->offset) {
2188                         scroll_steps = -view->offset;
2190                 } else if (steps > 0) {
2191                         if (view->lineno == view->lines - 1 &&
2192                             view->lines > view->height) {
2193                                 scroll_steps = view->lines - view->offset - 1;
2194                                 if (scroll_steps >= view->height)
2195                                         scroll_steps -= view->height - 1;
2196                         }
2197                 }
2198         }
2200         if (!view_is_displayed(view)) {
2201                 view->offset += scroll_steps;
2202                 assert(0 <= view->offset && view->offset < view->lines);
2203                 view->ops->select(view, &view->line[view->lineno]);
2204                 return;
2205         }
2207         /* Repaint the old "current" line if we be scrolling */
2208         if (ABS(steps) < view->height)
2209                 draw_view_line(view, view->lineno - steps - view->offset);
2211         if (scroll_steps) {
2212                 do_scroll_view(view, scroll_steps);
2213                 return;
2214         }
2216         /* Draw the current line */
2217         draw_view_line(view, view->lineno - view->offset);
2219         wnoutrefresh(view->win);
2220         report("");
2224 /*
2225  * Searching
2226  */
2228 static void search_view(struct view *view, enum request request);
2230 static bool
2231 grep_text(struct view *view, const char *text[])
2233         regmatch_t pmatch;
2234         size_t i;
2236         for (i = 0; text[i]; i++)
2237                 if (*text[i] &&
2238                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2239                         return TRUE;
2240         return FALSE;
2243 static void
2244 select_view_line(struct view *view, unsigned long lineno)
2246         unsigned long old_lineno = view->lineno;
2247         unsigned long old_offset = view->offset;
2249         if (goto_view_line(view, view->offset, lineno)) {
2250                 if (view_is_displayed(view)) {
2251                         if (old_offset != view->offset) {
2252                                 redraw_view(view);
2253                         } else {
2254                                 draw_view_line(view, old_lineno - view->offset);
2255                                 draw_view_line(view, view->lineno - view->offset);
2256                                 wnoutrefresh(view->win);
2257                         }
2258                 } else {
2259                         view->ops->select(view, &view->line[view->lineno]);
2260                 }
2261         }
2264 static void
2265 find_next(struct view *view, enum request request)
2267         unsigned long lineno = view->lineno;
2268         int direction;
2270         if (!*view->grep) {
2271                 if (!*opt_search)
2272                         report("No previous search");
2273                 else
2274                         search_view(view, request);
2275                 return;
2276         }
2278         switch (request) {
2279         case REQ_SEARCH:
2280         case REQ_FIND_NEXT:
2281                 direction = 1;
2282                 break;
2284         case REQ_SEARCH_BACK:
2285         case REQ_FIND_PREV:
2286                 direction = -1;
2287                 break;
2289         default:
2290                 return;
2291         }
2293         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2294                 lineno += direction;
2296         /* Note, lineno is unsigned long so will wrap around in which case it
2297          * will become bigger than view->lines. */
2298         for (; lineno < view->lines; lineno += direction) {
2299                 if (view->ops->grep(view, &view->line[lineno])) {
2300                         select_view_line(view, lineno);
2301                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2302                         return;
2303                 }
2304         }
2306         report("No match found for '%s'", view->grep);
2309 static void
2310 search_view(struct view *view, enum request request)
2312         int regex_err;
2314         if (view->regex) {
2315                 regfree(view->regex);
2316                 *view->grep = 0;
2317         } else {
2318                 view->regex = calloc(1, sizeof(*view->regex));
2319                 if (!view->regex)
2320                         return;
2321         }
2323         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2324         if (regex_err != 0) {
2325                 char buf[SIZEOF_STR] = "unknown error";
2327                 regerror(regex_err, view->regex, buf, sizeof(buf));
2328                 report("Search failed: %s", buf);
2329                 return;
2330         }
2332         string_copy(view->grep, opt_search);
2334         find_next(view, request);
2337 /*
2338  * Incremental updating
2339  */
2341 static void
2342 reset_view(struct view *view)
2344         int i;
2346         for (i = 0; i < view->lines; i++)
2347                 free(view->line[i].data);
2348         free(view->line);
2350         view->p_offset = view->offset;
2351         view->p_yoffset = view->yoffset;
2352         view->p_lineno = view->lineno;
2354         view->line = NULL;
2355         view->offset = 0;
2356         view->yoffset = 0;
2357         view->lines  = 0;
2358         view->lineno = 0;
2359         view->vid[0] = 0;
2360         view->update_secs = 0;
2363 static const char *
2364 format_arg(const char *name)
2366         static struct {
2367                 const char *name;
2368                 size_t namelen;
2369                 const char *value;
2370                 const char *value_if_empty;
2371         } vars[] = {
2372 #define FORMAT_VAR(name, value, value_if_empty) \
2373         { name, STRING_SIZE(name), value, value_if_empty }
2374                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2375                 FORMAT_VAR("%(file)",           opt_file,       ""),
2376                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2377                 FORMAT_VAR("%(head)",           ref_head,       ""),
2378                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2379                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2380                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2381         };
2382         int i;
2384         for (i = 0; i < ARRAY_SIZE(vars); i++)
2385                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2386                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2388         report("Unknown replacement: `%s`", name);
2389         return NULL;
2392 static bool
2393 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2395         char buf[SIZEOF_STR];
2396         int argc;
2398         argv_free(*dst_argv);
2400         for (argc = 0; src_argv[argc]; argc++) {
2401                 const char *arg = src_argv[argc];
2402                 size_t bufpos = 0;
2404                 if (!strcmp(arg, "%(fileargs)")) {
2405                         if (!argv_append_array(dst_argv, opt_file_argv))
2406                                 break;
2407                         continue;
2409                 } else if (!strcmp(arg, "%(diffargs)")) {
2410                         if (!argv_append_array(dst_argv, opt_diff_argv))
2411                                 break;
2412                         continue;
2414                 } else if (!strcmp(arg, "%(blameargs)")) {
2415                         if (!argv_append_array(dst_argv, opt_blame_argv))
2416                                 break;
2417                         continue;
2419                 } else if (!strcmp(arg, "%(revargs)") ||
2420                            (first && !strcmp(arg, "%(commit)"))) {
2421                         if (!argv_append_array(dst_argv, opt_rev_argv))
2422                                 break;
2423                         continue;
2424                 }
2426                 while (arg) {
2427                         char *next = strstr(arg, "%(");
2428                         int len = next - arg;
2429                         const char *value;
2431                         if (!next || !replace) {
2432                                 len = strlen(arg);
2433                                 value = "";
2435                         } else {
2436                                 value = format_arg(next);
2438                                 if (!value) {
2439                                         return FALSE;
2440                                 }
2441                         }
2443                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2444                                 return FALSE;
2446                         arg = next && replace ? strchr(next, ')') + 1 : NULL;
2447                 }
2449                 if (!argv_append(dst_argv, buf))
2450                         break;
2451         }
2453         return src_argv[argc] == NULL;
2456 static bool
2457 restore_view_position(struct view *view)
2459         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2460                 return FALSE;
2462         /* Changing the view position cancels the restoring. */
2463         /* FIXME: Changing back to the first line is not detected. */
2464         if (view->offset != 0 || view->lineno != 0) {
2465                 view->p_restore = FALSE;
2466                 return FALSE;
2467         }
2469         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2470             view_is_displayed(view))
2471                 werase(view->win);
2473         view->yoffset = view->p_yoffset;
2474         view->p_restore = FALSE;
2476         return TRUE;
2479 static void
2480 end_update(struct view *view, bool force)
2482         if (!view->pipe)
2483                 return;
2484         while (!view->ops->read(view, NULL))
2485                 if (!force)
2486                         return;
2487         if (force)
2488                 io_kill(view->pipe);
2489         io_done(view->pipe);
2490         view->pipe = NULL;
2493 static void
2494 setup_update(struct view *view, const char *vid)
2496         reset_view(view);
2497         string_copy_rev(view->vid, vid);
2498         view->pipe = &view->io;
2499         view->start_time = time(NULL);
2502 static bool
2503 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2505         view->dir = dir;
2506         return format_argv(&view->argv, argv, replace, !view->prev);
2509 static bool
2510 start_update(struct view *view, const char **argv, const char *dir)
2512         if (view->pipe)
2513                 io_done(view->pipe);
2514         return prepare_io(view, dir, argv, FALSE) &&
2515                io_run(&view->io, IO_RD, dir, view->argv);
2518 static bool
2519 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2521         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2522         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2524         if (!reload && !strcmp(view->vid, view->id))
2525                 return TRUE;
2527         if (view->pipe)
2528                 end_update(view, TRUE);
2530         if (!refresh) {
2531                 if (!prepare_io(view, dir, argv, TRUE))
2532                         return FALSE;
2534                 /* Put the current ref_* value to the view title ref
2535                  * member. This is needed by the blob view. Most other
2536                  * views sets it automatically after loading because the
2537                  * first line is a commit line. */
2538                 string_copy_rev(view->ref, view->id);
2539         }
2541         if (view->argv && view->argv[0] &&
2542             !io_run(&view->io, IO_RD, view->dir, view->argv))
2543                 return FALSE;
2544         else if (view->argv && !strcmp(view->argv[0], opt_cdup) &&
2545                  !io_open(&view->io, "%s%s", opt_cdup, view->argv[1]))
2546                 return FALSE;
2548         setup_update(view, view->id);
2550         return TRUE;
2553 static bool
2554 view_open(struct view *view, enum open_flags flags)
2556         return begin_update(view, NULL, NULL, flags);
2559 static bool
2560 update_view(struct view *view)
2562         char out_buffer[BUFSIZ * 2];
2563         char *line;
2564         /* Clear the view and redraw everything since the tree sorting
2565          * might have rearranged things. */
2566         bool redraw = view->lines == 0;
2567         bool can_read = TRUE;
2569         if (!view->pipe)
2570                 return TRUE;
2572         if (!io_can_read(view->pipe, FALSE)) {
2573                 if (view->lines == 0 && view_is_displayed(view)) {
2574                         time_t secs = time(NULL) - view->start_time;
2576                         if (secs > 1 && secs > view->update_secs) {
2577                                 if (view->update_secs == 0)
2578                                         redraw_view(view);
2579                                 update_view_title(view);
2580                                 view->update_secs = secs;
2581                         }
2582                 }
2583                 return TRUE;
2584         }
2586         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2587                 if (opt_iconv_in != ICONV_NONE) {
2588                         ICONV_CONST char *inbuf = line;
2589                         size_t inlen = strlen(line) + 1;
2591                         char *outbuf = out_buffer;
2592                         size_t outlen = sizeof(out_buffer);
2594                         size_t ret;
2596                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2597                         if (ret != (size_t) -1)
2598                                 line = out_buffer;
2599                 }
2601                 if (!view->ops->read(view, line)) {
2602                         report("Allocation failure");
2603                         end_update(view, TRUE);
2604                         return FALSE;
2605                 }
2606         }
2608         {
2609                 unsigned long lines = view->lines;
2610                 int digits;
2612                 for (digits = 0; lines; digits++)
2613                         lines /= 10;
2615                 /* Keep the displayed view in sync with line number scaling. */
2616                 if (digits != view->digits) {
2617                         view->digits = digits;
2618                         if (opt_line_number || view->type == VIEW_BLAME)
2619                                 redraw = TRUE;
2620                 }
2621         }
2623         if (io_error(view->pipe)) {
2624                 report("Failed to read: %s", io_strerror(view->pipe));
2625                 end_update(view, TRUE);
2627         } else if (io_eof(view->pipe)) {
2628                 if (view_is_displayed(view))
2629                         report("");
2630                 end_update(view, FALSE);
2631         }
2633         if (restore_view_position(view))
2634                 redraw = TRUE;
2636         if (!view_is_displayed(view))
2637                 return TRUE;
2639         if (redraw)
2640                 redraw_view_from(view, 0);
2641         else
2642                 redraw_view_dirty(view);
2644         /* Update the title _after_ the redraw so that if the redraw picks up a
2645          * commit reference in view->ref it'll be available here. */
2646         update_view_title(view);
2647         return TRUE;
2650 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2652 static struct line *
2653 add_line_data(struct view *view, void *data, enum line_type type)
2655         struct line *line;
2657         if (!realloc_lines(&view->line, view->lines, 1))
2658                 return NULL;
2660         line = &view->line[view->lines++];
2661         memset(line, 0, sizeof(*line));
2662         line->type = type;
2663         line->data = data;
2664         line->dirty = 1;
2666         return line;
2669 static struct line *
2670 add_line_text(struct view *view, const char *text, enum line_type type)
2672         char *data = text ? strdup(text) : NULL;
2674         return data ? add_line_data(view, data, type) : NULL;
2677 static struct line *
2678 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2680         char buf[SIZEOF_STR];
2681         va_list args;
2683         va_start(args, fmt);
2684         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2685                 buf[0] = 0;
2686         va_end(args);
2688         return buf[0] ? add_line_text(view, buf, type) : NULL;
2691 /*
2692  * View opening
2693  */
2695 static void
2696 load_view(struct view *view, enum open_flags flags)
2698         if (view->pipe)
2699                 end_update(view, TRUE);
2700         if (!view->ops->open(view, flags)) {
2701                 report("Failed to load %s view", view->name);
2702                 return;
2703         }
2704         restore_view_position(view);
2706         if (view->pipe && view->lines == 0) {
2707                 /* Clear the old view and let the incremental updating refill
2708                  * the screen. */
2709                 werase(view->win);
2710                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2711                 report("");
2712         } else if (view_is_displayed(view)) {
2713                 redraw_view(view);
2714                 report("");
2715         }
2718 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2720 static void
2721 open_view(struct view *prev, enum request request, enum open_flags flags)
2723         bool split = !!(flags & OPEN_SPLIT);
2724         bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2725         struct view *view = VIEW(request);
2726         int nviews = displayed_views();
2728         assert(flags ^ OPEN_REFRESH);
2730         if (view == prev && nviews == 1 && !reload) {
2731                 report("Already in %s view", view->name);
2732                 return;
2733         }
2735         if (view->git_dir && !opt_git_dir[0]) {
2736                 report("The %s view is disabled in pager view", view->name);
2737                 return;
2738         }
2740         if (split) {
2741                 display[1] = view;
2742                 current_view = 1;
2743                 view->parent = prev;
2744                 resize_display();
2746                 if (prev->lineno - prev->offset >= prev->height) {
2747                         /* Take the title line into account. */
2748                         int lines = prev->lineno - prev->offset - prev->height + 1;
2750                         /* Scroll the view that was split if the current line is
2751                          * outside the new limited view. */
2752                         do_scroll_view(prev, lines);
2753                 }
2755                 if (view != prev && view_is_displayed(prev)) {
2756                         /* "Blur" the previous view. */
2757                         update_view_title(prev);
2758                 }
2759         } else {
2760                 maximize_view(view, FALSE);
2761         }
2763         /* No prev signals that this is the first loaded view. */
2764         if (prev && view != prev) {
2765                 view->prev = prev;
2766         }
2768         load_view(view, flags);
2771 static void
2772 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2774         enum request request = view - views + REQ_OFFSET + 1;
2776         if (view->pipe)
2777                 end_update(view, TRUE);
2778         if (!prepare_io(view, dir, argv, FALSE)) {
2779                 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2780         } else {
2781                 open_view(prev, request, flags | OPEN_PREPARED);
2782         }
2785 static void
2786 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2788         enum request request = view - views + REQ_OFFSET + 1;
2789         const char *file_argv[] = { opt_cdup, file , NULL };
2791         if (view->pipe)
2792                 end_update(view, TRUE);
2793         if (!argv_copy(&view->argv, file_argv)) {
2794                 report("Failed to load %s: out of memory", file);
2795         } else {
2796                 open_view(prev, request, flags | OPEN_PREPARED);
2797         }
2800 static void
2801 open_external_viewer(const char *argv[], const char *dir)
2803         def_prog_mode();           /* save current tty modes */
2804         endwin();                  /* restore original tty modes */
2805         io_run_fg(argv, dir);
2806         fprintf(stderr, "Press Enter to continue");
2807         getc(opt_tty);
2808         reset_prog_mode();
2809         redraw_display(TRUE);
2812 static void
2813 open_mergetool(const char *file)
2815         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2817         open_external_viewer(mergetool_argv, opt_cdup);
2820 static void
2821 open_editor(const char *file)
2823         const char *editor_argv[] = { "vi", file, NULL };
2824         const char *editor;
2826         editor = getenv("GIT_EDITOR");
2827         if (!editor && *opt_editor)
2828                 editor = opt_editor;
2829         if (!editor)
2830                 editor = getenv("VISUAL");
2831         if (!editor)
2832                 editor = getenv("EDITOR");
2833         if (!editor)
2834                 editor = "vi";
2836         editor_argv[0] = editor;
2837         open_external_viewer(editor_argv, opt_cdup);
2840 static void
2841 open_run_request(enum request request)
2843         struct run_request *req = get_run_request(request);
2844         const char **argv = NULL;
2846         if (!req) {
2847                 report("Unknown run request");
2848                 return;
2849         }
2851         if (format_argv(&argv, req->argv, TRUE, FALSE))
2852                 open_external_viewer(argv, NULL);
2853         if (argv)
2854                 argv_free(argv);
2855         free(argv);
2858 /*
2859  * User request switch noodle
2860  */
2862 static int
2863 view_driver(struct view *view, enum request request)
2865         int i;
2867         if (request == REQ_NONE)
2868                 return TRUE;
2870         if (request > REQ_NONE) {
2871                 open_run_request(request);
2872                 view_request(view, REQ_REFRESH);
2873                 return TRUE;
2874         }
2876         request = view_request(view, request);
2877         if (request == REQ_NONE)
2878                 return TRUE;
2880         switch (request) {
2881         case REQ_MOVE_UP:
2882         case REQ_MOVE_DOWN:
2883         case REQ_MOVE_PAGE_UP:
2884         case REQ_MOVE_PAGE_DOWN:
2885         case REQ_MOVE_FIRST_LINE:
2886         case REQ_MOVE_LAST_LINE:
2887                 move_view(view, request);
2888                 break;
2890         case REQ_SCROLL_FIRST_COL:
2891         case REQ_SCROLL_LEFT:
2892         case REQ_SCROLL_RIGHT:
2893         case REQ_SCROLL_LINE_DOWN:
2894         case REQ_SCROLL_LINE_UP:
2895         case REQ_SCROLL_PAGE_DOWN:
2896         case REQ_SCROLL_PAGE_UP:
2897                 scroll_view(view, request);
2898                 break;
2900         case REQ_VIEW_BLAME:
2901                 if (!opt_file[0]) {
2902                         report("No file chosen, press %s to open tree view",
2903                                get_key(view->keymap, REQ_VIEW_TREE));
2904                         break;
2905                 }
2906                 open_view(view, request, OPEN_DEFAULT);
2907                 break;
2909         case REQ_VIEW_BLOB:
2910                 if (!ref_blob[0]) {
2911                         report("No file chosen, press %s to open tree view",
2912                                get_key(view->keymap, REQ_VIEW_TREE));
2913                         break;
2914                 }
2915                 open_view(view, request, OPEN_DEFAULT);
2916                 break;
2918         case REQ_VIEW_PAGER:
2919                 if (view == NULL) {
2920                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2921                                 die("Failed to open stdin");
2922                         open_view(view, request, OPEN_PREPARED);
2923                         break;
2924                 }
2926                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2927                         report("No pager content, press %s to run command from prompt",
2928                                get_key(view->keymap, REQ_PROMPT));
2929                         break;
2930                 }
2931                 open_view(view, request, OPEN_DEFAULT);
2932                 break;
2934         case REQ_VIEW_STAGE:
2935                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2936                         report("No stage content, press %s to open the status view and choose file",
2937                                get_key(view->keymap, REQ_VIEW_STATUS));
2938                         break;
2939                 }
2940                 open_view(view, request, OPEN_DEFAULT);
2941                 break;
2943         case REQ_VIEW_STATUS:
2944                 if (opt_is_inside_work_tree == FALSE) {
2945                         report("The status view requires a working tree");
2946                         break;
2947                 }
2948                 open_view(view, request, OPEN_DEFAULT);
2949                 break;
2951         case REQ_VIEW_MAIN:
2952         case REQ_VIEW_DIFF:
2953         case REQ_VIEW_LOG:
2954         case REQ_VIEW_TREE:
2955         case REQ_VIEW_HELP:
2956         case REQ_VIEW_BRANCH:
2957                 open_view(view, request, OPEN_DEFAULT);
2958                 break;
2960         case REQ_NEXT:
2961         case REQ_PREVIOUS:
2962                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2964                 if (view->parent) {
2965                         int line;
2967                         view = view->parent;
2968                         line = view->lineno;
2969                         move_view(view, request);
2970                         if (view_is_displayed(view))
2971                                 update_view_title(view);
2972                         if (line != view->lineno)
2973                                 view_request(view, REQ_ENTER);
2974                 } else {
2975                         move_view(view, request);
2976                 }
2977                 break;
2979         case REQ_VIEW_NEXT:
2980         {
2981                 int nviews = displayed_views();
2982                 int next_view = (current_view + 1) % nviews;
2984                 if (next_view == current_view) {
2985                         report("Only one view is displayed");
2986                         break;
2987                 }
2989                 current_view = next_view;
2990                 /* Blur out the title of the previous view. */
2991                 update_view_title(view);
2992                 report("");
2993                 break;
2994         }
2995         case REQ_REFRESH:
2996                 report("Refreshing is not yet supported for the %s view", view->name);
2997                 break;
2999         case REQ_MAXIMIZE:
3000                 if (displayed_views() == 2)
3001                         maximize_view(view, TRUE);
3002                 break;
3004         case REQ_OPTIONS:
3005         case REQ_TOGGLE_LINENO:
3006         case REQ_TOGGLE_DATE:
3007         case REQ_TOGGLE_AUTHOR:
3008         case REQ_TOGGLE_GRAPHIC:
3009         case REQ_TOGGLE_REV_GRAPH:
3010         case REQ_TOGGLE_REFS:
3011                 toggle_option(request);
3012                 break;
3014         case REQ_TOGGLE_SORT_FIELD:
3015         case REQ_TOGGLE_SORT_ORDER:
3016                 report("Sorting is not yet supported for the %s view", view->name);
3017                 break;
3019         case REQ_SEARCH:
3020         case REQ_SEARCH_BACK:
3021                 search_view(view, request);
3022                 break;
3024         case REQ_FIND_NEXT:
3025         case REQ_FIND_PREV:
3026                 find_next(view, request);
3027                 break;
3029         case REQ_STOP_LOADING:
3030                 foreach_view(view, i) {
3031                         if (view->pipe)
3032                                 report("Stopped loading the %s view", view->name),
3033                         end_update(view, TRUE);
3034                 }
3035                 break;
3037         case REQ_SHOW_VERSION:
3038                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3039                 return TRUE;
3041         case REQ_SCREEN_REDRAW:
3042                 redraw_display(TRUE);
3043                 break;
3045         case REQ_EDIT:
3046                 report("Nothing to edit");
3047                 break;
3049         case REQ_ENTER:
3050                 report("Nothing to enter");
3051                 break;
3053         case REQ_VIEW_CLOSE:
3054                 /* XXX: Mark closed views by letting view->prev point to the
3055                  * view itself. Parents to closed view should never be
3056                  * followed. */
3057                 if (view->prev && view->prev != view) {
3058                         maximize_view(view->prev, TRUE);
3059                         view->prev = view;
3060                         break;
3061                 }
3062                 /* Fall-through */
3063         case REQ_QUIT:
3064                 return FALSE;
3066         default:
3067                 report("Unknown key, press %s for help",
3068                        get_key(view->keymap, REQ_VIEW_HELP));
3069                 return TRUE;
3070         }
3072         return TRUE;
3076 /*
3077  * View backend utilities
3078  */
3080 enum sort_field {
3081         ORDERBY_NAME,
3082         ORDERBY_DATE,
3083         ORDERBY_AUTHOR,
3084 };
3086 struct sort_state {
3087         const enum sort_field *fields;
3088         size_t size, current;
3089         bool reverse;
3090 };
3092 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3093 #define get_sort_field(state) ((state).fields[(state).current])
3094 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3096 static void
3097 sort_view(struct view *view, enum request request, struct sort_state *state,
3098           int (*compare)(const void *, const void *))
3100         switch (request) {
3101         case REQ_TOGGLE_SORT_FIELD:
3102                 state->current = (state->current + 1) % state->size;
3103                 break;
3105         case REQ_TOGGLE_SORT_ORDER:
3106                 state->reverse = !state->reverse;
3107                 break;
3108         default:
3109                 die("Not a sort request");
3110         }
3112         qsort(view->line, view->lines, sizeof(*view->line), compare);
3113         redraw_view(view);
3116 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3118 /* Small author cache to reduce memory consumption. It uses binary
3119  * search to lookup or find place to position new entries. No entries
3120  * are ever freed. */
3121 static const char *
3122 get_author(const char *name)
3124         static const char **authors;
3125         static size_t authors_size;
3126         int from = 0, to = authors_size - 1;
3128         while (from <= to) {
3129                 size_t pos = (to + from) / 2;
3130                 int cmp = strcmp(name, authors[pos]);
3132                 if (!cmp)
3133                         return authors[pos];
3135                 if (cmp < 0)
3136                         to = pos - 1;
3137                 else
3138                         from = pos + 1;
3139         }
3141         if (!realloc_authors(&authors, authors_size, 1))
3142                 return NULL;
3143         name = strdup(name);
3144         if (!name)
3145                 return NULL;
3147         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3148         authors[from] = name;
3149         authors_size++;
3151         return name;
3154 static void
3155 parse_timesec(struct time *time, const char *sec)
3157         time->sec = (time_t) atol(sec);
3160 static void
3161 parse_timezone(struct time *time, const char *zone)
3163         long tz;
3165         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3166         tz += ('0' - zone[2]) * 60 * 60;
3167         tz += ('0' - zone[3]) * 60 * 10;
3168         tz += ('0' - zone[4]) * 60;
3170         if (zone[0] == '-')
3171                 tz = -tz;
3173         time->tz = tz;
3174         time->sec -= tz;
3177 /* Parse author lines where the name may be empty:
3178  *      author  <email@address.tld> 1138474660 +0100
3179  */
3180 static void
3181 parse_author_line(char *ident, const char **author, struct time *time)
3183         char *nameend = strchr(ident, '<');
3184         char *emailend = strchr(ident, '>');
3186         if (nameend && emailend)
3187                 *nameend = *emailend = 0;
3188         ident = chomp_string(ident);
3189         if (!*ident) {
3190                 if (nameend)
3191                         ident = chomp_string(nameend + 1);
3192                 if (!*ident)
3193                         ident = "Unknown";
3194         }
3196         *author = get_author(ident);
3198         /* Parse epoch and timezone */
3199         if (emailend && emailend[1] == ' ') {
3200                 char *secs = emailend + 2;
3201                 char *zone = strchr(secs, ' ');
3203                 parse_timesec(time, secs);
3205                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3206                         parse_timezone(time, zone + 1);
3207         }
3210 /*
3211  * Pager backend
3212  */
3214 static bool
3215 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3217         if (opt_line_number && draw_lineno(view, lineno))
3218                 return TRUE;
3220         draw_text(view, line->type, line->data);
3221         return TRUE;
3224 static bool
3225 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3227         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3228         char ref[SIZEOF_STR];
3230         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3231                 return TRUE;
3233         /* This is the only fatal call, since it can "corrupt" the buffer. */
3234         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3235                 return FALSE;
3237         return TRUE;
3240 static void
3241 add_pager_refs(struct view *view, struct line *line)
3243         char buf[SIZEOF_STR];
3244         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3245         struct ref_list *list;
3246         size_t bufpos = 0, i;
3247         const char *sep = "Refs: ";
3248         bool is_tag = FALSE;
3250         assert(line->type == LINE_COMMIT);
3252         list = get_ref_list(commit_id);
3253         if (!list) {
3254                 if (view->type == VIEW_DIFF)
3255                         goto try_add_describe_ref;
3256                 return;
3257         }
3259         for (i = 0; i < list->size; i++) {
3260                 struct ref *ref = list->refs[i];
3261                 const char *fmt = ref->tag    ? "%s[%s]" :
3262                                   ref->remote ? "%s<%s>" : "%s%s";
3264                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3265                         return;
3266                 sep = ", ";
3267                 if (ref->tag)
3268                         is_tag = TRUE;
3269         }
3271         if (!is_tag && view->type == VIEW_DIFF) {
3272 try_add_describe_ref:
3273                 /* Add <tag>-g<commit_id> "fake" reference. */
3274                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3275                         return;
3276         }
3278         if (bufpos == 0)
3279                 return;
3281         add_line_text(view, buf, LINE_PP_REFS);
3284 static bool
3285 pager_read(struct view *view, char *data)
3287         struct line *line;
3289         if (!data)
3290                 return TRUE;
3292         line = add_line_text(view, data, get_line_type(data));
3293         if (!line)
3294                 return FALSE;
3296         if (line->type == LINE_COMMIT &&
3297             (view->type == VIEW_DIFF ||
3298              view->type == VIEW_LOG))
3299                 add_pager_refs(view, line);
3301         return TRUE;
3304 static enum request
3305 pager_request(struct view *view, enum request request, struct line *line)
3307         int split = 0;
3309         if (request != REQ_ENTER)
3310                 return request;
3312         if (line->type == LINE_COMMIT &&
3313            (view->type == VIEW_LOG ||
3314             view->type == VIEW_PAGER)) {
3315                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3316                 split = 1;
3317         }
3319         /* Always scroll the view even if it was split. That way
3320          * you can use Enter to scroll through the log view and
3321          * split open each commit diff. */
3322         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3324         /* FIXME: A minor workaround. Scrolling the view will call report("")
3325          * but if we are scrolling a non-current view this won't properly
3326          * update the view title. */
3327         if (split)
3328                 update_view_title(view);
3330         return REQ_NONE;
3333 static bool
3334 pager_grep(struct view *view, struct line *line)
3336         const char *text[] = { line->data, NULL };
3338         return grep_text(view, text);
3341 static void
3342 pager_select(struct view *view, struct line *line)
3344         if (line->type == LINE_COMMIT) {
3345                 char *text = (char *)line->data + STRING_SIZE("commit ");
3347                 if (view->type != VIEW_PAGER)
3348                         string_copy_rev(view->ref, text);
3349                 string_copy_rev(ref_commit, text);
3350         }
3353 static struct view_ops pager_ops = {
3354         "line",
3355         view_open,
3356         pager_read,
3357         pager_draw,
3358         pager_request,
3359         pager_grep,
3360         pager_select,
3361 };
3363 static bool
3364 log_open(struct view *view, enum open_flags flags)
3366         static const char *log_argv[] = {
3367                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3368         };
3370         return begin_update(view, NULL, log_argv, flags);
3373 static enum request
3374 log_request(struct view *view, enum request request, struct line *line)
3376         switch (request) {
3377         case REQ_REFRESH:
3378                 load_refs();
3379                 refresh_view(view);
3380                 return REQ_NONE;
3381         default:
3382                 return pager_request(view, request, line);
3383         }
3386 static struct view_ops log_ops = {
3387         "line",
3388         log_open,
3389         pager_read,
3390         pager_draw,
3391         log_request,
3392         pager_grep,
3393         pager_select,
3394 };
3396 static bool
3397 diff_open(struct view *view, enum open_flags flags)
3399         static const char *diff_argv[] = {
3400                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3401                         "--patch-with-stat", "--find-copies-harder", "-C",
3402                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3403         };
3405         return begin_update(view, NULL, diff_argv, flags);
3408 static bool
3409 diff_read(struct view *view, char *data)
3411         if (!data) {
3412                 /* Fall back to retry if no diff will be shown. */
3413                 if (view->lines == 0 && opt_file_argv) {
3414                         int pos = argv_size(view->argv)
3415                                 - argv_size(opt_file_argv) - 1;
3417                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3418                                 for (; view->argv[pos]; pos++) {
3419                                         free((void *) view->argv[pos]);
3420                                         view->argv[pos] = NULL;
3421                                 }
3423                                 if (view->pipe)
3424                                         io_done(view->pipe);
3425                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3426                                         return FALSE;
3427                         }
3428                 }
3429                 return TRUE;
3430         }
3432         return pager_read(view, data);
3435 static struct view_ops diff_ops = {
3436         "line",
3437         diff_open,
3438         diff_read,
3439         pager_draw,
3440         pager_request,
3441         pager_grep,
3442         pager_select,
3443 };
3445 /*
3446  * Help backend
3447  */
3449 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3451 static bool
3452 help_open_keymap_title(struct view *view, enum keymap keymap)
3454         struct line *line;
3456         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3457                                help_keymap_hidden[keymap] ? '+' : '-',
3458                                enum_name(keymap_table[keymap]));
3459         if (line)
3460                 line->other = keymap;
3462         return help_keymap_hidden[keymap];
3465 static void
3466 help_open_keymap(struct view *view, enum keymap keymap)
3468         const char *group = NULL;
3469         char buf[SIZEOF_STR];
3470         size_t bufpos;
3471         bool add_title = TRUE;
3472         int i;
3474         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3475                 const char *key = NULL;
3477                 if (req_info[i].request == REQ_NONE)
3478                         continue;
3480                 if (!req_info[i].request) {
3481                         group = req_info[i].help;
3482                         continue;
3483                 }
3485                 key = get_keys(keymap, req_info[i].request, TRUE);
3486                 if (!key || !*key)
3487                         continue;
3489                 if (add_title && help_open_keymap_title(view, keymap))
3490                         return;
3491                 add_title = FALSE;
3493                 if (group) {
3494                         add_line_text(view, group, LINE_HELP_GROUP);
3495                         group = NULL;
3496                 }
3498                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3499                                 enum_name(req_info[i]), req_info[i].help);
3500         }
3502         group = "External commands:";
3504         for (i = 0; i < run_requests; i++) {
3505                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3506                 const char *key;
3507                 int argc;
3509                 if (!req || req->keymap != keymap)
3510                         continue;
3512                 key = get_key_name(req->key);
3513                 if (!*key)
3514                         key = "(no key defined)";
3516                 if (add_title && help_open_keymap_title(view, keymap))
3517                         return;
3518                 if (group) {
3519                         add_line_text(view, group, LINE_HELP_GROUP);
3520                         group = NULL;
3521                 }
3523                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3524                         if (!string_format_from(buf, &bufpos, "%s%s",
3525                                                 argc ? " " : "", req->argv[argc]))
3526                                 return;
3528                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3529         }
3532 static bool
3533 help_open(struct view *view, enum open_flags flags)
3535         enum keymap keymap;
3537         reset_view(view);
3538         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3539         add_line_text(view, "", LINE_DEFAULT);
3541         for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3542                 help_open_keymap(view, keymap);
3544         return TRUE;
3547 static enum request
3548 help_request(struct view *view, enum request request, struct line *line)
3550         switch (request) {
3551         case REQ_ENTER:
3552                 if (line->type == LINE_HELP_KEYMAP) {
3553                         help_keymap_hidden[line->other] =
3554                                 !help_keymap_hidden[line->other];
3555                         refresh_view(view);
3556                 }
3558                 return REQ_NONE;
3559         default:
3560                 return pager_request(view, request, line);
3561         }
3564 static struct view_ops help_ops = {
3565         "line",
3566         help_open,
3567         NULL,
3568         pager_draw,
3569         help_request,
3570         pager_grep,
3571         pager_select,
3572 };
3575 /*
3576  * Tree backend
3577  */
3579 struct tree_stack_entry {
3580         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3581         unsigned long lineno;           /* Line number to restore */
3582         char *name;                     /* Position of name in opt_path */
3583 };
3585 /* The top of the path stack. */
3586 static struct tree_stack_entry *tree_stack = NULL;
3587 unsigned long tree_lineno = 0;
3589 static void
3590 pop_tree_stack_entry(void)
3592         struct tree_stack_entry *entry = tree_stack;
3594         tree_lineno = entry->lineno;
3595         entry->name[0] = 0;
3596         tree_stack = entry->prev;
3597         free(entry);
3600 static void
3601 push_tree_stack_entry(const char *name, unsigned long lineno)
3603         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3604         size_t pathlen = strlen(opt_path);
3606         if (!entry)
3607                 return;
3609         entry->prev = tree_stack;
3610         entry->name = opt_path + pathlen;
3611         tree_stack = entry;
3613         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3614                 pop_tree_stack_entry();
3615                 return;
3616         }
3618         /* Move the current line to the first tree entry. */
3619         tree_lineno = 1;
3620         entry->lineno = lineno;
3623 /* Parse output from git-ls-tree(1):
3624  *
3625  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3626  */
3628 #define SIZEOF_TREE_ATTR \
3629         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3631 #define SIZEOF_TREE_MODE \
3632         STRING_SIZE("100644 ")
3634 #define TREE_ID_OFFSET \
3635         STRING_SIZE("100644 blob ")
3637 struct tree_entry {
3638         char id[SIZEOF_REV];
3639         mode_t mode;
3640         struct time time;               /* Date from the author ident. */
3641         const char *author;             /* Author of the commit. */
3642         char name[1];
3643 };
3645 static const char *
3646 tree_path(const struct line *line)
3648         return ((struct tree_entry *) line->data)->name;
3651 static int
3652 tree_compare_entry(const struct line *line1, const struct line *line2)
3654         if (line1->type != line2->type)
3655                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3656         return strcmp(tree_path(line1), tree_path(line2));
3659 static const enum sort_field tree_sort_fields[] = {
3660         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3661 };
3662 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3664 static int
3665 tree_compare(const void *l1, const void *l2)
3667         const struct line *line1 = (const struct line *) l1;
3668         const struct line *line2 = (const struct line *) l2;
3669         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3670         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3672         if (line1->type == LINE_TREE_HEAD)
3673                 return -1;
3674         if (line2->type == LINE_TREE_HEAD)
3675                 return 1;
3677         switch (get_sort_field(tree_sort_state)) {
3678         case ORDERBY_DATE:
3679                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3681         case ORDERBY_AUTHOR:
3682                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3684         case ORDERBY_NAME:
3685         default:
3686                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3687         }
3691 static struct line *
3692 tree_entry(struct view *view, enum line_type type, const char *path,
3693            const char *mode, const char *id)
3695         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3696         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3698         if (!entry || !line) {
3699                 free(entry);
3700                 return NULL;
3701         }
3703         strncpy(entry->name, path, strlen(path));
3704         if (mode)
3705                 entry->mode = strtoul(mode, NULL, 8);
3706         if (id)
3707                 string_copy_rev(entry->id, id);
3709         return line;
3712 static bool
3713 tree_read_date(struct view *view, char *text, bool *read_date)
3715         static const char *author_name;
3716         static struct time author_time;
3718         if (!text && *read_date) {
3719                 *read_date = FALSE;
3720                 return TRUE;
3722         } else if (!text) {
3723                 char *path = *opt_path ? opt_path : ".";
3724                 /* Find next entry to process */
3725                 const char *log_file[] = {
3726                         "git", "log", "--no-color", "--pretty=raw",
3727                                 "--cc", "--raw", view->id, "--", path, NULL
3728                 };
3730                 if (!view->lines) {
3731                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3732                         report("Tree is empty");
3733                         return TRUE;
3734                 }
3736                 if (!start_update(view, log_file, opt_cdup)) {
3737                         report("Failed to load tree data");
3738                         return TRUE;
3739                 }
3741                 *read_date = TRUE;
3742                 return FALSE;
3744         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3745                 parse_author_line(text + STRING_SIZE("author "),
3746                                   &author_name, &author_time);
3748         } else if (*text == ':') {
3749                 char *pos;
3750                 size_t annotated = 1;
3751                 size_t i;
3753                 pos = strchr(text, '\t');
3754                 if (!pos)
3755                         return TRUE;
3756                 text = pos + 1;
3757                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3758                         text += strlen(opt_path);
3759                 pos = strchr(text, '/');
3760                 if (pos)
3761                         *pos = 0;
3763                 for (i = 1; i < view->lines; i++) {
3764                         struct line *line = &view->line[i];
3765                         struct tree_entry *entry = line->data;
3767                         annotated += !!entry->author;
3768                         if (entry->author || strcmp(entry->name, text))
3769                                 continue;
3771                         entry->author = author_name;
3772                         entry->time = author_time;
3773                         line->dirty = 1;
3774                         break;
3775                 }
3777                 if (annotated == view->lines)
3778                         io_kill(view->pipe);
3779         }
3780         return TRUE;
3783 static bool
3784 tree_read(struct view *view, char *text)
3786         static bool read_date = FALSE;
3787         struct tree_entry *data;
3788         struct line *entry, *line;
3789         enum line_type type;
3790         size_t textlen = text ? strlen(text) : 0;
3791         char *path = text + SIZEOF_TREE_ATTR;
3793         if (read_date || !text)
3794                 return tree_read_date(view, text, &read_date);
3796         if (textlen <= SIZEOF_TREE_ATTR)
3797                 return FALSE;
3798         if (view->lines == 0 &&
3799             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3800                 return FALSE;
3802         /* Strip the path part ... */
3803         if (*opt_path) {
3804                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3805                 size_t striplen = strlen(opt_path);
3807                 if (pathlen > striplen)
3808                         memmove(path, path + striplen,
3809                                 pathlen - striplen + 1);
3811                 /* Insert "link" to parent directory. */
3812                 if (view->lines == 1 &&
3813                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3814                         return FALSE;
3815         }
3817         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3818         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3819         if (!entry)
3820                 return FALSE;
3821         data = entry->data;
3823         /* Skip "Directory ..." and ".." line. */
3824         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3825                 if (tree_compare_entry(line, entry) <= 0)
3826                         continue;
3828                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3830                 line->data = data;
3831                 line->type = type;
3832                 for (; line <= entry; line++)
3833                         line->dirty = line->cleareol = 1;
3834                 return TRUE;
3835         }
3837         if (tree_lineno > view->lineno) {
3838                 view->lineno = tree_lineno;
3839                 tree_lineno = 0;
3840         }
3842         return TRUE;
3845 static bool
3846 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3848         struct tree_entry *entry = line->data;
3850         if (line->type == LINE_TREE_HEAD) {
3851                 if (draw_text(view, line->type, "Directory path /"))
3852                         return TRUE;
3853         } else {
3854                 if (draw_mode(view, entry->mode))
3855                         return TRUE;
3857                 if (draw_author(view, entry->author))
3858                         return TRUE;
3860                 if (draw_date(view, &entry->time))
3861                         return TRUE;
3862         }
3864         draw_text(view, line->type, entry->name);
3865         return TRUE;
3868 static void
3869 open_blob_editor(const char *id)
3871         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3872         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3873         int fd = mkstemp(file);
3875         if (fd == -1)
3876                 report("Failed to create temporary file");
3877         else if (!io_run_append(blob_argv, fd))
3878                 report("Failed to save blob data to file");
3879         else
3880                 open_editor(file);
3881         if (fd != -1)
3882                 unlink(file);
3885 static enum request
3886 tree_request(struct view *view, enum request request, struct line *line)
3888         enum open_flags flags;
3889         struct tree_entry *entry = line->data;
3891         switch (request) {
3892         case REQ_VIEW_BLAME:
3893                 if (line->type != LINE_TREE_FILE) {
3894                         report("Blame only supported for files");
3895                         return REQ_NONE;
3896                 }
3898                 string_copy(opt_ref, view->vid);
3899                 return request;
3901         case REQ_EDIT:
3902                 if (line->type != LINE_TREE_FILE) {
3903                         report("Edit only supported for files");
3904                 } else if (!is_head_commit(view->vid)) {
3905                         open_blob_editor(entry->id);
3906                 } else {
3907                         open_editor(opt_file);
3908                 }
3909                 return REQ_NONE;
3911         case REQ_TOGGLE_SORT_FIELD:
3912         case REQ_TOGGLE_SORT_ORDER:
3913                 sort_view(view, request, &tree_sort_state, tree_compare);
3914                 return REQ_NONE;
3916         case REQ_PARENT:
3917                 if (!*opt_path) {
3918                         /* quit view if at top of tree */
3919                         return REQ_VIEW_CLOSE;
3920                 }
3921                 /* fake 'cd  ..' */
3922                 line = &view->line[1];
3923                 break;
3925         case REQ_ENTER:
3926                 break;
3928         default:
3929                 return request;
3930         }
3932         /* Cleanup the stack if the tree view is at a different tree. */
3933         while (!*opt_path && tree_stack)
3934                 pop_tree_stack_entry();
3936         switch (line->type) {
3937         case LINE_TREE_DIR:
3938                 /* Depending on whether it is a subdirectory or parent link
3939                  * mangle the path buffer. */
3940                 if (line == &view->line[1] && *opt_path) {
3941                         pop_tree_stack_entry();
3943                 } else {
3944                         const char *basename = tree_path(line);
3946                         push_tree_stack_entry(basename, view->lineno);
3947                 }
3949                 /* Trees and subtrees share the same ID, so they are not not
3950                  * unique like blobs. */
3951                 flags = OPEN_RELOAD;
3952                 request = REQ_VIEW_TREE;
3953                 break;
3955         case LINE_TREE_FILE:
3956                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3957                 request = REQ_VIEW_BLOB;
3958                 break;
3960         default:
3961                 return REQ_NONE;
3962         }
3964         open_view(view, request, flags);
3965         if (request == REQ_VIEW_TREE)
3966                 view->lineno = tree_lineno;
3968         return REQ_NONE;
3971 static bool
3972 tree_grep(struct view *view, struct line *line)
3974         struct tree_entry *entry = line->data;
3975         const char *text[] = {
3976                 entry->name,
3977                 opt_author ? entry->author : "",
3978                 mkdate(&entry->time, opt_date),
3979                 NULL
3980         };
3982         return grep_text(view, text);
3985 static void
3986 tree_select(struct view *view, struct line *line)
3988         struct tree_entry *entry = line->data;
3990         if (line->type == LINE_TREE_FILE) {
3991                 string_copy_rev(ref_blob, entry->id);
3992                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3994         } else if (line->type != LINE_TREE_DIR) {
3995                 return;
3996         }
3998         string_copy_rev(view->ref, entry->id);
4001 static bool
4002 tree_open(struct view *view, enum open_flags flags)
4004         static const char *tree_argv[] = {
4005                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4006         };
4008         if (view->lines == 0 && opt_prefix[0]) {
4009                 char *pos = opt_prefix;
4011                 while (pos && *pos) {
4012                         char *end = strchr(pos, '/');
4014                         if (end)
4015                                 *end = 0;
4016                         push_tree_stack_entry(pos, 0);
4017                         pos = end;
4018                         if (end) {
4019                                 *end = '/';
4020                                 pos++;
4021                         }
4022                 }
4024         } else if (strcmp(view->vid, view->id)) {
4025                 opt_path[0] = 0;
4026         }
4028         return begin_update(view, opt_cdup, tree_argv, flags);
4031 static struct view_ops tree_ops = {
4032         "file",
4033         tree_open,
4034         tree_read,
4035         tree_draw,
4036         tree_request,
4037         tree_grep,
4038         tree_select,
4039 };
4041 static bool
4042 blob_open(struct view *view, enum open_flags flags)
4044         static const char *blob_argv[] = {
4045                 "git", "cat-file", "blob", "%(blob)", NULL
4046         };
4048         return begin_update(view, NULL, blob_argv, flags);
4051 static bool
4052 blob_read(struct view *view, char *line)
4054         if (!line)
4055                 return TRUE;
4056         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4059 static enum request
4060 blob_request(struct view *view, enum request request, struct line *line)
4062         switch (request) {
4063         case REQ_EDIT:
4064                 open_blob_editor(view->vid);
4065                 return REQ_NONE;
4066         default:
4067                 return pager_request(view, request, line);
4068         }
4071 static struct view_ops blob_ops = {
4072         "line",
4073         blob_open,
4074         blob_read,
4075         pager_draw,
4076         blob_request,
4077         pager_grep,
4078         pager_select,
4079 };
4081 /*
4082  * Blame backend
4083  *
4084  * Loading the blame view is a two phase job:
4085  *
4086  *  1. File content is read either using opt_file from the
4087  *     filesystem or using git-cat-file.
4088  *  2. Then blame information is incrementally added by
4089  *     reading output from git-blame.
4090  */
4092 struct blame_commit {
4093         char id[SIZEOF_REV];            /* SHA1 ID. */
4094         char title[128];                /* First line of the commit message. */
4095         const char *author;             /* Author of the commit. */
4096         struct time time;               /* Date from the author ident. */
4097         char filename[128];             /* Name of file. */
4098         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4099         char parent_filename[128];      /* Parent/previous name of file. */
4100 };
4102 struct blame {
4103         struct blame_commit *commit;
4104         unsigned long lineno;
4105         char text[1];
4106 };
4108 static bool
4109 blame_open(struct view *view, enum open_flags flags)
4111         char path[SIZEOF_STR];
4112         size_t i;
4114         if (!view->prev && *opt_prefix) {
4115                 string_copy(path, opt_file);
4116                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4117                         return FALSE;
4118         }
4120         if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4121                 const char *blame_cat_file_argv[] = {
4122                         "git", "cat-file", "blob", path, NULL
4123                 };
4125                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4126                     !start_update(view, blame_cat_file_argv, opt_cdup))
4127                         return FALSE;
4128         }
4130         /* First pass: remove multiple references to the same commit. */
4131         for (i = 0; i < view->lines; i++) {
4132                 struct blame *blame = view->line[i].data;
4134                 if (blame->commit && blame->commit->id[0])
4135                         blame->commit->id[0] = 0;
4136                 else
4137                         blame->commit = NULL;
4138         }
4140         /* Second pass: free existing references. */
4141         for (i = 0; i < view->lines; i++) {
4142                 struct blame *blame = view->line[i].data;
4144                 if (blame->commit)
4145                         free(blame->commit);
4146         }
4148         setup_update(view, opt_file);
4149         string_format(view->ref, "%s ...", opt_file);
4151         return TRUE;
4154 static struct blame_commit *
4155 get_blame_commit(struct view *view, const char *id)
4157         size_t i;
4159         for (i = 0; i < view->lines; i++) {
4160                 struct blame *blame = view->line[i].data;
4162                 if (!blame->commit)
4163                         continue;
4165                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4166                         return blame->commit;
4167         }
4169         {
4170                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4172                 if (commit)
4173                         string_ncopy(commit->id, id, SIZEOF_REV);
4174                 return commit;
4175         }
4178 static bool
4179 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4181         const char *pos = *posref;
4183         *posref = NULL;
4184         pos = strchr(pos + 1, ' ');
4185         if (!pos || !isdigit(pos[1]))
4186                 return FALSE;
4187         *number = atoi(pos + 1);
4188         if (*number < min || *number > max)
4189                 return FALSE;
4191         *posref = pos;
4192         return TRUE;
4195 static struct blame_commit *
4196 parse_blame_commit(struct view *view, const char *text, int *blamed)
4198         struct blame_commit *commit;
4199         struct blame *blame;
4200         const char *pos = text + SIZEOF_REV - 2;
4201         size_t orig_lineno = 0;
4202         size_t lineno;
4203         size_t group;
4205         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4206                 return NULL;
4208         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4209             !parse_number(&pos, &lineno, 1, view->lines) ||
4210             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4211                 return NULL;
4213         commit = get_blame_commit(view, text);
4214         if (!commit)
4215                 return NULL;
4217         *blamed += group;
4218         while (group--) {
4219                 struct line *line = &view->line[lineno + group - 1];
4221                 blame = line->data;
4222                 blame->commit = commit;
4223                 blame->lineno = orig_lineno + group - 1;
4224                 line->dirty = 1;
4225         }
4227         return commit;
4230 static bool
4231 blame_read_file(struct view *view, const char *line, bool *read_file)
4233         if (!line) {
4234                 const char *blame_argv[] = {
4235                         "git", "blame", "%(blameargs)", "--incremental",
4236                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4237                 };
4239                 if (view->lines == 0 && !view->prev)
4240                         die("No blame exist for %s", view->vid);
4242                 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4243                         report("Failed to load blame data");
4244                         return TRUE;
4245                 }
4247                 *read_file = FALSE;
4248                 return FALSE;
4250         } else {
4251                 size_t linelen = strlen(line);
4252                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4254                 if (!blame)
4255                         return FALSE;
4257                 blame->commit = NULL;
4258                 strncpy(blame->text, line, linelen);
4259                 blame->text[linelen] = 0;
4260                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4261         }
4264 static bool
4265 match_blame_header(const char *name, char **line)
4267         size_t namelen = strlen(name);
4268         bool matched = !strncmp(name, *line, namelen);
4270         if (matched)
4271                 *line += namelen;
4273         return matched;
4276 static bool
4277 blame_read(struct view *view, char *line)
4279         static struct blame_commit *commit = NULL;
4280         static int blamed = 0;
4281         static bool read_file = TRUE;
4283         if (read_file)
4284                 return blame_read_file(view, line, &read_file);
4286         if (!line) {
4287                 /* Reset all! */
4288                 commit = NULL;
4289                 blamed = 0;
4290                 read_file = TRUE;
4291                 string_format(view->ref, "%s", view->vid);
4292                 if (view_is_displayed(view)) {
4293                         update_view_title(view);
4294                         redraw_view_from(view, 0);
4295                 }
4296                 return TRUE;
4297         }
4299         if (!commit) {
4300                 commit = parse_blame_commit(view, line, &blamed);
4301                 string_format(view->ref, "%s %2d%%", view->vid,
4302                               view->lines ? blamed * 100 / view->lines : 0);
4304         } else if (match_blame_header("author ", &line)) {
4305                 commit->author = get_author(line);
4307         } else if (match_blame_header("author-time ", &line)) {
4308                 parse_timesec(&commit->time, line);
4310         } else if (match_blame_header("author-tz ", &line)) {
4311                 parse_timezone(&commit->time, line);
4313         } else if (match_blame_header("summary ", &line)) {
4314                 string_ncopy(commit->title, line, strlen(line));
4316         } else if (match_blame_header("previous ", &line)) {
4317                 if (strlen(line) <= SIZEOF_REV)
4318                         return FALSE;
4319                 string_copy_rev(commit->parent_id, line);
4320                 line += SIZEOF_REV;
4321                 string_ncopy(commit->parent_filename, line, strlen(line));
4323         } else if (match_blame_header("filename ", &line)) {
4324                 string_ncopy(commit->filename, line, strlen(line));
4325                 commit = NULL;
4326         }
4328         return TRUE;
4331 static bool
4332 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4334         struct blame *blame = line->data;
4335         struct time *time = NULL;
4336         const char *id = NULL, *author = NULL;
4338         if (blame->commit && *blame->commit->filename) {
4339                 id = blame->commit->id;
4340                 author = blame->commit->author;
4341                 time = &blame->commit->time;
4342         }
4344         if (draw_date(view, time))
4345                 return TRUE;
4347         if (draw_author(view, author))
4348                 return TRUE;
4350         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4351                 return TRUE;
4353         if (draw_lineno(view, lineno))
4354                 return TRUE;
4356         draw_text(view, LINE_DEFAULT, blame->text);
4357         return TRUE;
4360 static bool
4361 check_blame_commit(struct blame *blame, bool check_null_id)
4363         if (!blame->commit)
4364                 report("Commit data not loaded yet");
4365         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4366                 report("No commit exist for the selected line");
4367         else
4368                 return TRUE;
4369         return FALSE;
4372 static void
4373 setup_blame_parent_line(struct view *view, struct blame *blame)
4375         char from[SIZEOF_REF + SIZEOF_STR];
4376         char to[SIZEOF_REF + SIZEOF_STR];
4377         const char *diff_tree_argv[] = {
4378                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4379                         "-U0", from, to, "--", NULL
4380         };
4381         struct io io;
4382         int parent_lineno = -1;
4383         int blamed_lineno = -1;
4384         char *line;
4386         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4387             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4388             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4389                 return;
4391         while ((line = io_get(&io, '\n', TRUE))) {
4392                 if (*line == '@') {
4393                         char *pos = strchr(line, '+');
4395                         parent_lineno = atoi(line + 4);
4396                         if (pos)
4397                                 blamed_lineno = atoi(pos + 1);
4399                 } else if (*line == '+' && parent_lineno != -1) {
4400                         if (blame->lineno == blamed_lineno - 1 &&
4401                             !strcmp(blame->text, line + 1)) {
4402                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4403                                 break;
4404                         }
4405                         blamed_lineno++;
4406                 }
4407         }
4409         io_done(&io);
4412 static enum request
4413 blame_request(struct view *view, enum request request, struct line *line)
4415         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4416         struct blame *blame = line->data;
4418         switch (request) {
4419         case REQ_VIEW_BLAME:
4420                 if (check_blame_commit(blame, TRUE)) {
4421                         string_copy(opt_ref, blame->commit->id);
4422                         string_copy(opt_file, blame->commit->filename);
4423                         if (blame->lineno)
4424                                 view->lineno = blame->lineno;
4425                         refresh_view(view);
4426                 }
4427                 break;
4429         case REQ_PARENT:
4430                 if (!check_blame_commit(blame, TRUE))
4431                         break;
4432                 if (!*blame->commit->parent_id) {
4433                         report("The selected commit has no parents");
4434                 } else {
4435                         string_copy_rev(opt_ref, blame->commit->parent_id);
4436                         string_copy(opt_file, blame->commit->parent_filename);
4437                         setup_blame_parent_line(view, blame);
4438                         refresh_view(view);
4439                 }
4440                 break;
4442         case REQ_ENTER:
4443                 if (!check_blame_commit(blame, FALSE))
4444                         break;
4446                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4447                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4448                         break;
4450                 if (!strcmp(blame->commit->id, NULL_ID)) {
4451                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4452                         const char *diff_index_argv[] = {
4453                                 "git", "diff-index", "--root", "--patch-with-stat",
4454                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4455                         };
4457                         if (!*blame->commit->parent_id) {
4458                                 diff_index_argv[1] = "diff";
4459                                 diff_index_argv[2] = "--no-color";
4460                                 diff_index_argv[6] = "--";
4461                                 diff_index_argv[7] = "/dev/null";
4462                         }
4464                         open_argv(view, diff, diff_index_argv, NULL, flags);
4465                 } else {
4466                         open_view(view, REQ_VIEW_DIFF, flags);
4467                 }
4468                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4469                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4470                 break;
4472         default:
4473                 return request;
4474         }
4476         return REQ_NONE;
4479 static bool
4480 blame_grep(struct view *view, struct line *line)
4482         struct blame *blame = line->data;
4483         struct blame_commit *commit = blame->commit;
4484         const char *text[] = {
4485                 blame->text,
4486                 commit ? commit->title : "",
4487                 commit ? commit->id : "",
4488                 commit && opt_author ? commit->author : "",
4489                 commit ? mkdate(&commit->time, opt_date) : "",
4490                 NULL
4491         };
4493         return grep_text(view, text);
4496 static void
4497 blame_select(struct view *view, struct line *line)
4499         struct blame *blame = line->data;
4500         struct blame_commit *commit = blame->commit;
4502         if (!commit)
4503                 return;
4505         if (!strcmp(commit->id, NULL_ID))
4506                 string_ncopy(ref_commit, "HEAD", 4);
4507         else
4508                 string_copy_rev(ref_commit, commit->id);
4511 static struct view_ops blame_ops = {
4512         "line",
4513         blame_open,
4514         blame_read,
4515         blame_draw,
4516         blame_request,
4517         blame_grep,
4518         blame_select,
4519 };
4521 /*
4522  * Branch backend
4523  */
4525 struct branch {
4526         const char *author;             /* Author of the last commit. */
4527         struct time time;               /* Date of the last activity. */
4528         const struct ref *ref;          /* Name and commit ID information. */
4529 };
4531 static const struct ref branch_all;
4533 static const enum sort_field branch_sort_fields[] = {
4534         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4535 };
4536 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4538 static int
4539 branch_compare(const void *l1, const void *l2)
4541         const struct branch *branch1 = ((const struct line *) l1)->data;
4542         const struct branch *branch2 = ((const struct line *) l2)->data;
4544         switch (get_sort_field(branch_sort_state)) {
4545         case ORDERBY_DATE:
4546                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4548         case ORDERBY_AUTHOR:
4549                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4551         case ORDERBY_NAME:
4552         default:
4553                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4554         }
4557 static bool
4558 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4560         struct branch *branch = line->data;
4561         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4563         if (draw_date(view, &branch->time))
4564                 return TRUE;
4566         if (draw_author(view, branch->author))
4567                 return TRUE;
4569         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4570         return TRUE;
4573 static enum request
4574 branch_request(struct view *view, enum request request, struct line *line)
4576         struct branch *branch = line->data;
4578         switch (request) {
4579         case REQ_REFRESH:
4580                 load_refs();
4581                 refresh_view(view);
4582                 return REQ_NONE;
4584         case REQ_TOGGLE_SORT_FIELD:
4585         case REQ_TOGGLE_SORT_ORDER:
4586                 sort_view(view, request, &branch_sort_state, branch_compare);
4587                 return REQ_NONE;
4589         case REQ_ENTER:
4590         {
4591                 const struct ref *ref = branch->ref;
4592                 const char *all_branches_argv[] = {
4593                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4594                               "--topo-order",
4595                               ref == &branch_all ? "--all" : ref->name, NULL
4596                 };
4597                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4599                 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4600                 return REQ_NONE;
4601         }
4602         default:
4603                 return request;
4604         }
4607 static bool
4608 branch_read(struct view *view, char *line)
4610         static char id[SIZEOF_REV];
4611         struct branch *reference;
4612         size_t i;
4614         if (!line)
4615                 return TRUE;
4617         switch (get_line_type(line)) {
4618         case LINE_COMMIT:
4619                 string_copy_rev(id, line + STRING_SIZE("commit "));
4620                 return TRUE;
4622         case LINE_AUTHOR:
4623                 for (i = 0, reference = NULL; i < view->lines; i++) {
4624                         struct branch *branch = view->line[i].data;
4626                         if (strcmp(branch->ref->id, id))
4627                                 continue;
4629                         view->line[i].dirty = TRUE;
4630                         if (reference) {
4631                                 branch->author = reference->author;
4632                                 branch->time = reference->time;
4633                                 continue;
4634                         }
4636                         parse_author_line(line + STRING_SIZE("author "),
4637                                           &branch->author, &branch->time);
4638                         reference = branch;
4639                 }
4640                 return TRUE;
4642         default:
4643                 return TRUE;
4644         }
4648 static bool
4649 branch_open_visitor(void *data, const struct ref *ref)
4651         struct view *view = data;
4652         struct branch *branch;
4654         if (ref->tag || ref->ltag || ref->remote)
4655                 return TRUE;
4657         branch = calloc(1, sizeof(*branch));
4658         if (!branch)
4659                 return FALSE;
4661         branch->ref = ref;
4662         return !!add_line_data(view, branch, LINE_DEFAULT);
4665 static bool
4666 branch_open(struct view *view, enum open_flags flags)
4668         const char *branch_log[] = {
4669                 "git", "log", "--no-color", "--pretty=raw",
4670                         "--simplify-by-decoration", "--all", NULL
4671         };
4673         if (!start_update(view, branch_log, NULL)) {
4674                 report("Failed to load branch data");
4675                 return TRUE;
4676         }
4678         setup_update(view, view->id);
4679         branch_open_visitor(view, &branch_all);
4680         foreach_ref(branch_open_visitor, view);
4681         view->p_restore = TRUE;
4683         return TRUE;
4686 static bool
4687 branch_grep(struct view *view, struct line *line)
4689         struct branch *branch = line->data;
4690         const char *text[] = {
4691                 branch->ref->name,
4692                 branch->author,
4693                 NULL
4694         };
4696         return grep_text(view, text);
4699 static void
4700 branch_select(struct view *view, struct line *line)
4702         struct branch *branch = line->data;
4704         string_copy_rev(view->ref, branch->ref->id);
4705         string_copy_rev(ref_commit, branch->ref->id);
4706         string_copy_rev(ref_head, branch->ref->id);
4707         string_copy_rev(ref_branch, branch->ref->name);
4710 static struct view_ops branch_ops = {
4711         "branch",
4712         branch_open,
4713         branch_read,
4714         branch_draw,
4715         branch_request,
4716         branch_grep,
4717         branch_select,
4718 };
4720 /*
4721  * Status backend
4722  */
4724 struct status {
4725         char status;
4726         struct {
4727                 mode_t mode;
4728                 char rev[SIZEOF_REV];
4729                 char name[SIZEOF_STR];
4730         } old;
4731         struct {
4732                 mode_t mode;
4733                 char rev[SIZEOF_REV];
4734                 char name[SIZEOF_STR];
4735         } new;
4736 };
4738 static char status_onbranch[SIZEOF_STR];
4739 static struct status stage_status;
4740 static enum line_type stage_line_type;
4741 static size_t stage_chunks;
4742 static int *stage_chunk;
4744 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4746 /* This should work even for the "On branch" line. */
4747 static inline bool
4748 status_has_none(struct view *view, struct line *line)
4750         return line < view->line + view->lines && !line[1].data;
4753 /* Get fields from the diff line:
4754  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4755  */
4756 static inline bool
4757 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4759         const char *old_mode = buf +  1;
4760         const char *new_mode = buf +  8;
4761         const char *old_rev  = buf + 15;
4762         const char *new_rev  = buf + 56;
4763         const char *status   = buf + 97;
4765         if (bufsize < 98 ||
4766             old_mode[-1] != ':' ||
4767             new_mode[-1] != ' ' ||
4768             old_rev[-1]  != ' ' ||
4769             new_rev[-1]  != ' ' ||
4770             status[-1]   != ' ')
4771                 return FALSE;
4773         file->status = *status;
4775         string_copy_rev(file->old.rev, old_rev);
4776         string_copy_rev(file->new.rev, new_rev);
4778         file->old.mode = strtoul(old_mode, NULL, 8);
4779         file->new.mode = strtoul(new_mode, NULL, 8);
4781         file->old.name[0] = file->new.name[0] = 0;
4783         return TRUE;
4786 static bool
4787 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4789         struct status *unmerged = NULL;
4790         char *buf;
4791         struct io io;
4793         if (!io_run(&io, IO_RD, opt_cdup, argv))
4794                 return FALSE;
4796         add_line_data(view, NULL, type);
4798         while ((buf = io_get(&io, 0, TRUE))) {
4799                 struct status *file = unmerged;
4801                 if (!file) {
4802                         file = calloc(1, sizeof(*file));
4803                         if (!file || !add_line_data(view, file, type))
4804                                 goto error_out;
4805                 }
4807                 /* Parse diff info part. */
4808                 if (status) {
4809                         file->status = status;
4810                         if (status == 'A')
4811                                 string_copy(file->old.rev, NULL_ID);
4813                 } else if (!file->status || file == unmerged) {
4814                         if (!status_get_diff(file, buf, strlen(buf)))
4815                                 goto error_out;
4817                         buf = io_get(&io, 0, TRUE);
4818                         if (!buf)
4819                                 break;
4821                         /* Collapse all modified entries that follow an
4822                          * associated unmerged entry. */
4823                         if (unmerged == file) {
4824                                 unmerged->status = 'U';
4825                                 unmerged = NULL;
4826                         } else if (file->status == 'U') {
4827                                 unmerged = file;
4828                         }
4829                 }
4831                 /* Grab the old name for rename/copy. */
4832                 if (!*file->old.name &&
4833                     (file->status == 'R' || file->status == 'C')) {
4834                         string_ncopy(file->old.name, buf, strlen(buf));
4836                         buf = io_get(&io, 0, TRUE);
4837                         if (!buf)
4838                                 break;
4839                 }
4841                 /* git-ls-files just delivers a NUL separated list of
4842                  * file names similar to the second half of the
4843                  * git-diff-* output. */
4844                 string_ncopy(file->new.name, buf, strlen(buf));
4845                 if (!*file->old.name)
4846                         string_copy(file->old.name, file->new.name);
4847                 file = NULL;
4848         }
4850         if (io_error(&io)) {
4851 error_out:
4852                 io_done(&io);
4853                 return FALSE;
4854         }
4856         if (!view->line[view->lines - 1].data)
4857                 add_line_data(view, NULL, LINE_STAT_NONE);
4859         io_done(&io);
4860         return TRUE;
4863 /* Don't show unmerged entries in the staged section. */
4864 static const char *status_diff_index_argv[] = {
4865         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4866                              "--cached", "-M", "HEAD", NULL
4867 };
4869 static const char *status_diff_files_argv[] = {
4870         "git", "diff-files", "-z", NULL
4871 };
4873 static const char *status_list_other_argv[] = {
4874         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4875 };
4877 static const char *status_list_no_head_argv[] = {
4878         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4879 };
4881 static const char *update_index_argv[] = {
4882         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4883 };
4885 /* Restore the previous line number to stay in the context or select a
4886  * line with something that can be updated. */
4887 static void
4888 status_restore(struct view *view)
4890         if (view->p_lineno >= view->lines)
4891                 view->p_lineno = view->lines - 1;
4892         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4893                 view->p_lineno++;
4894         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4895                 view->p_lineno--;
4897         /* If the above fails, always skip the "On branch" line. */
4898         if (view->p_lineno < view->lines)
4899                 view->lineno = view->p_lineno;
4900         else
4901                 view->lineno = 1;
4903         if (view->lineno < view->offset)
4904                 view->offset = view->lineno;
4905         else if (view->offset + view->height <= view->lineno)
4906                 view->offset = view->lineno - view->height + 1;
4908         view->p_restore = FALSE;
4911 static void
4912 status_update_onbranch(void)
4914         static const char *paths[][2] = {
4915                 { "rebase-apply/rebasing",      "Rebasing" },
4916                 { "rebase-apply/applying",      "Applying mailbox" },
4917                 { "rebase-apply/",              "Rebasing mailbox" },
4918                 { "rebase-merge/interactive",   "Interactive rebase" },
4919                 { "rebase-merge/",              "Rebase merge" },
4920                 { "MERGE_HEAD",                 "Merging" },
4921                 { "BISECT_LOG",                 "Bisecting" },
4922                 { "HEAD",                       "On branch" },
4923         };
4924         char buf[SIZEOF_STR];
4925         struct stat stat;
4926         int i;
4928         if (is_initial_commit()) {
4929                 string_copy(status_onbranch, "Initial commit");
4930                 return;
4931         }
4933         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4934                 char *head = opt_head;
4936                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4937                     lstat(buf, &stat) < 0)
4938                         continue;
4940                 if (!*opt_head) {
4941                         struct io io;
4943                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4944                             io_read_buf(&io, buf, sizeof(buf))) {
4945                                 head = buf;
4946                                 if (!prefixcmp(head, "refs/heads/"))
4947                                         head += STRING_SIZE("refs/heads/");
4948                         }
4949                 }
4951                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4952                         string_copy(status_onbranch, opt_head);
4953                 return;
4954         }
4956         string_copy(status_onbranch, "Not currently on any branch");
4959 /* First parse staged info using git-diff-index(1), then parse unstaged
4960  * info using git-diff-files(1), and finally untracked files using
4961  * git-ls-files(1). */
4962 static bool
4963 status_open(struct view *view, enum open_flags flags)
4965         reset_view(view);
4967         add_line_data(view, NULL, LINE_STAT_HEAD);
4968         status_update_onbranch();
4970         io_run_bg(update_index_argv);
4972         if (is_initial_commit()) {
4973                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4974                         return FALSE;
4975         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4976                 return FALSE;
4977         }
4979         if (!opt_untracked_dirs_content)
4980                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4982         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4983             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4984                 return FALSE;
4986         /* Restore the exact position or use the specialized restore
4987          * mode? */
4988         if (!view->p_restore)
4989                 status_restore(view);
4990         return TRUE;
4993 static bool
4994 status_draw(struct view *view, struct line *line, unsigned int lineno)
4996         struct status *status = line->data;
4997         enum line_type type;
4998         const char *text;
5000         if (!status) {
5001                 switch (line->type) {
5002                 case LINE_STAT_STAGED:
5003                         type = LINE_STAT_SECTION;
5004                         text = "Changes to be committed:";
5005                         break;
5007                 case LINE_STAT_UNSTAGED:
5008                         type = LINE_STAT_SECTION;
5009                         text = "Changed but not updated:";
5010                         break;
5012                 case LINE_STAT_UNTRACKED:
5013                         type = LINE_STAT_SECTION;
5014                         text = "Untracked files:";
5015                         break;
5017                 case LINE_STAT_NONE:
5018                         type = LINE_DEFAULT;
5019                         text = "  (no files)";
5020                         break;
5022                 case LINE_STAT_HEAD:
5023                         type = LINE_STAT_HEAD;
5024                         text = status_onbranch;
5025                         break;
5027                 default:
5028                         return FALSE;
5029                 }
5030         } else {
5031                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5033                 buf[0] = status->status;
5034                 if (draw_text(view, line->type, buf))
5035                         return TRUE;
5036                 type = LINE_DEFAULT;
5037                 text = status->new.name;
5038         }
5040         draw_text(view, type, text);
5041         return TRUE;
5044 static enum request
5045 status_enter(struct view *view, struct line *line)
5047         struct status *status = line->data;
5048         const char *oldpath = status ? status->old.name : NULL;
5049         /* Diffs for unmerged entries are empty when passing the new
5050          * path, so leave it empty. */
5051         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5052         const char *info;
5053         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5054         struct view *stage = VIEW(REQ_VIEW_STAGE);
5056         if (line->type == LINE_STAT_NONE ||
5057             (!status && line[1].type == LINE_STAT_NONE)) {
5058                 report("No file to diff");
5059                 return REQ_NONE;
5060         }
5062         switch (line->type) {
5063         case LINE_STAT_STAGED:
5064                 if (is_initial_commit()) {
5065                         const char *no_head_diff_argv[] = {
5066                                 "git", "diff", "--no-color", "--patch-with-stat",
5067                                         "--", "/dev/null", newpath, NULL
5068                         };
5070                         open_argv(view, stage, no_head_diff_argv, opt_cdup, flags); 
5071                 } else {
5072                         const char *index_show_argv[] = {
5073                                 "git", "diff-index", "--root", "--patch-with-stat",
5074                                         "-C", "-M", "--cached", "HEAD", "--",
5075                                         oldpath, newpath, NULL
5076                         };
5078                         open_argv(view, stage, index_show_argv, opt_cdup, flags);
5079                 }
5081                 if (status)
5082                         info = "Staged changes to %s";
5083                 else
5084                         info = "Staged changes";
5085                 break;
5087         case LINE_STAT_UNSTAGED:
5088         {
5089                 const char *files_show_argv[] = {
5090                         "git", "diff-files", "--root", "--patch-with-stat",
5091                                 "-C", "-M", "--", oldpath, newpath, NULL
5092                 };
5094                 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5095                 if (status)
5096                         info = "Unstaged changes to %s";
5097                 else
5098                         info = "Unstaged changes";
5099                 break;
5100         }
5101         case LINE_STAT_UNTRACKED:
5102                 if (!newpath) {
5103                         report("No file to show");
5104                         return REQ_NONE;
5105                 }
5107                 if (!suffixcmp(status->new.name, -1, "/")) {
5108                         report("Cannot display a directory");
5109                         return REQ_NONE;
5110                 }
5112                 open_file(view, stage, newpath, flags);
5113                 info = "Untracked file %s";
5114                 break;
5116         case LINE_STAT_HEAD:
5117                 return REQ_NONE;
5119         default:
5120                 die("line type %d not handled in switch", line->type);
5121         }
5123         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5124                 if (status) {
5125                         stage_status = *status;
5126                 } else {
5127                         memset(&stage_status, 0, sizeof(stage_status));
5128                 }
5130                 stage_line_type = line->type;
5131                 stage_chunks = 0;
5132                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5133         }
5135         return REQ_NONE;
5138 static bool
5139 status_exists(struct status *status, enum line_type type)
5141         struct view *view = VIEW(REQ_VIEW_STATUS);
5142         unsigned long lineno;
5144         for (lineno = 0; lineno < view->lines; lineno++) {
5145                 struct line *line = &view->line[lineno];
5146                 struct status *pos = line->data;
5148                 if (line->type != type)
5149                         continue;
5150                 if (!pos && (!status || !status->status) && line[1].data) {
5151                         select_view_line(view, lineno);
5152                         return TRUE;
5153                 }
5154                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5155                         select_view_line(view, lineno);
5156                         return TRUE;
5157                 }
5158         }
5160         return FALSE;
5164 static bool
5165 status_update_prepare(struct io *io, enum line_type type)
5167         const char *staged_argv[] = {
5168                 "git", "update-index", "-z", "--index-info", NULL
5169         };
5170         const char *others_argv[] = {
5171                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5172         };
5174         switch (type) {
5175         case LINE_STAT_STAGED:
5176                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5178         case LINE_STAT_UNSTAGED:
5179         case LINE_STAT_UNTRACKED:
5180                 return io_run(io, IO_WR, opt_cdup, others_argv);
5182         default:
5183                 die("line type %d not handled in switch", type);
5184                 return FALSE;
5185         }
5188 static bool
5189 status_update_write(struct io *io, struct status *status, enum line_type type)
5191         char buf[SIZEOF_STR];
5192         size_t bufsize = 0;
5194         switch (type) {
5195         case LINE_STAT_STAGED:
5196                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5197                                         status->old.mode,
5198                                         status->old.rev,
5199                                         status->old.name, 0))
5200                         return FALSE;
5201                 break;
5203         case LINE_STAT_UNSTAGED:
5204         case LINE_STAT_UNTRACKED:
5205                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5206                         return FALSE;
5207                 break;
5209         default:
5210                 die("line type %d not handled in switch", type);
5211         }
5213         return io_write(io, buf, bufsize);
5216 static bool
5217 status_update_file(struct status *status, enum line_type type)
5219         struct io io;
5220         bool result;
5222         if (!status_update_prepare(&io, type))
5223                 return FALSE;
5225         result = status_update_write(&io, status, type);
5226         return io_done(&io) && result;
5229 static bool
5230 status_update_files(struct view *view, struct line *line)
5232         char buf[sizeof(view->ref)];
5233         struct io io;
5234         bool result = TRUE;
5235         struct line *pos = view->line + view->lines;
5236         int files = 0;
5237         int file, done;
5238         int cursor_y = -1, cursor_x = -1;
5240         if (!status_update_prepare(&io, line->type))
5241                 return FALSE;
5243         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5244                 files++;
5246         string_copy(buf, view->ref);
5247         getsyx(cursor_y, cursor_x);
5248         for (file = 0, done = 5; result && file < files; line++, file++) {
5249                 int almost_done = file * 100 / files;
5251                 if (almost_done > done) {
5252                         done = almost_done;
5253                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5254                                       file, files, done);
5255                         update_view_title(view);
5256                         setsyx(cursor_y, cursor_x);
5257                         doupdate();
5258                 }
5259                 result = status_update_write(&io, line->data, line->type);
5260         }
5261         string_copy(view->ref, buf);
5263         return io_done(&io) && result;
5266 static bool
5267 status_update(struct view *view)
5269         struct line *line = &view->line[view->lineno];
5271         assert(view->lines);
5273         if (!line->data) {
5274                 /* This should work even for the "On branch" line. */
5275                 if (line < view->line + view->lines && !line[1].data) {
5276                         report("Nothing to update");
5277                         return FALSE;
5278                 }
5280                 if (!status_update_files(view, line + 1)) {
5281                         report("Failed to update file status");
5282                         return FALSE;
5283                 }
5285         } else if (!status_update_file(line->data, line->type)) {
5286                 report("Failed to update file status");
5287                 return FALSE;
5288         }
5290         return TRUE;
5293 static bool
5294 status_revert(struct status *status, enum line_type type, bool has_none)
5296         if (!status || type != LINE_STAT_UNSTAGED) {
5297                 if (type == LINE_STAT_STAGED) {
5298                         report("Cannot revert changes to staged files");
5299                 } else if (type == LINE_STAT_UNTRACKED) {
5300                         report("Cannot revert changes to untracked files");
5301                 } else if (has_none) {
5302                         report("Nothing to revert");
5303                 } else {
5304                         report("Cannot revert changes to multiple files");
5305                 }
5307         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5308                 char mode[10] = "100644";
5309                 const char *reset_argv[] = {
5310                         "git", "update-index", "--cacheinfo", mode,
5311                                 status->old.rev, status->old.name, NULL
5312                 };
5313                 const char *checkout_argv[] = {
5314                         "git", "checkout", "--", status->old.name, NULL
5315                 };
5317                 if (status->status == 'U') {
5318                         string_format(mode, "%5o", status->old.mode);
5320                         if (status->old.mode == 0 && status->new.mode == 0) {
5321                                 reset_argv[2] = "--force-remove";
5322                                 reset_argv[3] = status->old.name;
5323                                 reset_argv[4] = NULL;
5324                         }
5326                         if (!io_run_fg(reset_argv, opt_cdup))
5327                                 return FALSE;
5328                         if (status->old.mode == 0 && status->new.mode == 0)
5329                                 return TRUE;
5330                 }
5332                 return io_run_fg(checkout_argv, opt_cdup);
5333         }
5335         return FALSE;
5338 static enum request
5339 status_request(struct view *view, enum request request, struct line *line)
5341         struct status *status = line->data;
5343         switch (request) {
5344         case REQ_STATUS_UPDATE:
5345                 if (!status_update(view))
5346                         return REQ_NONE;
5347                 break;
5349         case REQ_STATUS_REVERT:
5350                 if (!status_revert(status, line->type, status_has_none(view, line)))
5351                         return REQ_NONE;
5352                 break;
5354         case REQ_STATUS_MERGE:
5355                 if (!status || status->status != 'U') {
5356                         report("Merging only possible for files with unmerged status ('U').");
5357                         return REQ_NONE;
5358                 }
5359                 open_mergetool(status->new.name);
5360                 break;
5362         case REQ_EDIT:
5363                 if (!status)
5364                         return request;
5365                 if (status->status == 'D') {
5366                         report("File has been deleted.");
5367                         return REQ_NONE;
5368                 }
5370                 open_editor(status->new.name);
5371                 break;
5373         case REQ_VIEW_BLAME:
5374                 if (status)
5375                         opt_ref[0] = 0;
5376                 return request;
5378         case REQ_ENTER:
5379                 /* After returning the status view has been split to
5380                  * show the stage view. No further reloading is
5381                  * necessary. */
5382                 return status_enter(view, line);
5384         case REQ_REFRESH:
5385                 /* Simply reload the view. */
5386                 break;
5388         default:
5389                 return request;
5390         }
5392         refresh_view(view);
5394         return REQ_NONE;
5397 static void
5398 status_select(struct view *view, struct line *line)
5400         struct status *status = line->data;
5401         char file[SIZEOF_STR] = "all files";
5402         const char *text;
5403         const char *key;
5405         if (status && !string_format(file, "'%s'", status->new.name))
5406                 return;
5408         if (!status && line[1].type == LINE_STAT_NONE)
5409                 line++;
5411         switch (line->type) {
5412         case LINE_STAT_STAGED:
5413                 text = "Press %s to unstage %s for commit";
5414                 break;
5416         case LINE_STAT_UNSTAGED:
5417                 text = "Press %s to stage %s for commit";
5418                 break;
5420         case LINE_STAT_UNTRACKED:
5421                 text = "Press %s to stage %s for addition";
5422                 break;
5424         case LINE_STAT_HEAD:
5425         case LINE_STAT_NONE:
5426                 text = "Nothing to update";
5427                 break;
5429         default:
5430                 die("line type %d not handled in switch", line->type);
5431         }
5433         if (status && status->status == 'U') {
5434                 text = "Press %s to resolve conflict in %s";
5435                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5437         } else {
5438                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5439         }
5441         string_format(view->ref, text, key, file);
5442         if (status)
5443                 string_copy(opt_file, status->new.name);
5446 static bool
5447 status_grep(struct view *view, struct line *line)
5449         struct status *status = line->data;
5451         if (status) {
5452                 const char buf[2] = { status->status, 0 };
5453                 const char *text[] = { status->new.name, buf, NULL };
5455                 return grep_text(view, text);
5456         }
5458         return FALSE;
5461 static struct view_ops status_ops = {
5462         "file",
5463         status_open,
5464         NULL,
5465         status_draw,
5466         status_request,
5467         status_grep,
5468         status_select,
5469 };
5472 static bool
5473 stage_diff_write(struct io *io, struct line *line, struct line *end)
5475         while (line < end) {
5476                 if (!io_write(io, line->data, strlen(line->data)) ||
5477                     !io_write(io, "\n", 1))
5478                         return FALSE;
5479                 line++;
5480                 if (line->type == LINE_DIFF_CHUNK ||
5481                     line->type == LINE_DIFF_HEADER)
5482                         break;
5483         }
5485         return TRUE;
5488 static struct line *
5489 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5491         for (; view->line < line; line--)
5492                 if (line->type == type)
5493                         return line;
5495         return NULL;
5498 static bool
5499 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5501         const char *apply_argv[SIZEOF_ARG] = {
5502                 "git", "apply", "--whitespace=nowarn", NULL
5503         };
5504         struct line *diff_hdr;
5505         struct io io;
5506         int argc = 3;
5508         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5509         if (!diff_hdr)
5510                 return FALSE;
5512         if (!revert)
5513                 apply_argv[argc++] = "--cached";
5514         if (revert || stage_line_type == LINE_STAT_STAGED)
5515                 apply_argv[argc++] = "-R";
5516         apply_argv[argc++] = "-";
5517         apply_argv[argc++] = NULL;
5518         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5519                 return FALSE;
5521         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5522             !stage_diff_write(&io, chunk, view->line + view->lines))
5523                 chunk = NULL;
5525         io_done(&io);
5526         io_run_bg(update_index_argv);
5528         return chunk ? TRUE : FALSE;
5531 static bool
5532 stage_update(struct view *view, struct line *line)
5534         struct line *chunk = NULL;
5536         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5537                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5539         if (chunk) {
5540                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5541                         report("Failed to apply chunk");
5542                         return FALSE;
5543                 }
5545         } else if (!stage_status.status) {
5546                 view = VIEW(REQ_VIEW_STATUS);
5548                 for (line = view->line; line < view->line + view->lines; line++)
5549                         if (line->type == stage_line_type)
5550                                 break;
5552                 if (!status_update_files(view, line + 1)) {
5553                         report("Failed to update files");
5554                         return FALSE;
5555                 }
5557         } else if (!status_update_file(&stage_status, stage_line_type)) {
5558                 report("Failed to update file");
5559                 return FALSE;
5560         }
5562         return TRUE;
5565 static bool
5566 stage_revert(struct view *view, struct line *line)
5568         struct line *chunk = NULL;
5570         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5571                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5573         if (chunk) {
5574                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5575                         return FALSE;
5577                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5578                         report("Failed to revert chunk");
5579                         return FALSE;
5580                 }
5581                 return TRUE;
5583         } else {
5584                 return status_revert(stage_status.status ? &stage_status : NULL,
5585                                      stage_line_type, FALSE);
5586         }
5590 static void
5591 stage_next(struct view *view, struct line *line)
5593         int i;
5595         if (!stage_chunks) {
5596                 for (line = view->line; line < view->line + view->lines; line++) {
5597                         if (line->type != LINE_DIFF_CHUNK)
5598                                 continue;
5600                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5601                                 report("Allocation failure");
5602                                 return;
5603                         }
5605                         stage_chunk[stage_chunks++] = line - view->line;
5606                 }
5607         }
5609         for (i = 0; i < stage_chunks; i++) {
5610                 if (stage_chunk[i] > view->lineno) {
5611                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5612                         report("Chunk %d of %d", i + 1, stage_chunks);
5613                         return;
5614                 }
5615         }
5617         report("No next chunk found");
5620 static enum request
5621 stage_request(struct view *view, enum request request, struct line *line)
5623         switch (request) {
5624         case REQ_STATUS_UPDATE:
5625                 if (!stage_update(view, line))
5626                         return REQ_NONE;
5627                 break;
5629         case REQ_STATUS_REVERT:
5630                 if (!stage_revert(view, line))
5631                         return REQ_NONE;
5632                 break;
5634         case REQ_STAGE_NEXT:
5635                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5636                         report("File is untracked; press %s to add",
5637                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5638                         return REQ_NONE;
5639                 }
5640                 stage_next(view, line);
5641                 return REQ_NONE;
5643         case REQ_EDIT:
5644                 if (!stage_status.new.name[0])
5645                         return request;
5646                 if (stage_status.status == 'D') {
5647                         report("File has been deleted.");
5648                         return REQ_NONE;
5649                 }
5651                 open_editor(stage_status.new.name);
5652                 break;
5654         case REQ_REFRESH:
5655                 /* Reload everything ... */
5656                 break;
5658         case REQ_VIEW_BLAME:
5659                 if (stage_status.new.name[0]) {
5660                         string_copy(opt_file, stage_status.new.name);
5661                         opt_ref[0] = 0;
5662                 }
5663                 return request;
5665         case REQ_ENTER:
5666                 return pager_request(view, request, line);
5668         default:
5669                 return request;
5670         }
5672         refresh_view(view->parent);
5674         /* Check whether the staged entry still exists, and close the
5675          * stage view if it doesn't. */
5676         if (!status_exists(&stage_status, stage_line_type)) {
5677                 status_restore(VIEW(REQ_VIEW_STATUS));
5678                 return REQ_VIEW_CLOSE;
5679         }
5681         refresh_view(view);
5683         return REQ_NONE;
5686 static struct view_ops stage_ops = {
5687         "line",
5688         view_open,
5689         pager_read,
5690         pager_draw,
5691         stage_request,
5692         pager_grep,
5693         pager_select,
5694 };
5697 /*
5698  * Revision graph
5699  */
5701 static const enum line_type graph_colors[] = {
5702         LINE_GRAPH_LINE_0,
5703         LINE_GRAPH_LINE_1,
5704         LINE_GRAPH_LINE_2,
5705         LINE_GRAPH_LINE_3,
5706         LINE_GRAPH_LINE_4,
5707         LINE_GRAPH_LINE_5,
5708         LINE_GRAPH_LINE_6,
5709 };
5711 static enum line_type get_graph_color(struct graph_symbol *symbol)
5713         if (symbol->commit)
5714                 return LINE_GRAPH_COMMIT;
5715         assert(symbol->color < ARRAY_SIZE(graph_colors));
5716         return graph_colors[symbol->color];
5719 static bool
5720 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5722         const char *chars = graph_symbol_to_utf8(symbol);
5724         return draw_text(view, color, chars + !!first); 
5727 static bool
5728 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5730         const char *chars = graph_symbol_to_ascii(symbol);
5732         return draw_text(view, color, chars + !!first); 
5735 static bool
5736 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5738         const chtype *chars = graph_symbol_to_chtype(symbol);
5740         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5743 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5745 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5747         static const draw_graph_fn fns[] = {
5748                 draw_graph_ascii,
5749                 draw_graph_chtype,
5750                 draw_graph_utf8
5751         };
5752         draw_graph_fn fn = fns[opt_line_graphics];
5753         int i;
5755         for (i = 0; i < canvas->size; i++) {
5756                 struct graph_symbol *symbol = &canvas->symbols[i];
5757                 enum line_type color = get_graph_color(symbol);
5759                 if (fn(view, symbol, color, i == 0))
5760                         return TRUE;
5761         }
5763         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5766 /*
5767  * Main view backend
5768  */
5770 struct commit {
5771         char id[SIZEOF_REV];            /* SHA1 ID. */
5772         char title[128];                /* First line of the commit message. */
5773         const char *author;             /* Author of the commit. */
5774         struct time time;               /* Date from the author ident. */
5775         struct ref_list *refs;          /* Repository references. */
5776         struct graph_canvas graph;      /* Ancestry chain graphics. */
5777 };
5779 static bool
5780 main_open(struct view *view, enum open_flags flags)
5782         static const char *main_argv[] = {
5783                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5784                         "--topo-order", "%(diffargs)", "%(revargs)",
5785                         "--", "%(fileargs)", NULL
5786         };
5788         return begin_update(view, NULL, main_argv, flags);
5791 static bool
5792 main_draw(struct view *view, struct line *line, unsigned int lineno)
5794         struct commit *commit = line->data;
5796         if (!commit->author)
5797                 return FALSE;
5799         if (draw_date(view, &commit->time))
5800                 return TRUE;
5802         if (draw_author(view, commit->author))
5803                 return TRUE;
5805         if (opt_rev_graph && draw_graph(view, &commit->graph))
5806                 return TRUE;
5808         if (opt_show_refs && commit->refs) {
5809                 size_t i;
5811                 for (i = 0; i < commit->refs->size; i++) {
5812                         struct ref *ref = commit->refs->refs[i];
5813                         enum line_type type;
5815                         if (ref->head)
5816                                 type = LINE_MAIN_HEAD;
5817                         else if (ref->ltag)
5818                                 type = LINE_MAIN_LOCAL_TAG;
5819                         else if (ref->tag)
5820                                 type = LINE_MAIN_TAG;
5821                         else if (ref->tracked)
5822                                 type = LINE_MAIN_TRACKED;
5823                         else if (ref->remote)
5824                                 type = LINE_MAIN_REMOTE;
5825                         else
5826                                 type = LINE_MAIN_REF;
5828                         if (draw_text(view, type, "[") ||
5829                             draw_text(view, type, ref->name) ||
5830                             draw_text(view, type, "]"))
5831                                 return TRUE;
5833                         if (draw_text(view, LINE_DEFAULT, " "))
5834                                 return TRUE;
5835                 }
5836         }
5838         draw_text(view, LINE_DEFAULT, commit->title);
5839         return TRUE;
5842 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5843 static bool
5844 main_read(struct view *view, char *line)
5846         static struct graph graph;
5847         enum line_type type;
5848         struct commit *commit;
5850         if (!line) {
5851                 if (!view->lines && !view->prev)
5852                         die("No revisions match the given arguments.");
5853                 if (view->lines > 0) {
5854                         commit = view->line[view->lines - 1].data;
5855                         view->line[view->lines - 1].dirty = 1;
5856                         if (!commit->author) {
5857                                 view->lines--;
5858                                 free(commit);
5859                         }
5860                 }
5862                 done_graph(&graph);
5863                 return TRUE;
5864         }
5866         type = get_line_type(line);
5867         if (type == LINE_COMMIT) {
5868                 bool is_boundary;
5870                 commit = calloc(1, sizeof(struct commit));
5871                 if (!commit)
5872                         return FALSE;
5874                 line += STRING_SIZE("commit ");
5875                 is_boundary = *line == '-';
5876                 if (is_boundary)
5877                         line++;
5879                 string_copy_rev(commit->id, line);
5880                 commit->refs = get_ref_list(commit->id);
5881                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5882                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5883                 return TRUE;
5884         }
5886         if (!view->lines)
5887                 return TRUE;
5888         commit = view->line[view->lines - 1].data;
5890         switch (type) {
5891         case LINE_PARENT:
5892                 if (!graph.has_parents)
5893                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5894                 break;
5896         case LINE_AUTHOR:
5897                 parse_author_line(line + STRING_SIZE("author "),
5898                                   &commit->author, &commit->time);
5899                 graph_render_parents(&graph);
5900                 break;
5902         default:
5903                 /* Fill in the commit title if it has not already been set. */
5904                 if (commit->title[0])
5905                         break;
5907                 /* Require titles to start with a non-space character at the
5908                  * offset used by git log. */
5909                 if (strncmp(line, "    ", 4))
5910                         break;
5911                 line += 4;
5912                 /* Well, if the title starts with a whitespace character,
5913                  * try to be forgiving.  Otherwise we end up with no title. */
5914                 while (isspace(*line))
5915                         line++;
5916                 if (*line == '\0')
5917                         break;
5918                 /* FIXME: More graceful handling of titles; append "..." to
5919                  * shortened titles, etc. */
5921                 string_expand(commit->title, sizeof(commit->title), line, 1);
5922                 view->line[view->lines - 1].dirty = 1;
5923         }
5925         return TRUE;
5928 static enum request
5929 main_request(struct view *view, enum request request, struct line *line)
5931         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5933         switch (request) {
5934         case REQ_ENTER:
5935                 if (view_is_displayed(view) && display[0] != view)
5936                         maximize_view(view, TRUE);
5937                 open_view(view, REQ_VIEW_DIFF, flags);
5938                 break;
5939         case REQ_REFRESH:
5940                 load_refs();
5941                 refresh_view(view);
5942                 break;
5943         default:
5944                 return request;
5945         }
5947         return REQ_NONE;
5950 static bool
5951 grep_refs(struct ref_list *list, regex_t *regex)
5953         regmatch_t pmatch;
5954         size_t i;
5956         if (!opt_show_refs || !list)
5957                 return FALSE;
5959         for (i = 0; i < list->size; i++) {
5960                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5961                         return TRUE;
5962         }
5964         return FALSE;
5967 static bool
5968 main_grep(struct view *view, struct line *line)
5970         struct commit *commit = line->data;
5971         const char *text[] = {
5972                 commit->title,
5973                 opt_author ? commit->author : "",
5974                 mkdate(&commit->time, opt_date),
5975                 NULL
5976         };
5978         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5981 static void
5982 main_select(struct view *view, struct line *line)
5984         struct commit *commit = line->data;
5986         string_copy_rev(view->ref, commit->id);
5987         string_copy_rev(ref_commit, view->ref);
5990 static struct view_ops main_ops = {
5991         "commit",
5992         main_open,
5993         main_read,
5994         main_draw,
5995         main_request,
5996         main_grep,
5997         main_select,
5998 };
6001 /*
6002  * Status management
6003  */
6005 /* Whether or not the curses interface has been initialized. */
6006 static bool cursed = FALSE;
6008 /* Terminal hacks and workarounds. */
6009 static bool use_scroll_redrawwin;
6010 static bool use_scroll_status_wclear;
6012 /* The status window is used for polling keystrokes. */
6013 static WINDOW *status_win;
6015 /* Reading from the prompt? */
6016 static bool input_mode = FALSE;
6018 static bool status_empty = FALSE;
6020 /* Update status and title window. */
6021 static void
6022 report(const char *msg, ...)
6024         struct view *view = display[current_view];
6026         if (input_mode)
6027                 return;
6029         if (!view) {
6030                 char buf[SIZEOF_STR];
6031                 va_list args;
6033                 va_start(args, msg);
6034                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6035                         buf[sizeof(buf) - 1] = 0;
6036                         buf[sizeof(buf) - 2] = '.';
6037                         buf[sizeof(buf) - 3] = '.';
6038                         buf[sizeof(buf) - 4] = '.';
6039                 }
6040                 va_end(args);
6041                 die("%s", buf);
6042         }
6044         if (!status_empty || *msg) {
6045                 va_list args;
6047                 va_start(args, msg);
6049                 wmove(status_win, 0, 0);
6050                 if (view->has_scrolled && use_scroll_status_wclear)
6051                         wclear(status_win);
6052                 if (*msg) {
6053                         vwprintw(status_win, msg, args);
6054                         status_empty = FALSE;
6055                 } else {
6056                         status_empty = TRUE;
6057                 }
6058                 wclrtoeol(status_win);
6059                 wnoutrefresh(status_win);
6061                 va_end(args);
6062         }
6064         update_view_title(view);
6067 static void
6068 init_display(void)
6070         const char *term;
6071         int x, y;
6073         /* Initialize the curses library */
6074         if (isatty(STDIN_FILENO)) {
6075                 cursed = !!initscr();
6076                 opt_tty = stdin;
6077         } else {
6078                 /* Leave stdin and stdout alone when acting as a pager. */
6079                 opt_tty = fopen("/dev/tty", "r+");
6080                 if (!opt_tty)
6081                         die("Failed to open /dev/tty");
6082                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6083         }
6085         if (!cursed)
6086                 die("Failed to initialize curses");
6088         nonl();         /* Disable conversion and detect newlines from input. */
6089         cbreak();       /* Take input chars one at a time, no wait for \n */
6090         noecho();       /* Don't echo input */
6091         leaveok(stdscr, FALSE);
6093         if (has_colors())
6094                 init_colors();
6096         getmaxyx(stdscr, y, x);
6097         status_win = newwin(1, x, y - 1, 0);
6098         if (!status_win)
6099                 die("Failed to create status window");
6101         /* Enable keyboard mapping */
6102         keypad(status_win, TRUE);
6103         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6105 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6106         set_tabsize(opt_tab_size);
6107 #else
6108         TABSIZE = opt_tab_size;
6109 #endif
6111         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6112         if (term && !strcmp(term, "gnome-terminal")) {
6113                 /* In the gnome-terminal-emulator, the message from
6114                  * scrolling up one line when impossible followed by
6115                  * scrolling down one line causes corruption of the
6116                  * status line. This is fixed by calling wclear. */
6117                 use_scroll_status_wclear = TRUE;
6118                 use_scroll_redrawwin = FALSE;
6120         } else if (term && !strcmp(term, "xrvt-xpm")) {
6121                 /* No problems with full optimizations in xrvt-(unicode)
6122                  * and aterm. */
6123                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6125         } else {
6126                 /* When scrolling in (u)xterm the last line in the
6127                  * scrolling direction will update slowly. */
6128                 use_scroll_redrawwin = TRUE;
6129                 use_scroll_status_wclear = FALSE;
6130         }
6133 static int
6134 get_input(int prompt_position)
6136         struct view *view;
6137         int i, key, cursor_y, cursor_x;
6139         if (prompt_position)
6140                 input_mode = TRUE;
6142         while (TRUE) {
6143                 bool loading = FALSE;
6145                 foreach_view (view, i) {
6146                         update_view(view);
6147                         if (view_is_displayed(view) && view->has_scrolled &&
6148                             use_scroll_redrawwin)
6149                                 redrawwin(view->win);
6150                         view->has_scrolled = FALSE;
6151                         if (view->pipe)
6152                                 loading = TRUE;
6153                 }
6155                 /* Update the cursor position. */
6156                 if (prompt_position) {
6157                         getbegyx(status_win, cursor_y, cursor_x);
6158                         cursor_x = prompt_position;
6159                 } else {
6160                         view = display[current_view];
6161                         getbegyx(view->win, cursor_y, cursor_x);
6162                         cursor_x = view->width - 1;
6163                         cursor_y += view->lineno - view->offset;
6164                 }
6165                 setsyx(cursor_y, cursor_x);
6167                 /* Refresh, accept single keystroke of input */
6168                 doupdate();
6169                 nodelay(status_win, loading);
6170                 key = wgetch(status_win);
6172                 /* wgetch() with nodelay() enabled returns ERR when
6173                  * there's no input. */
6174                 if (key == ERR) {
6176                 } else if (key == KEY_RESIZE) {
6177                         int height, width;
6179                         getmaxyx(stdscr, height, width);
6181                         wresize(status_win, 1, width);
6182                         mvwin(status_win, height - 1, 0);
6183                         wnoutrefresh(status_win);
6184                         resize_display();
6185                         redraw_display(TRUE);
6187                 } else {
6188                         input_mode = FALSE;
6189                         return key;
6190                 }
6191         }
6194 static char *
6195 prompt_input(const char *prompt, input_handler handler, void *data)
6197         enum input_status status = INPUT_OK;
6198         static char buf[SIZEOF_STR];
6199         size_t pos = 0;
6201         buf[pos] = 0;
6203         while (status == INPUT_OK || status == INPUT_SKIP) {
6204                 int key;
6206                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6207                 wclrtoeol(status_win);
6209                 key = get_input(pos + 1);
6210                 switch (key) {
6211                 case KEY_RETURN:
6212                 case KEY_ENTER:
6213                 case '\n':
6214                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6215                         break;
6217                 case KEY_BACKSPACE:
6218                         if (pos > 0)
6219                                 buf[--pos] = 0;
6220                         else
6221                                 status = INPUT_CANCEL;
6222                         break;
6224                 case KEY_ESC:
6225                         status = INPUT_CANCEL;
6226                         break;
6228                 default:
6229                         if (pos >= sizeof(buf)) {
6230                                 report("Input string too long");
6231                                 return NULL;
6232                         }
6234                         status = handler(data, buf, key);
6235                         if (status == INPUT_OK)
6236                                 buf[pos++] = (char) key;
6237                 }
6238         }
6240         /* Clear the status window */
6241         status_empty = FALSE;
6242         report("");
6244         if (status == INPUT_CANCEL)
6245                 return NULL;
6247         buf[pos++] = 0;
6249         return buf;
6252 static enum input_status
6253 prompt_yesno_handler(void *data, char *buf, int c)
6255         if (c == 'y' || c == 'Y')
6256                 return INPUT_STOP;
6257         if (c == 'n' || c == 'N')
6258                 return INPUT_CANCEL;
6259         return INPUT_SKIP;
6262 static bool
6263 prompt_yesno(const char *prompt)
6265         char prompt2[SIZEOF_STR];
6267         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6268                 return FALSE;
6270         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6273 static enum input_status
6274 read_prompt_handler(void *data, char *buf, int c)
6276         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6279 static char *
6280 read_prompt(const char *prompt)
6282         return prompt_input(prompt, read_prompt_handler, NULL);
6285 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6287         enum input_status status = INPUT_OK;
6288         int size = 0;
6290         while (items[size].text)
6291                 size++;
6293         while (status == INPUT_OK) {
6294                 const struct menu_item *item = &items[*selected];
6295                 int key;
6296                 int i;
6298                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6299                           prompt, *selected + 1, size);
6300                 if (item->hotkey)
6301                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6302                 wprintw(status_win, "%s", item->text);
6303                 wclrtoeol(status_win);
6305                 key = get_input(COLS - 1);
6306                 switch (key) {
6307                 case KEY_RETURN:
6308                 case KEY_ENTER:
6309                 case '\n':
6310                         status = INPUT_STOP;
6311                         break;
6313                 case KEY_LEFT:
6314                 case KEY_UP:
6315                         *selected = *selected - 1;
6316                         if (*selected < 0)
6317                                 *selected = size - 1;
6318                         break;
6320                 case KEY_RIGHT:
6321                 case KEY_DOWN:
6322                         *selected = (*selected + 1) % size;
6323                         break;
6325                 case KEY_ESC:
6326                         status = INPUT_CANCEL;
6327                         break;
6329                 default:
6330                         for (i = 0; items[i].text; i++)
6331                                 if (items[i].hotkey == key) {
6332                                         *selected = i;
6333                                         status = INPUT_STOP;
6334                                         break;
6335                                 }
6336                 }
6337         }
6339         /* Clear the status window */
6340         status_empty = FALSE;
6341         report("");
6343         return status != INPUT_CANCEL;
6346 /*
6347  * Repository properties
6348  */
6350 static struct ref **refs = NULL;
6351 static size_t refs_size = 0;
6352 static struct ref *refs_head = NULL;
6354 static struct ref_list **ref_lists = NULL;
6355 static size_t ref_lists_size = 0;
6357 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6358 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6359 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6361 static int
6362 compare_refs(const void *ref1_, const void *ref2_)
6364         const struct ref *ref1 = *(const struct ref **)ref1_;
6365         const struct ref *ref2 = *(const struct ref **)ref2_;
6367         if (ref1->tag != ref2->tag)
6368                 return ref2->tag - ref1->tag;
6369         if (ref1->ltag != ref2->ltag)
6370                 return ref2->ltag - ref2->ltag;
6371         if (ref1->head != ref2->head)
6372                 return ref2->head - ref1->head;
6373         if (ref1->tracked != ref2->tracked)
6374                 return ref2->tracked - ref1->tracked;
6375         if (ref1->remote != ref2->remote)
6376                 return ref2->remote - ref1->remote;
6377         return strcmp(ref1->name, ref2->name);
6380 static void
6381 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6383         size_t i;
6385         for (i = 0; i < refs_size; i++)
6386                 if (!visitor(data, refs[i]))
6387                         break;
6390 static struct ref *
6391 get_ref_head()
6393         return refs_head;
6396 static struct ref_list *
6397 get_ref_list(const char *id)
6399         struct ref_list *list;
6400         size_t i;
6402         for (i = 0; i < ref_lists_size; i++)
6403                 if (!strcmp(id, ref_lists[i]->id))
6404                         return ref_lists[i];
6406         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6407                 return NULL;
6408         list = calloc(1, sizeof(*list));
6409         if (!list)
6410                 return NULL;
6412         for (i = 0; i < refs_size; i++) {
6413                 if (!strcmp(id, refs[i]->id) &&
6414                     realloc_refs_list(&list->refs, list->size, 1))
6415                         list->refs[list->size++] = refs[i];
6416         }
6418         if (!list->refs) {
6419                 free(list);
6420                 return NULL;
6421         }
6423         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6424         ref_lists[ref_lists_size++] = list;
6425         return list;
6428 static int
6429 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6431         struct ref *ref = NULL;
6432         bool tag = FALSE;
6433         bool ltag = FALSE;
6434         bool remote = FALSE;
6435         bool tracked = FALSE;
6436         bool head = FALSE;
6437         int from = 0, to = refs_size - 1;
6439         if (!prefixcmp(name, "refs/tags/")) {
6440                 if (!suffixcmp(name, namelen, "^{}")) {
6441                         namelen -= 3;
6442                         name[namelen] = 0;
6443                 } else {
6444                         ltag = TRUE;
6445                 }
6447                 tag = TRUE;
6448                 namelen -= STRING_SIZE("refs/tags/");
6449                 name    += STRING_SIZE("refs/tags/");
6451         } else if (!prefixcmp(name, "refs/remotes/")) {
6452                 remote = TRUE;
6453                 namelen -= STRING_SIZE("refs/remotes/");
6454                 name    += STRING_SIZE("refs/remotes/");
6455                 tracked  = !strcmp(opt_remote, name);
6457         } else if (!prefixcmp(name, "refs/heads/")) {
6458                 namelen -= STRING_SIZE("refs/heads/");
6459                 name    += STRING_SIZE("refs/heads/");
6460                 if (!strncmp(opt_head, name, namelen))
6461                         return OK;
6463         } else if (!strcmp(name, "HEAD")) {
6464                 head     = TRUE;
6465                 if (*opt_head) {
6466                         namelen  = strlen(opt_head);
6467                         name     = opt_head;
6468                 }
6469         }
6471         /* If we are reloading or it's an annotated tag, replace the
6472          * previous SHA1 with the resolved commit id; relies on the fact
6473          * git-ls-remote lists the commit id of an annotated tag right
6474          * before the commit id it points to. */
6475         while (from <= to) {
6476                 size_t pos = (to + from) / 2;
6477                 int cmp = strcmp(name, refs[pos]->name);
6479                 if (!cmp) {
6480                         ref = refs[pos];
6481                         break;
6482                 }
6484                 if (cmp < 0)
6485                         to = pos - 1;
6486                 else
6487                         from = pos + 1;
6488         }
6490         if (!ref) {
6491                 if (!realloc_refs(&refs, refs_size, 1))
6492                         return ERR;
6493                 ref = calloc(1, sizeof(*ref) + namelen);
6494                 if (!ref)
6495                         return ERR;
6496                 memmove(refs + from + 1, refs + from,
6497                         (refs_size - from) * sizeof(*refs));
6498                 refs[from] = ref;
6499                 strncpy(ref->name, name, namelen);
6500                 refs_size++;
6501         }
6503         ref->head = head;
6504         ref->tag = tag;
6505         ref->ltag = ltag;
6506         ref->remote = remote;
6507         ref->tracked = tracked;
6508         string_copy_rev(ref->id, id);
6510         if (head)
6511                 refs_head = ref;
6512         return OK;
6515 static int
6516 load_refs(void)
6518         const char *head_argv[] = {
6519                 "git", "symbolic-ref", "HEAD", NULL
6520         };
6521         static const char *ls_remote_argv[SIZEOF_ARG] = {
6522                 "git", "ls-remote", opt_git_dir, NULL
6523         };
6524         static bool init = FALSE;
6525         size_t i;
6527         if (!init) {
6528                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6529                         die("TIG_LS_REMOTE contains too many arguments");
6530                 init = TRUE;
6531         }
6533         if (!*opt_git_dir)
6534                 return OK;
6536         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6537             !prefixcmp(opt_head, "refs/heads/")) {
6538                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6540                 memmove(opt_head, offset, strlen(offset) + 1);
6541         }
6543         refs_head = NULL;
6544         for (i = 0; i < refs_size; i++)
6545                 refs[i]->id[0] = 0;
6547         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6548                 return ERR;
6550         /* Update the ref lists to reflect changes. */
6551         for (i = 0; i < ref_lists_size; i++) {
6552                 struct ref_list *list = ref_lists[i];
6553                 size_t old, new;
6555                 for (old = new = 0; old < list->size; old++)
6556                         if (!strcmp(list->id, list->refs[old]->id))
6557                                 list->refs[new++] = list->refs[old];
6558                 list->size = new;
6559         }
6561         return OK;
6564 static void
6565 set_remote_branch(const char *name, const char *value, size_t valuelen)
6567         if (!strcmp(name, ".remote")) {
6568                 string_ncopy(opt_remote, value, valuelen);
6570         } else if (*opt_remote && !strcmp(name, ".merge")) {
6571                 size_t from = strlen(opt_remote);
6573                 if (!prefixcmp(value, "refs/heads/"))
6574                         value += STRING_SIZE("refs/heads/");
6576                 if (!string_format_from(opt_remote, &from, "/%s", value))
6577                         opt_remote[0] = 0;
6578         }
6581 static void
6582 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6584         const char *argv[SIZEOF_ARG] = { name, "=" };
6585         int argc = 1 + (cmd == option_set_command);
6586         enum option_code error;
6588         if (!argv_from_string(argv, &argc, value))
6589                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6590         else
6591                 error = cmd(argc, argv);
6593         if (error != OPT_OK)
6594                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6597 static bool
6598 set_environment_variable(const char *name, const char *value)
6600         size_t len = strlen(name) + 1 + strlen(value) + 1;
6601         char *env = malloc(len);
6603         if (env &&
6604             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6605             putenv(env) == 0)
6606                 return TRUE;
6607         free(env);
6608         return FALSE;
6611 static void
6612 set_work_tree(const char *value)
6614         char cwd[SIZEOF_STR];
6616         if (!getcwd(cwd, sizeof(cwd)))
6617                 die("Failed to get cwd path: %s", strerror(errno));
6618         if (chdir(opt_git_dir) < 0)
6619                 die("Failed to chdir(%s): %s", strerror(errno));
6620         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6621                 die("Failed to get git path: %s", strerror(errno));
6622         if (chdir(cwd) < 0)
6623                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6624         if (chdir(value) < 0)
6625                 die("Failed to chdir(%s): %s", value, strerror(errno));
6626         if (!getcwd(cwd, sizeof(cwd)))
6627                 die("Failed to get cwd path: %s", strerror(errno));
6628         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6629                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6630         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6631                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6632         opt_is_inside_work_tree = TRUE;
6635 static int
6636 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6638         if (!strcmp(name, "i18n.commitencoding"))
6639                 string_ncopy(opt_encoding, value, valuelen);
6641         else if (!strcmp(name, "core.editor"))
6642                 string_ncopy(opt_editor, value, valuelen);
6644         else if (!strcmp(name, "core.worktree"))
6645                 set_work_tree(value);
6647         else if (!prefixcmp(name, "tig.color."))
6648                 set_repo_config_option(name + 10, value, option_color_command);
6650         else if (!prefixcmp(name, "tig.bind."))
6651                 set_repo_config_option(name + 9, value, option_bind_command);
6653         else if (!prefixcmp(name, "tig."))
6654                 set_repo_config_option(name + 4, value, option_set_command);
6656         else if (*opt_head && !prefixcmp(name, "branch.") &&
6657                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6658                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6660         return OK;
6663 static int
6664 load_git_config(void)
6666         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6668         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6671 static int
6672 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6674         if (!opt_git_dir[0]) {
6675                 string_ncopy(opt_git_dir, name, namelen);
6677         } else if (opt_is_inside_work_tree == -1) {
6678                 /* This can be 3 different values depending on the
6679                  * version of git being used. If git-rev-parse does not
6680                  * understand --is-inside-work-tree it will simply echo
6681                  * the option else either "true" or "false" is printed.
6682                  * Default to true for the unknown case. */
6683                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6685         } else if (*name == '.') {
6686                 string_ncopy(opt_cdup, name, namelen);
6688         } else {
6689                 string_ncopy(opt_prefix, name, namelen);
6690         }
6692         return OK;
6695 static int
6696 load_repo_info(void)
6698         const char *rev_parse_argv[] = {
6699                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6700                         "--show-cdup", "--show-prefix", NULL
6701         };
6703         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6707 /*
6708  * Main
6709  */
6711 static const char usage[] =
6712 "tig " TIG_VERSION " (" __DATE__ ")\n"
6713 "\n"
6714 "Usage: tig        [options] [revs] [--] [paths]\n"
6715 "   or: tig show   [options] [revs] [--] [paths]\n"
6716 "   or: tig blame  [options] [rev] [--] path\n"
6717 "   or: tig status\n"
6718 "   or: tig <      [git command output]\n"
6719 "\n"
6720 "Options:\n"
6721 "  -v, --version   Show version and exit\n"
6722 "  -h, --help      Show help message and exit";
6724 static void __NORETURN
6725 quit(int sig)
6727         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6728         if (cursed)
6729                 endwin();
6730         exit(0);
6733 static void __NORETURN
6734 die(const char *err, ...)
6736         va_list args;
6738         endwin();
6740         va_start(args, err);
6741         fputs("tig: ", stderr);
6742         vfprintf(stderr, err, args);
6743         fputs("\n", stderr);
6744         va_end(args);
6746         exit(1);
6749 static void
6750 warn(const char *msg, ...)
6752         va_list args;
6754         va_start(args, msg);
6755         fputs("tig warning: ", stderr);
6756         vfprintf(stderr, msg, args);
6757         fputs("\n", stderr);
6758         va_end(args);
6761 static int
6762 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6764         const char ***filter_args = data;
6766         return argv_append(filter_args, name) ? OK : ERR;
6769 static void
6770 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6772         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6773         const char **all_argv = NULL;
6775         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6776             !argv_append_array(&all_argv, argv) ||
6777             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6778                 die("Failed to split arguments");
6779         argv_free(all_argv);
6780         free(all_argv);
6783 static void
6784 filter_options(const char *argv[])
6786         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6787         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6788         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6791 static enum request
6792 parse_options(int argc, const char *argv[])
6794         enum request request = REQ_VIEW_MAIN;
6795         const char *subcommand;
6796         bool seen_dashdash = FALSE;
6797         const char **filter_argv = NULL;
6798         int i;
6800         if (!isatty(STDIN_FILENO))
6801                 return REQ_VIEW_PAGER;
6803         if (argc <= 1)
6804                 return REQ_VIEW_MAIN;
6806         subcommand = argv[1];
6807         if (!strcmp(subcommand, "status")) {
6808                 if (argc > 2)
6809                         warn("ignoring arguments after `%s'", subcommand);
6810                 return REQ_VIEW_STATUS;
6812         } else if (!strcmp(subcommand, "blame")) {
6813                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6814                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6815                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6817                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6818                         die("invalid number of options to blame\n\n%s", usage);
6820                 if (opt_rev_argv) {
6821                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6822                 }
6824                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6825                 return REQ_VIEW_BLAME;
6827         } else if (!strcmp(subcommand, "show")) {
6828                 request = REQ_VIEW_DIFF;
6830         } else {
6831                 subcommand = NULL;
6832         }
6834         for (i = 1 + !!subcommand; i < argc; i++) {
6835                 const char *opt = argv[i];
6837                 if (seen_dashdash) {
6838                         argv_append(&opt_file_argv, opt);
6839                         continue;
6841                 } else if (!strcmp(opt, "--")) {
6842                         seen_dashdash = TRUE;
6843                         continue;
6845                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6846                         printf("tig version %s\n", TIG_VERSION);
6847                         quit(0);
6849                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6850                         printf("%s\n", usage);
6851                         quit(0);
6853                 } else if (!strcmp(opt, "--all")) {
6854                         argv_append(&opt_rev_argv, opt);
6855                         continue;
6856                 }
6858                 if (!argv_append(&filter_argv, opt))
6859                         die("command too long");
6860         }
6862         if (filter_argv)
6863                 filter_options(filter_argv);
6865         return request;
6868 int
6869 main(int argc, const char *argv[])
6871         const char *codeset = "UTF-8";
6872         enum request request = parse_options(argc, argv);
6873         struct view *view;
6875         signal(SIGINT, quit);
6876         signal(SIGPIPE, SIG_IGN);
6878         if (setlocale(LC_ALL, "")) {
6879                 codeset = nl_langinfo(CODESET);
6880         }
6882         if (load_repo_info() == ERR)
6883                 die("Failed to load repo info.");
6885         if (load_options() == ERR)
6886                 die("Failed to load user config.");
6888         if (load_git_config() == ERR)
6889                 die("Failed to load repo config.");
6891         /* Require a git repository unless when running in pager mode. */
6892         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6893                 die("Not a git repository");
6895         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6896                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6897                 if (opt_iconv_in == ICONV_NONE)
6898                         die("Failed to initialize character set conversion");
6899         }
6901         if (codeset && strcmp(codeset, "UTF-8")) {
6902                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6903                 if (opt_iconv_out == ICONV_NONE)
6904                         die("Failed to initialize character set conversion");
6905         }
6907         if (load_refs() == ERR)
6908                 die("Failed to load refs.");
6910         init_display();
6912         while (view_driver(display[current_view], request)) {
6913                 int key = get_input(0);
6915                 view = display[current_view];
6916                 request = get_keybinding(view->keymap, key);
6918                 /* Some low-level request handling. This keeps access to
6919                  * status_win restricted. */
6920                 switch (request) {
6921                 case REQ_NONE:
6922                         report("Unknown key, press %s for help",
6923                                get_key(view->keymap, REQ_VIEW_HELP));
6924                         break;
6925                 case REQ_PROMPT:
6926                 {
6927                         char *cmd = read_prompt(":");
6929                         if (cmd && isdigit(*cmd)) {
6930                                 int lineno = view->lineno + 1;
6932                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6933                                         select_view_line(view, lineno - 1);
6934                                         report("");
6935                                 } else {
6936                                         report("Unable to parse '%s' as a line number", cmd);
6937                                 }
6939                         } else if (cmd) {
6940                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6941                                 const char *argv[SIZEOF_ARG] = { "git" };
6942                                 int argc = 1;
6944                                 /* When running random commands, initially show the
6945                                  * command in the title. However, it maybe later be
6946                                  * overwritten if a commit line is selected. */
6947                                 string_ncopy(next->ref, cmd, strlen(cmd));
6949                                 if (!argv_from_string(argv, &argc, cmd)) {
6950                                         report("Too many arguments");
6951                                 } else {
6952                                         open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6953                                 }
6954                         }
6956                         request = REQ_NONE;
6957                         break;
6958                 }
6959                 case REQ_SEARCH:
6960                 case REQ_SEARCH_BACK:
6961                 {
6962                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6963                         char *search = read_prompt(prompt);
6965                         if (search)
6966                                 string_ncopy(opt_search, search, strlen(search));
6967                         else if (*opt_search)
6968                                 request = request == REQ_SEARCH ?
6969                                         REQ_FIND_NEXT :
6970                                         REQ_FIND_PREV;
6971                         else
6972                                 request = REQ_NONE;
6973                         break;
6974                 }
6975                 default:
6976                         break;
6977                 }
6978         }
6980         quit(0);
6982         return 0;