Code

Refactor mkauthor from draw_author
[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;
210 #define author_trim(cols) (cols == 0 || cols > 5)
212 static const char *
213 mkauthor(const char *text, int cols, enum author author)
215         bool trim = author_trim(cols);
216         bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
218         if (!author)
219                 return "";
220         if (abbreviate && text)
221                 return get_author_initials(text);
222         return text;
225 /*
226  * User requests
227  */
229 #define REQ_INFO \
230         /* XXX: Keep the view request first and in sync with views[]. */ \
231         REQ_GROUP("View switching") \
232         REQ_(VIEW_MAIN,         "Show main view"), \
233         REQ_(VIEW_DIFF,         "Show diff view"), \
234         REQ_(VIEW_LOG,          "Show log view"), \
235         REQ_(VIEW_TREE,         "Show tree view"), \
236         REQ_(VIEW_BLOB,         "Show blob view"), \
237         REQ_(VIEW_BLAME,        "Show blame view"), \
238         REQ_(VIEW_BRANCH,       "Show branch view"), \
239         REQ_(VIEW_HELP,         "Show help page"), \
240         REQ_(VIEW_PAGER,        "Show pager view"), \
241         REQ_(VIEW_STATUS,       "Show status view"), \
242         REQ_(VIEW_STAGE,        "Show stage view"), \
243         \
244         REQ_GROUP("View manipulation") \
245         REQ_(ENTER,             "Enter current line and scroll"), \
246         REQ_(NEXT,              "Move to next"), \
247         REQ_(PREVIOUS,          "Move to previous"), \
248         REQ_(PARENT,            "Move to parent"), \
249         REQ_(VIEW_NEXT,         "Move focus to next view"), \
250         REQ_(REFRESH,           "Reload and refresh"), \
251         REQ_(MAXIMIZE,          "Maximize the current view"), \
252         REQ_(VIEW_CLOSE,        "Close the current view"), \
253         REQ_(QUIT,              "Close all views and quit"), \
254         \
255         REQ_GROUP("View specific requests") \
256         REQ_(STATUS_UPDATE,     "Update file status"), \
257         REQ_(STATUS_REVERT,     "Revert file changes"), \
258         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
259         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
260         \
261         REQ_GROUP("Cursor navigation") \
262         REQ_(MOVE_UP,           "Move cursor one line up"), \
263         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
264         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
265         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
266         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
267         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
268         \
269         REQ_GROUP("Scrolling") \
270         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
271         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
272         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
273         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
274         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
275         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
276         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
277         \
278         REQ_GROUP("Searching") \
279         REQ_(SEARCH,            "Search the view"), \
280         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
281         REQ_(FIND_NEXT,         "Find next search match"), \
282         REQ_(FIND_PREV,         "Find previous search match"), \
283         \
284         REQ_GROUP("Option manipulation") \
285         REQ_(OPTIONS,           "Open option menu"), \
286         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
287         REQ_(TOGGLE_DATE,       "Toggle date display"), \
288         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
289         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
290         REQ_(TOGGLE_GRAPHIC,    "Toggle (line) graphics mode"), \
291         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
292         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
293         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
294         \
295         REQ_GROUP("Misc") \
296         REQ_(PROMPT,            "Bring up the prompt"), \
297         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
298         REQ_(SHOW_VERSION,      "Show version information"), \
299         REQ_(STOP_LOADING,      "Stop all loading views"), \
300         REQ_(EDIT,              "Open in editor"), \
301         REQ_(NONE,              "Do nothing")
304 /* User action requests. */
305 enum request {
306 #define REQ_GROUP(help)
307 #define REQ_(req, help) REQ_##req
309         /* Offset all requests to avoid conflicts with ncurses getch values. */
310         REQ_UNKNOWN = KEY_MAX + 1,
311         REQ_OFFSET,
312         REQ_INFO
314 #undef  REQ_GROUP
315 #undef  REQ_
316 };
318 struct request_info {
319         enum request request;
320         const char *name;
321         int namelen;
322         const char *help;
323 };
325 static const struct request_info req_info[] = {
326 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
327 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
328         REQ_INFO
329 #undef  REQ_GROUP
330 #undef  REQ_
331 };
333 static enum request
334 get_request(const char *name)
336         int namelen = strlen(name);
337         int i;
339         for (i = 0; i < ARRAY_SIZE(req_info); i++)
340                 if (enum_equals(req_info[i], name, namelen))
341                         return req_info[i].request;
343         return REQ_UNKNOWN;
347 /*
348  * Options
349  */
351 /* Option and state variables. */
352 static enum graphic opt_line_graphics   = GRAPHIC_DEFAULT;
353 static enum date opt_date               = DATE_DEFAULT;
354 static enum author opt_author           = AUTHOR_DEFAULT;
355 static bool opt_rev_graph               = TRUE;
356 static bool opt_line_number             = FALSE;
357 static bool opt_show_refs               = TRUE;
358 static bool opt_untracked_dirs_content  = TRUE;
359 static int opt_num_interval             = 5;
360 static double opt_hscroll               = 0.50;
361 static double opt_scale_split_view      = 2.0 / 3.0;
362 static int opt_tab_size                 = 8;
363 static int opt_author_cols              = AUTHOR_COLS;
364 static char opt_path[SIZEOF_STR]        = "";
365 static char opt_file[SIZEOF_STR]        = "";
366 static char opt_ref[SIZEOF_REF]         = "";
367 static char opt_head[SIZEOF_REF]        = "";
368 static char opt_remote[SIZEOF_REF]      = "";
369 static char opt_encoding[20]            = "UTF-8";
370 static iconv_t opt_iconv_in             = ICONV_NONE;
371 static iconv_t opt_iconv_out            = ICONV_NONE;
372 static char opt_search[SIZEOF_STR]      = "";
373 static char opt_cdup[SIZEOF_STR]        = "";
374 static char opt_prefix[SIZEOF_STR]      = "";
375 static char opt_git_dir[SIZEOF_STR]     = "";
376 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
377 static char opt_editor[SIZEOF_STR]      = "";
378 static FILE *opt_tty                    = NULL;
379 static const char **opt_diff_argv       = NULL;
380 static const char **opt_rev_argv        = NULL;
381 static const char **opt_file_argv       = NULL;
382 static const char **opt_blame_argv      = NULL;
384 #define is_initial_commit()     (!get_ref_head())
385 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
388 /*
389  * Line-oriented content detection.
390  */
392 #define LINE_INFO \
393 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
394 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
395 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
396 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
397 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
398 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
399 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
400 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
401 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
402 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
403 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
404 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
405 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
406 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
407 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
408 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
409 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
410 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
411 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
412 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
413 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
414 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
415 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
416 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
417 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
418 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
419 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
420 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
421 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
422 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
423 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
424 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
425 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
426 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
427 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
428 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
429 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
430 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
431 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
432 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
433 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
434 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
435 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
436 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
437 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
438 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
439 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
440 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
441 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
442 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
443 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
444 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
445 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
446 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
447 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
448 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
449 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
450 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
451 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
452 LINE(GRAPH_LINE_0, "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
453 LINE(GRAPH_LINE_1, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
454 LINE(GRAPH_LINE_2, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
455 LINE(GRAPH_LINE_3, "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
456 LINE(GRAPH_LINE_4, "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
457 LINE(GRAPH_LINE_5, "",                  COLOR_WHITE,    COLOR_DEFAULT,  0), \
458 LINE(GRAPH_LINE_6, "",                  COLOR_RED,      COLOR_DEFAULT,  0), \
459 LINE(GRAPH_COMMIT, "",                  COLOR_BLUE,     COLOR_DEFAULT,  0)
461 enum line_type {
462 #define LINE(type, line, fg, bg, attr) \
463         LINE_##type
464         LINE_INFO,
465         LINE_NONE
466 #undef  LINE
467 };
469 struct line_info {
470         const char *name;       /* Option name. */
471         int namelen;            /* Size of option name. */
472         const char *line;       /* The start of line to match. */
473         int linelen;            /* Size of string to match. */
474         int fg, bg, attr;       /* Color and text attributes for the lines. */
475 };
477 static struct line_info line_info[] = {
478 #define LINE(type, line, fg, bg, attr) \
479         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
480         LINE_INFO
481 #undef  LINE
482 };
484 static enum line_type
485 get_line_type(const char *line)
487         int linelen = strlen(line);
488         enum line_type type;
490         for (type = 0; type < ARRAY_SIZE(line_info); type++)
491                 /* Case insensitive search matches Signed-off-by lines better. */
492                 if (linelen >= line_info[type].linelen &&
493                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
494                         return type;
496         return LINE_DEFAULT;
499 static inline int
500 get_line_attr(enum line_type type)
502         assert(type < ARRAY_SIZE(line_info));
503         return COLOR_PAIR(type) | line_info[type].attr;
506 static struct line_info *
507 get_line_info(const char *name)
509         size_t namelen = strlen(name);
510         enum line_type type;
512         for (type = 0; type < ARRAY_SIZE(line_info); type++)
513                 if (enum_equals(line_info[type], name, namelen))
514                         return &line_info[type];
516         return NULL;
519 static void
520 init_colors(void)
522         int default_bg = line_info[LINE_DEFAULT].bg;
523         int default_fg = line_info[LINE_DEFAULT].fg;
524         enum line_type type;
526         start_color();
528         if (assume_default_colors(default_fg, default_bg) == ERR) {
529                 default_bg = COLOR_BLACK;
530                 default_fg = COLOR_WHITE;
531         }
533         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
534                 struct line_info *info = &line_info[type];
535                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
536                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
538                 init_pair(type, fg, bg);
539         }
542 struct line {
543         enum line_type type;
545         /* State flags */
546         unsigned int selected:1;
547         unsigned int dirty:1;
548         unsigned int cleareol:1;
549         unsigned int other:16;
551         void *data;             /* User data */
552 };
555 /*
556  * Keys
557  */
559 struct keybinding {
560         int alias;
561         enum request request;
562 };
564 static struct keybinding default_keybindings[] = {
565         /* View switching */
566         { 'm',          REQ_VIEW_MAIN },
567         { 'd',          REQ_VIEW_DIFF },
568         { 'l',          REQ_VIEW_LOG },
569         { 't',          REQ_VIEW_TREE },
570         { 'f',          REQ_VIEW_BLOB },
571         { 'B',          REQ_VIEW_BLAME },
572         { 'H',          REQ_VIEW_BRANCH },
573         { 'p',          REQ_VIEW_PAGER },
574         { 'h',          REQ_VIEW_HELP },
575         { 'S',          REQ_VIEW_STATUS },
576         { 'c',          REQ_VIEW_STAGE },
578         /* View manipulation */
579         { 'q',          REQ_VIEW_CLOSE },
580         { KEY_TAB,      REQ_VIEW_NEXT },
581         { KEY_RETURN,   REQ_ENTER },
582         { KEY_UP,       REQ_PREVIOUS },
583         { KEY_CTL('P'), REQ_PREVIOUS },
584         { KEY_DOWN,     REQ_NEXT },
585         { KEY_CTL('N'), REQ_NEXT },
586         { 'R',          REQ_REFRESH },
587         { KEY_F(5),     REQ_REFRESH },
588         { 'O',          REQ_MAXIMIZE },
590         /* Cursor navigation */
591         { 'k',          REQ_MOVE_UP },
592         { 'j',          REQ_MOVE_DOWN },
593         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
594         { KEY_END,      REQ_MOVE_LAST_LINE },
595         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
596         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
597         { ' ',          REQ_MOVE_PAGE_DOWN },
598         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
599         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
600         { 'b',          REQ_MOVE_PAGE_UP },
601         { '-',          REQ_MOVE_PAGE_UP },
603         /* Scrolling */
604         { '|',          REQ_SCROLL_FIRST_COL },
605         { KEY_LEFT,     REQ_SCROLL_LEFT },
606         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
607         { KEY_IC,       REQ_SCROLL_LINE_UP },
608         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
609         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
610         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
611         { 'w',          REQ_SCROLL_PAGE_UP },
612         { 's',          REQ_SCROLL_PAGE_DOWN },
614         /* Searching */
615         { '/',          REQ_SEARCH },
616         { '?',          REQ_SEARCH_BACK },
617         { 'n',          REQ_FIND_NEXT },
618         { 'N',          REQ_FIND_PREV },
620         /* Misc */
621         { 'Q',          REQ_QUIT },
622         { 'z',          REQ_STOP_LOADING },
623         { 'v',          REQ_SHOW_VERSION },
624         { 'r',          REQ_SCREEN_REDRAW },
625         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
626         { 'o',          REQ_OPTIONS },
627         { '.',          REQ_TOGGLE_LINENO },
628         { 'D',          REQ_TOGGLE_DATE },
629         { 'A',          REQ_TOGGLE_AUTHOR },
630         { 'g',          REQ_TOGGLE_REV_GRAPH },
631         { '~',          REQ_TOGGLE_GRAPHIC },
632         { 'F',          REQ_TOGGLE_REFS },
633         { 'I',          REQ_TOGGLE_SORT_ORDER },
634         { 'i',          REQ_TOGGLE_SORT_FIELD },
635         { ':',          REQ_PROMPT },
636         { 'u',          REQ_STATUS_UPDATE },
637         { '!',          REQ_STATUS_REVERT },
638         { 'M',          REQ_STATUS_MERGE },
639         { '@',          REQ_STAGE_NEXT },
640         { ',',          REQ_PARENT },
641         { 'e',          REQ_EDIT },
642 };
644 #define KEYMAP_INFO \
645         KEYMAP_(GENERIC), \
646         KEYMAP_(MAIN), \
647         KEYMAP_(DIFF), \
648         KEYMAP_(LOG), \
649         KEYMAP_(TREE), \
650         KEYMAP_(BLOB), \
651         KEYMAP_(BLAME), \
652         KEYMAP_(BRANCH), \
653         KEYMAP_(PAGER), \
654         KEYMAP_(HELP), \
655         KEYMAP_(STATUS), \
656         KEYMAP_(STAGE)
658 enum keymap {
659 #define KEYMAP_(name) KEYMAP_##name
660         KEYMAP_INFO
661 #undef  KEYMAP_
662 };
664 static const struct enum_map keymap_table[] = {
665 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
666         KEYMAP_INFO
667 #undef  KEYMAP_
668 };
670 #define set_keymap(map, name) map_enum(map, keymap_table, name)
672 struct keybinding_table {
673         struct keybinding *data;
674         size_t size;
675 };
677 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
679 static void
680 add_keybinding(enum keymap keymap, enum request request, int key)
682         struct keybinding_table *table = &keybindings[keymap];
683         size_t i;
685         for (i = 0; i < keybindings[keymap].size; i++) {
686                 if (keybindings[keymap].data[i].alias == key) {
687                         keybindings[keymap].data[i].request = request;
688                         return;
689                 }
690         }
692         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
693         if (!table->data)
694                 die("Failed to allocate keybinding");
695         table->data[table->size].alias = key;
696         table->data[table->size++].request = request;
698         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
699                 int i;
701                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
702                         if (default_keybindings[i].alias == key)
703                                 default_keybindings[i].request = REQ_NONE;
704         }
707 /* Looks for a key binding first in the given map, then in the generic map, and
708  * lastly in the default keybindings. */
709 static enum request
710 get_keybinding(enum keymap keymap, int key)
712         size_t i;
714         for (i = 0; i < keybindings[keymap].size; i++)
715                 if (keybindings[keymap].data[i].alias == key)
716                         return keybindings[keymap].data[i].request;
718         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
719                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
720                         return keybindings[KEYMAP_GENERIC].data[i].request;
722         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
723                 if (default_keybindings[i].alias == key)
724                         return default_keybindings[i].request;
726         return (enum request) key;
730 struct key {
731         const char *name;
732         int value;
733 };
735 static const struct key key_table[] = {
736         { "Enter",      KEY_RETURN },
737         { "Space",      ' ' },
738         { "Backspace",  KEY_BACKSPACE },
739         { "Tab",        KEY_TAB },
740         { "Escape",     KEY_ESC },
741         { "Left",       KEY_LEFT },
742         { "Right",      KEY_RIGHT },
743         { "Up",         KEY_UP },
744         { "Down",       KEY_DOWN },
745         { "Insert",     KEY_IC },
746         { "Delete",     KEY_DC },
747         { "Hash",       '#' },
748         { "Home",       KEY_HOME },
749         { "End",        KEY_END },
750         { "PageUp",     KEY_PPAGE },
751         { "PageDown",   KEY_NPAGE },
752         { "F1",         KEY_F(1) },
753         { "F2",         KEY_F(2) },
754         { "F3",         KEY_F(3) },
755         { "F4",         KEY_F(4) },
756         { "F5",         KEY_F(5) },
757         { "F6",         KEY_F(6) },
758         { "F7",         KEY_F(7) },
759         { "F8",         KEY_F(8) },
760         { "F9",         KEY_F(9) },
761         { "F10",        KEY_F(10) },
762         { "F11",        KEY_F(11) },
763         { "F12",        KEY_F(12) },
764 };
766 static int
767 get_key_value(const char *name)
769         int i;
771         for (i = 0; i < ARRAY_SIZE(key_table); i++)
772                 if (!strcasecmp(key_table[i].name, name))
773                         return key_table[i].value;
775         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
776                 return (int)name[1] & 0x1f;
777         if (strlen(name) == 1 && isprint(*name))
778                 return (int) *name;
779         return ERR;
782 static const char *
783 get_key_name(int key_value)
785         static char key_char[] = "'X'\0";
786         const char *seq = NULL;
787         int key;
789         for (key = 0; key < ARRAY_SIZE(key_table); key++)
790                 if (key_table[key].value == key_value)
791                         seq = key_table[key].name;
793         if (seq == NULL && key_value < 0x7f) {
794                 char *s = key_char + 1;
796                 if (key_value >= 0x20) {
797                         *s++ = key_value;
798                 } else {
799                         *s++ = '^';
800                         *s++ = 0x40 | (key_value & 0x1f);
801                 }
802                 *s++ = '\'';
803                 *s++ = '\0';
804                 seq = key_char;
805         }
807         return seq ? seq : "(no key)";
810 static bool
811 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
813         const char *sep = *pos > 0 ? ", " : "";
814         const char *keyname = get_key_name(keybinding->alias);
816         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
819 static bool
820 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
821                            enum keymap keymap, bool all)
823         int i;
825         for (i = 0; i < keybindings[keymap].size; i++) {
826                 if (keybindings[keymap].data[i].request == request) {
827                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
828                                 return FALSE;
829                         if (!all)
830                                 break;
831                 }
832         }
834         return TRUE;
837 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
839 static const char *
840 get_keys(enum keymap keymap, enum request request, bool all)
842         static char buf[BUFSIZ];
843         size_t pos = 0;
844         int i;
846         buf[pos] = 0;
848         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
849                 return "Too many keybindings!";
850         if (pos > 0 && !all)
851                 return buf;
853         if (keymap != KEYMAP_GENERIC) {
854                 /* Only the generic keymap includes the default keybindings when
855                  * listing all keys. */
856                 if (all)
857                         return buf;
859                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
860                         return "Too many keybindings!";
861                 if (pos)
862                         return buf;
863         }
865         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
866                 if (default_keybindings[i].request == request) {
867                         if (!append_key(buf, &pos, &default_keybindings[i]))
868                                 return "Too many keybindings!";
869                         if (!all)
870                                 return buf;
871                 }
872         }
874         return buf;
877 struct run_request {
878         enum keymap keymap;
879         int key;
880         const char **argv;
881 };
883 static struct run_request *run_request;
884 static size_t run_requests;
886 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
888 static enum request
889 add_run_request(enum keymap keymap, int key, const char **argv)
891         struct run_request *req;
893         if (!realloc_run_requests(&run_request, run_requests, 1))
894                 return REQ_NONE;
896         req = &run_request[run_requests];
897         req->keymap = keymap;
898         req->key = key;
899         req->argv = NULL;
901         if (!argv_copy(&req->argv, argv))
902                 return REQ_NONE;
904         return REQ_NONE + ++run_requests;
907 static struct run_request *
908 get_run_request(enum request request)
910         if (request <= REQ_NONE)
911                 return NULL;
912         return &run_request[request - REQ_NONE - 1];
915 static void
916 add_builtin_run_requests(void)
918         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
919         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
920         const char *commit[] = { "git", "commit", NULL };
921         const char *gc[] = { "git", "gc", NULL };
922         struct run_request reqs[] = {
923                 { KEYMAP_MAIN,    'C', cherry_pick },
924                 { KEYMAP_STATUS,  'C', commit },
925                 { KEYMAP_BRANCH,  'C', checkout },
926                 { KEYMAP_GENERIC, 'G', gc },
927         };
928         int i;
930         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
931                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
933                 if (req != reqs[i].key)
934                         continue;
935                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
936                 if (req != REQ_NONE)
937                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
938         }
941 /*
942  * User config file handling.
943  */
945 #define OPT_ERR_INFO \
946         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
947         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
948         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
949         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
950         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
951         OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
952         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
953         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
954         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
955         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
956         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
957         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
958         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
959         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
960         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
961         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
962         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
964 enum option_code {
965 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
966         OPT_ERR_INFO
967 #undef  OPT_ERR_
968         OPT_OK
969 };
971 static const char *option_errors[] = {
972 #define OPT_ERR_(name, msg) msg
973         OPT_ERR_INFO
974 #undef  OPT_ERR_
975 };
977 static const struct enum_map color_map[] = {
978 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
979         COLOR_MAP(DEFAULT),
980         COLOR_MAP(BLACK),
981         COLOR_MAP(BLUE),
982         COLOR_MAP(CYAN),
983         COLOR_MAP(GREEN),
984         COLOR_MAP(MAGENTA),
985         COLOR_MAP(RED),
986         COLOR_MAP(WHITE),
987         COLOR_MAP(YELLOW),
988 };
990 static const struct enum_map attr_map[] = {
991 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
992         ATTR_MAP(NORMAL),
993         ATTR_MAP(BLINK),
994         ATTR_MAP(BOLD),
995         ATTR_MAP(DIM),
996         ATTR_MAP(REVERSE),
997         ATTR_MAP(STANDOUT),
998         ATTR_MAP(UNDERLINE),
999 };
1001 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
1003 static enum option_code
1004 parse_step(double *opt, const char *arg)
1006         *opt = atoi(arg);
1007         if (!strchr(arg, '%'))
1008                 return OPT_OK;
1010         /* "Shift down" so 100% and 1 does not conflict. */
1011         *opt = (*opt - 1) / 100;
1012         if (*opt >= 1.0) {
1013                 *opt = 0.99;
1014                 return OPT_ERR_INVALID_STEP_VALUE;
1015         }
1016         if (*opt < 0.0) {
1017                 *opt = 1;
1018                 return OPT_ERR_INVALID_STEP_VALUE;
1019         }
1020         return OPT_OK;
1023 static enum option_code
1024 parse_int(int *opt, const char *arg, int min, int max)
1026         int value = atoi(arg);
1028         if (min <= value && value <= max) {
1029                 *opt = value;
1030                 return OPT_OK;
1031         }
1033         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1036 static bool
1037 set_color(int *color, const char *name)
1039         if (map_enum(color, color_map, name))
1040                 return TRUE;
1041         if (!prefixcmp(name, "color"))
1042                 return parse_int(color, name + 5, 0, 255) == OK;
1043         return FALSE;
1046 /* Wants: object fgcolor bgcolor [attribute] */
1047 static enum option_code
1048 option_color_command(int argc, const char *argv[])
1050         struct line_info *info;
1052         if (argc < 3)
1053                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1055         info = get_line_info(argv[0]);
1056         if (!info) {
1057                 static const struct enum_map obsolete[] = {
1058                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1059                         ENUM_MAP("main-date",   LINE_DATE),
1060                         ENUM_MAP("main-author", LINE_AUTHOR),
1061                 };
1062                 int index;
1064                 if (!map_enum(&index, obsolete, argv[0]))
1065                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1066                 info = &line_info[index];
1067         }
1069         if (!set_color(&info->fg, argv[1]) ||
1070             !set_color(&info->bg, argv[2]))
1071                 return OPT_ERR_UNKNOWN_COLOR;
1073         info->attr = 0;
1074         while (argc-- > 3) {
1075                 int attr;
1077                 if (!set_attribute(&attr, argv[argc]))
1078                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1079                 info->attr |= attr;
1080         }
1082         return OPT_OK;
1085 static enum option_code
1086 parse_bool(bool *opt, const char *arg)
1088         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1089                 ? TRUE : FALSE;
1090         return OPT_OK;
1093 static enum option_code
1094 parse_enum_do(unsigned int *opt, const char *arg,
1095               const struct enum_map *map, size_t map_size)
1097         bool is_true;
1099         assert(map_size > 1);
1101         if (map_enum_do(map, map_size, (int *) opt, arg))
1102                 return OPT_OK;
1104         parse_bool(&is_true, arg);
1105         *opt = is_true ? map[1].value : map[0].value;
1106         return OPT_OK;
1109 #define parse_enum(opt, arg, map) \
1110         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1112 static enum option_code
1113 parse_string(char *opt, const char *arg, size_t optsize)
1115         int arglen = strlen(arg);
1117         switch (arg[0]) {
1118         case '\"':
1119         case '\'':
1120                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1121                         return OPT_ERR_UNMATCHED_QUOTATION;
1122                 arg += 1; arglen -= 2;
1123         default:
1124                 string_ncopy_do(opt, optsize, arg, arglen);
1125                 return OPT_OK;
1126         }
1129 static enum option_code
1130 parse_args(const char ***args, const char *argv[])
1132         if (*args == NULL && !argv_copy(args, argv))
1133                 return OPT_ERR_OUT_OF_MEMORY;
1134         return OPT_OK;
1137 /* Wants: name = value */
1138 static enum option_code
1139 option_set_command(int argc, const char *argv[])
1141         if (argc < 3)
1142                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1144         if (strcmp(argv[1], "="))
1145                 return OPT_ERR_NO_VALUE_ASSIGNED;
1147         if (!strcmp(argv[0], "blame-options"))
1148                 return parse_args(&opt_blame_argv, argv + 2);
1150         if (argc != 3)
1151                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1153         if (!strcmp(argv[0], "show-author"))
1154                 return parse_enum(&opt_author, argv[2], author_map);
1156         if (!strcmp(argv[0], "show-date"))
1157                 return parse_enum(&opt_date, argv[2], date_map);
1159         if (!strcmp(argv[0], "show-rev-graph"))
1160                 return parse_bool(&opt_rev_graph, argv[2]);
1162         if (!strcmp(argv[0], "show-refs"))
1163                 return parse_bool(&opt_show_refs, argv[2]);
1165         if (!strcmp(argv[0], "show-line-numbers"))
1166                 return parse_bool(&opt_line_number, argv[2]);
1168         if (!strcmp(argv[0], "line-graphics"))
1169                 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1171         if (!strcmp(argv[0], "line-number-interval"))
1172                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1174         if (!strcmp(argv[0], "author-width"))
1175                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1177         if (!strcmp(argv[0], "horizontal-scroll"))
1178                 return parse_step(&opt_hscroll, argv[2]);
1180         if (!strcmp(argv[0], "split-view-height"))
1181                 return parse_step(&opt_scale_split_view, argv[2]);
1183         if (!strcmp(argv[0], "tab-size"))
1184                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1186         if (!strcmp(argv[0], "commit-encoding"))
1187                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1189         if (!strcmp(argv[0], "status-untracked-dirs"))
1190                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1192         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1195 /* Wants: mode request key */
1196 static enum option_code
1197 option_bind_command(int argc, const char *argv[])
1199         enum request request;
1200         int keymap = -1;
1201         int key;
1203         if (argc < 3)
1204                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1206         if (!set_keymap(&keymap, argv[0]))
1207                 return OPT_ERR_UNKNOWN_KEY_MAP;
1209         key = get_key_value(argv[1]);
1210         if (key == ERR)
1211                 return OPT_ERR_UNKNOWN_KEY;
1213         request = get_request(argv[2]);
1214         if (request == REQ_UNKNOWN) {
1215                 static const struct enum_map obsolete[] = {
1216                         ENUM_MAP("cherry-pick",         REQ_NONE),
1217                         ENUM_MAP("screen-resize",       REQ_NONE),
1218                         ENUM_MAP("tree-parent",         REQ_PARENT),
1219                 };
1220                 int alias;
1222                 if (map_enum(&alias, obsolete, argv[2])) {
1223                         if (alias != REQ_NONE)
1224                                 add_keybinding(keymap, alias, key);
1225                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1226                 }
1227         }
1228         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1229                 request = add_run_request(keymap, key, argv + 2);
1230         if (request == REQ_UNKNOWN)
1231                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1233         add_keybinding(keymap, request, key);
1235         return OPT_OK;
1238 static enum option_code
1239 set_option(const char *opt, char *value)
1241         const char *argv[SIZEOF_ARG];
1242         int argc = 0;
1244         if (!argv_from_string(argv, &argc, value))
1245                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1247         if (!strcmp(opt, "color"))
1248                 return option_color_command(argc, argv);
1250         if (!strcmp(opt, "set"))
1251                 return option_set_command(argc, argv);
1253         if (!strcmp(opt, "bind"))
1254                 return option_bind_command(argc, argv);
1256         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1259 struct config_state {
1260         int lineno;
1261         bool errors;
1262 };
1264 static int
1265 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1267         struct config_state *config = data;
1268         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1270         config->lineno++;
1272         /* Check for comment markers, since read_properties() will
1273          * only ensure opt and value are split at first " \t". */
1274         optlen = strcspn(opt, "#");
1275         if (optlen == 0)
1276                 return OK;
1278         if (opt[optlen] == 0) {
1279                 /* Look for comment endings in the value. */
1280                 size_t len = strcspn(value, "#");
1282                 if (len < valuelen) {
1283                         valuelen = len;
1284                         value[valuelen] = 0;
1285                 }
1287                 status = set_option(opt, value);
1288         }
1290         if (status != OPT_OK) {
1291                 warn("Error on line %d, near '%.*s': %s",
1292                      config->lineno, (int) optlen, opt, option_errors[status]);
1293                 config->errors = TRUE;
1294         }
1296         /* Always keep going if errors are encountered. */
1297         return OK;
1300 static void
1301 load_option_file(const char *path)
1303         struct config_state config = { 0, FALSE };
1304         struct io io;
1306         /* It's OK that the file doesn't exist. */
1307         if (!io_open(&io, "%s", path))
1308                 return;
1310         if (io_load(&io, " \t", read_option, &config) == ERR ||
1311             config.errors == TRUE)
1312                 warn("Errors while loading %s.", path);
1315 static int
1316 load_options(void)
1318         const char *home = getenv("HOME");
1319         const char *tigrc_user = getenv("TIGRC_USER");
1320         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1321         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1322         char buf[SIZEOF_STR];
1324         if (!tigrc_system)
1325                 tigrc_system = SYSCONFDIR "/tigrc";
1326         load_option_file(tigrc_system);
1328         if (!tigrc_user) {
1329                 if (!home || !string_format(buf, "%s/.tigrc", home))
1330                         return ERR;
1331                 tigrc_user = buf;
1332         }
1333         load_option_file(tigrc_user);
1335         /* Add _after_ loading config files to avoid adding run requests
1336          * that conflict with keybindings. */
1337         add_builtin_run_requests();
1339         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1340                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1341                 int argc = 0;
1343                 if (!string_format(buf, "%s", tig_diff_opts) ||
1344                     !argv_from_string(diff_opts, &argc, buf))
1345                         die("TIG_DIFF_OPTS contains too many arguments");
1346                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1347                         die("Failed to format TIG_DIFF_OPTS arguments");
1348         }
1350         return OK;
1354 /*
1355  * The viewer
1356  */
1358 struct view;
1359 struct view_ops;
1361 /* The display array of active views and the index of the current view. */
1362 static struct view *display[2];
1363 static WINDOW *display_win[2];
1364 static WINDOW *display_title[2];
1365 static unsigned int current_view;
1367 #define foreach_displayed_view(view, i) \
1368         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1370 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1372 /* Current head and commit ID */
1373 static char ref_blob[SIZEOF_REF]        = "";
1374 static char ref_commit[SIZEOF_REF]      = "HEAD";
1375 static char ref_head[SIZEOF_REF]        = "HEAD";
1376 static char ref_branch[SIZEOF_REF]      = "";
1378 enum view_type {
1379         VIEW_MAIN,
1380         VIEW_DIFF,
1381         VIEW_LOG,
1382         VIEW_TREE,
1383         VIEW_BLOB,
1384         VIEW_BLAME,
1385         VIEW_BRANCH,
1386         VIEW_HELP,
1387         VIEW_PAGER,
1388         VIEW_STATUS,
1389         VIEW_STAGE,
1390 };
1392 struct view {
1393         enum view_type type;    /* View type */
1394         const char *name;       /* View name */
1395         const char *id;         /* Points to either of ref_{head,commit,blob} */
1397         struct view_ops *ops;   /* View operations */
1399         enum keymap keymap;     /* What keymap does this view have */
1400         bool git_dir;           /* Whether the view requires a git directory. */
1402         char ref[SIZEOF_REF];   /* Hovered commit reference */
1403         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1405         int height, width;      /* The width and height of the main window */
1406         WINDOW *win;            /* The main window */
1408         /* Navigation */
1409         unsigned long offset;   /* Offset of the window top */
1410         unsigned long yoffset;  /* Offset from the window side. */
1411         unsigned long lineno;   /* Current line number */
1412         unsigned long p_offset; /* Previous offset of the window top */
1413         unsigned long p_yoffset;/* Previous offset from the window side */
1414         unsigned long p_lineno; /* Previous current line number */
1415         bool p_restore;         /* Should the previous position be restored. */
1417         /* Searching */
1418         char grep[SIZEOF_STR];  /* Search string */
1419         regex_t *regex;         /* Pre-compiled regexp */
1421         /* If non-NULL, points to the view that opened this view. If this view
1422          * is closed tig will switch back to the parent view. */
1423         struct view *parent;
1424         struct view *prev;
1426         /* Buffering */
1427         size_t lines;           /* Total number of lines */
1428         struct line *line;      /* Line index */
1429         unsigned int digits;    /* Number of digits in the lines member. */
1431         /* Drawing */
1432         struct line *curline;   /* Line currently being drawn. */
1433         enum line_type curtype; /* Attribute currently used for drawing. */
1434         unsigned long col;      /* Column when drawing. */
1435         bool has_scrolled;      /* View was scrolled. */
1437         /* Loading */
1438         const char **argv;      /* Shell command arguments. */
1439         const char *dir;        /* Directory from which to execute. */
1440         struct io io;
1441         struct io *pipe;
1442         time_t start_time;
1443         time_t update_secs;
1444 };
1446 enum open_flags {
1447         OPEN_DEFAULT = 0,       /* Use default view switching. */
1448         OPEN_SPLIT = 1,         /* Split current view. */
1449         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1450         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
1451         OPEN_PREPARED = 32,     /* Open already prepared command. */
1452         OPEN_EXTRA = 64,        /* Open extra data from command. */
1453 };
1455 struct view_ops {
1456         /* What type of content being displayed. Used in the title bar. */
1457         const char *type;
1458         /* Open and reads in all view content. */
1459         bool (*open)(struct view *view, enum open_flags flags);
1460         /* Read one line; updates view->line. */
1461         bool (*read)(struct view *view, char *data);
1462         /* Draw one line; @lineno must be < view->height. */
1463         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1464         /* Depending on view handle a special requests. */
1465         enum request (*request)(struct view *view, enum request request, struct line *line);
1466         /* Search for regexp in a line. */
1467         bool (*grep)(struct view *view, struct line *line);
1468         /* Select line */
1469         void (*select)(struct view *view, struct line *line);
1470 };
1472 static struct view_ops blame_ops;
1473 static struct view_ops blob_ops;
1474 static struct view_ops diff_ops;
1475 static struct view_ops help_ops;
1476 static struct view_ops log_ops;
1477 static struct view_ops main_ops;
1478 static struct view_ops pager_ops;
1479 static struct view_ops stage_ops;
1480 static struct view_ops status_ops;
1481 static struct view_ops tree_ops;
1482 static struct view_ops branch_ops;
1484 #define VIEW_STR(type, name, ref, ops, map, git) \
1485         { type, name, ref, ops, map, git }
1487 #define VIEW_(id, name, ops, git, ref) \
1488         VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1490 static struct view views[] = {
1491         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1492         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1493         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1494         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1495         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1496         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1497         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1498         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1499         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1500         VIEW_(STATUS, "status", &status_ops, TRUE,  ""),
1501         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1502 };
1504 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1506 #define foreach_view(view, i) \
1507         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1509 #define view_is_displayed(view) \
1510         (view == display[0] || view == display[1])
1512 static enum request
1513 view_request(struct view *view, enum request request)
1515         if (!view || !view->lines)
1516                 return request;
1517         return view->ops->request(view, request, &view->line[view->lineno]);
1521 /*
1522  * View drawing.
1523  */
1525 static inline void
1526 set_view_attr(struct view *view, enum line_type type)
1528         if (!view->curline->selected && view->curtype != type) {
1529                 (void) wattrset(view->win, get_line_attr(type));
1530                 wchgat(view->win, -1, 0, type, NULL);
1531                 view->curtype = type;
1532         }
1535 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1537 static bool
1538 draw_chars(struct view *view, enum line_type type, const char *string,
1539            int max_len, bool use_tilde)
1541         static char out_buffer[BUFSIZ * 2];
1542         int len = 0;
1543         int col = 0;
1544         int trimmed = FALSE;
1545         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1547         if (max_len <= 0)
1548                 return VIEW_MAX_LEN(view) <= 0;
1550         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1552         set_view_attr(view, type);
1553         if (len > 0) {
1554                 if (opt_iconv_out != ICONV_NONE) {
1555                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1556                         size_t inlen = len + 1;
1558                         char *outbuf = out_buffer;
1559                         size_t outlen = sizeof(out_buffer);
1561                         size_t ret;
1563                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1564                         if (ret != (size_t) -1) {
1565                                 string = out_buffer;
1566                                 len = sizeof(out_buffer) - outlen;
1567                         }
1568                 }
1570                 waddnstr(view->win, string, len);
1572                 if (trimmed && use_tilde) {
1573                         set_view_attr(view, LINE_DELIMITER);
1574                         waddch(view->win, '~');
1575                         col++;
1576                 }
1577         }
1579         view->col += col;
1580         return VIEW_MAX_LEN(view) <= 0;
1583 static bool
1584 draw_space(struct view *view, enum line_type type, int max, int spaces)
1586         static char space[] = "                    ";
1588         spaces = MIN(max, spaces);
1590         while (spaces > 0) {
1591                 int len = MIN(spaces, sizeof(space) - 1);
1593                 if (draw_chars(view, type, space, len, FALSE))
1594                         return TRUE;
1595                 spaces -= len;
1596         }
1598         return VIEW_MAX_LEN(view) <= 0;
1601 static bool
1602 draw_text(struct view *view, enum line_type type, const char *string)
1604         char text[SIZEOF_STR];
1606         do {
1607                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1609                 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1610                         return TRUE;
1611                 string += pos;
1612         } while (*string);
1614         return VIEW_MAX_LEN(view) <= 0;
1617 static bool
1618 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1620         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1621         int max = VIEW_MAX_LEN(view);
1622         int i;
1624         if (max < size)
1625                 size = max;
1627         set_view_attr(view, type);
1628         /* Using waddch() instead of waddnstr() ensures that
1629          * they'll be rendered correctly for the cursor line. */
1630         for (i = skip; i < size; i++)
1631                 waddch(view->win, graphic[i]);
1633         view->col += size;
1634         if (separator) {
1635                 if (size < max && skip <= size)
1636                         waddch(view->win, ' ');
1637                 view->col++;
1638         }
1640         return VIEW_MAX_LEN(view) <= 0;
1643 static bool
1644 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1646         int max = MIN(VIEW_MAX_LEN(view), len);
1647         int col = view->col;
1649         if (!text) 
1650                 return draw_space(view, type, max, max);
1652         return draw_chars(view, type, text, max - 1, trim)
1653             || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1656 static bool
1657 draw_date(struct view *view, struct time *time)
1659         const char *date = mkdate(time, opt_date);
1660         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1662         if (opt_date == DATE_NO)
1663                 return FALSE;
1665         return draw_field(view, LINE_DATE, date, cols, FALSE);
1668 static bool
1669 draw_author(struct view *view, const char *author)
1671         bool trim = author_trim(opt_author_cols);
1672         const char *text = mkauthor(author, opt_author_cols, opt_author);
1674         return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1677 static bool
1678 draw_mode(struct view *view, mode_t mode)
1680         const char *str;
1682         if (S_ISDIR(mode))
1683                 str = "drwxr-xr-x";
1684         else if (S_ISLNK(mode))
1685                 str = "lrwxrwxrwx";
1686         else if (S_ISGITLINK(mode))
1687                 str = "m---------";
1688         else if (S_ISREG(mode) && mode & S_IXUSR)
1689                 str = "-rwxr-xr-x";
1690         else if (S_ISREG(mode))
1691                 str = "-rw-r--r--";
1692         else
1693                 str = "----------";
1695         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1698 static bool
1699 draw_lineno(struct view *view, unsigned int lineno)
1701         char number[10];
1702         int digits3 = view->digits < 3 ? 3 : view->digits;
1703         int max = MIN(VIEW_MAX_LEN(view), digits3);
1704         char *text = NULL;
1705         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1707         lineno += view->offset + 1;
1708         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1709                 static char fmt[] = "%1ld";
1711                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1712                 if (string_format(number, fmt, lineno))
1713                         text = number;
1714         }
1715         if (text)
1716                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1717         else
1718                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1719         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1722 static bool
1723 draw_refs(struct view *view, struct ref_list *refs)
1725         size_t i;
1727         if (!opt_show_refs || !refs)
1728                 return FALSE;
1730         for (i = 0; i < refs->size; i++) {
1731                 struct ref *ref = refs->refs[i];
1732                 enum line_type type;
1734                 if (ref->head)
1735                         type = LINE_MAIN_HEAD;
1736                 else if (ref->ltag)
1737                         type = LINE_MAIN_LOCAL_TAG;
1738                 else if (ref->tag)
1739                         type = LINE_MAIN_TAG;
1740                 else if (ref->tracked)
1741                         type = LINE_MAIN_TRACKED;
1742                 else if (ref->remote)
1743                         type = LINE_MAIN_REMOTE;
1744                 else
1745                         type = LINE_MAIN_REF;
1747                 if (draw_text(view, type, "[") ||
1748                     draw_text(view, type, ref->name) ||
1749                     draw_text(view, type, "]"))
1750                         return TRUE;
1752                 if (draw_text(view, LINE_DEFAULT, " "))
1753                         return TRUE;
1754         }
1756         return FALSE;
1759 static bool
1760 draw_view_line(struct view *view, unsigned int lineno)
1762         struct line *line;
1763         bool selected = (view->offset + lineno == view->lineno);
1765         assert(view_is_displayed(view));
1767         if (view->offset + lineno >= view->lines)
1768                 return FALSE;
1770         line = &view->line[view->offset + lineno];
1772         wmove(view->win, lineno, 0);
1773         if (line->cleareol)
1774                 wclrtoeol(view->win);
1775         view->col = 0;
1776         view->curline = line;
1777         view->curtype = LINE_NONE;
1778         line->selected = FALSE;
1779         line->dirty = line->cleareol = 0;
1781         if (selected) {
1782                 set_view_attr(view, LINE_CURSOR);
1783                 line->selected = TRUE;
1784                 view->ops->select(view, line);
1785         }
1787         return view->ops->draw(view, line, lineno);
1790 static void
1791 redraw_view_dirty(struct view *view)
1793         bool dirty = FALSE;
1794         int lineno;
1796         for (lineno = 0; lineno < view->height; lineno++) {
1797                 if (view->offset + lineno >= view->lines)
1798                         break;
1799                 if (!view->line[view->offset + lineno].dirty)
1800                         continue;
1801                 dirty = TRUE;
1802                 if (!draw_view_line(view, lineno))
1803                         break;
1804         }
1806         if (!dirty)
1807                 return;
1808         wnoutrefresh(view->win);
1811 static void
1812 redraw_view_from(struct view *view, int lineno)
1814         assert(0 <= lineno && lineno < view->height);
1816         for (; lineno < view->height; lineno++) {
1817                 if (!draw_view_line(view, lineno))
1818                         break;
1819         }
1821         wnoutrefresh(view->win);
1824 static void
1825 redraw_view(struct view *view)
1827         werase(view->win);
1828         redraw_view_from(view, 0);
1832 static void
1833 update_view_title(struct view *view)
1835         char buf[SIZEOF_STR];
1836         char state[SIZEOF_STR];
1837         size_t bufpos = 0, statelen = 0;
1838         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1840         assert(view_is_displayed(view));
1842         if (view->type != VIEW_STATUS && view->lines) {
1843                 unsigned int view_lines = view->offset + view->height;
1844                 unsigned int lines = view->lines
1845                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1846                                    : 0;
1848                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1849                                    view->ops->type,
1850                                    view->lineno + 1,
1851                                    view->lines,
1852                                    lines);
1854         }
1856         if (view->pipe) {
1857                 time_t secs = time(NULL) - view->start_time;
1859                 /* Three git seconds are a long time ... */
1860                 if (secs > 2)
1861                         string_format_from(state, &statelen, " loading %lds", secs);
1862         }
1864         string_format_from(buf, &bufpos, "[%s]", view->name);
1865         if (*view->ref && bufpos < view->width) {
1866                 size_t refsize = strlen(view->ref);
1867                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1869                 if (minsize < view->width)
1870                         refsize = view->width - minsize + 7;
1871                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1872         }
1874         if (statelen && bufpos < view->width) {
1875                 string_format_from(buf, &bufpos, "%s", state);
1876         }
1878         if (view == display[current_view])
1879                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1880         else
1881                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1883         mvwaddnstr(window, 0, 0, buf, bufpos);
1884         wclrtoeol(window);
1885         wnoutrefresh(window);
1888 static int
1889 apply_step(double step, int value)
1891         if (step >= 1)
1892                 return (int) step;
1893         value *= step + 0.01;
1894         return value ? value : 1;
1897 static void
1898 resize_display(void)
1900         int offset, i;
1901         struct view *base = display[0];
1902         struct view *view = display[1] ? display[1] : display[0];
1904         /* Setup window dimensions */
1906         getmaxyx(stdscr, base->height, base->width);
1908         /* Make room for the status window. */
1909         base->height -= 1;
1911         if (view != base) {
1912                 /* Horizontal split. */
1913                 view->width   = base->width;
1914                 view->height  = apply_step(opt_scale_split_view, base->height);
1915                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1916                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1917                 base->height -= view->height;
1919                 /* Make room for the title bar. */
1920                 view->height -= 1;
1921         }
1923         /* Make room for the title bar. */
1924         base->height -= 1;
1926         offset = 0;
1928         foreach_displayed_view (view, i) {
1929                 if (!display_win[i]) {
1930                         display_win[i] = newwin(view->height, view->width, offset, 0);
1931                         if (!display_win[i])
1932                                 die("Failed to create %s view", view->name);
1934                         scrollok(display_win[i], FALSE);
1936                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1937                         if (!display_title[i])
1938                                 die("Failed to create title window");
1940                 } else {
1941                         wresize(display_win[i], view->height, view->width);
1942                         mvwin(display_win[i],   offset, 0);
1943                         mvwin(display_title[i], offset + view->height, 0);
1944                 }
1946                 view->win = display_win[i];
1948                 offset += view->height + 1;
1949         }
1952 static void
1953 redraw_display(bool clear)
1955         struct view *view;
1956         int i;
1958         foreach_displayed_view (view, i) {
1959                 if (clear)
1960                         wclear(view->win);
1961                 redraw_view(view);
1962                 update_view_title(view);
1963         }
1967 /*
1968  * Option management
1969  */
1971 #define TOGGLE_MENU \
1972         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1973         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1974         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1975         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1976         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1977         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1979 static void
1980 toggle_option(enum request request)
1982         const struct {
1983                 enum request request;
1984                 const struct enum_map *map;
1985                 size_t map_size;
1986         } data[] = {            
1987 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1988                 TOGGLE_MENU
1989 #undef  TOGGLE_
1990         };
1991         const struct menu_item menu[] = {
1992 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1993                 TOGGLE_MENU
1994 #undef  TOGGLE_
1995                 { 0 }
1996         };
1997         int i = 0;
1999         if (request == REQ_OPTIONS) {
2000                 if (!prompt_menu("Toggle option", menu, &i))
2001                         return;
2002         } else {
2003                 while (i < ARRAY_SIZE(data) && data[i].request != request)
2004                         i++;
2005                 if (i >= ARRAY_SIZE(data))
2006                         die("Invalid request (%d)", request);
2007         }
2009         if (data[i].map != NULL) {
2010                 unsigned int *opt = menu[i].data;
2012                 *opt = (*opt + 1) % data[i].map_size;
2013                 redraw_display(FALSE);
2014                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2016         } else {
2017                 bool *option = menu[i].data;
2019                 *option = !*option;
2020                 redraw_display(FALSE);
2021                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2022         }
2025 static void
2026 maximize_view(struct view *view, bool redraw)
2028         memset(display, 0, sizeof(display));
2029         current_view = 0;
2030         display[current_view] = view;
2031         resize_display();
2032         if (redraw) {
2033                 redraw_display(FALSE);
2034                 report("");
2035         }
2039 /*
2040  * Navigation
2041  */
2043 static bool
2044 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2046         if (lineno >= view->lines)
2047                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2049         if (offset > lineno || offset + view->height <= lineno) {
2050                 unsigned long half = view->height / 2;
2052                 if (lineno > half)
2053                         offset = lineno - half;
2054                 else
2055                         offset = 0;
2056         }
2058         if (offset != view->offset || lineno != view->lineno) {
2059                 view->offset = offset;
2060                 view->lineno = lineno;
2061                 return TRUE;
2062         }
2064         return FALSE;
2067 /* Scrolling backend */
2068 static void
2069 do_scroll_view(struct view *view, int lines)
2071         bool redraw_current_line = FALSE;
2073         /* The rendering expects the new offset. */
2074         view->offset += lines;
2076         assert(0 <= view->offset && view->offset < view->lines);
2077         assert(lines);
2079         /* Move current line into the view. */
2080         if (view->lineno < view->offset) {
2081                 view->lineno = view->offset;
2082                 redraw_current_line = TRUE;
2083         } else if (view->lineno >= view->offset + view->height) {
2084                 view->lineno = view->offset + view->height - 1;
2085                 redraw_current_line = TRUE;
2086         }
2088         assert(view->offset <= view->lineno && view->lineno < view->lines);
2090         /* Redraw the whole screen if scrolling is pointless. */
2091         if (view->height < ABS(lines)) {
2092                 redraw_view(view);
2094         } else {
2095                 int line = lines > 0 ? view->height - lines : 0;
2096                 int end = line + ABS(lines);
2098                 scrollok(view->win, TRUE);
2099                 wscrl(view->win, lines);
2100                 scrollok(view->win, FALSE);
2102                 while (line < end && draw_view_line(view, line))
2103                         line++;
2105                 if (redraw_current_line)
2106                         draw_view_line(view, view->lineno - view->offset);
2107                 wnoutrefresh(view->win);
2108         }
2110         view->has_scrolled = TRUE;
2111         report("");
2114 /* Scroll frontend */
2115 static void
2116 scroll_view(struct view *view, enum request request)
2118         int lines = 1;
2120         assert(view_is_displayed(view));
2122         switch (request) {
2123         case REQ_SCROLL_FIRST_COL:
2124                 view->yoffset = 0;
2125                 redraw_view_from(view, 0);
2126                 report("");
2127                 return;
2128         case REQ_SCROLL_LEFT:
2129                 if (view->yoffset == 0) {
2130                         report("Cannot scroll beyond the first column");
2131                         return;
2132                 }
2133                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2134                         view->yoffset = 0;
2135                 else
2136                         view->yoffset -= apply_step(opt_hscroll, view->width);
2137                 redraw_view_from(view, 0);
2138                 report("");
2139                 return;
2140         case REQ_SCROLL_RIGHT:
2141                 view->yoffset += apply_step(opt_hscroll, view->width);
2142                 redraw_view(view);
2143                 report("");
2144                 return;
2145         case REQ_SCROLL_PAGE_DOWN:
2146                 lines = view->height;
2147         case REQ_SCROLL_LINE_DOWN:
2148                 if (view->offset + lines > view->lines)
2149                         lines = view->lines - view->offset;
2151                 if (lines == 0 || view->offset + view->height >= view->lines) {
2152                         report("Cannot scroll beyond the last line");
2153                         return;
2154                 }
2155                 break;
2157         case REQ_SCROLL_PAGE_UP:
2158                 lines = view->height;
2159         case REQ_SCROLL_LINE_UP:
2160                 if (lines > view->offset)
2161                         lines = view->offset;
2163                 if (lines == 0) {
2164                         report("Cannot scroll beyond the first line");
2165                         return;
2166                 }
2168                 lines = -lines;
2169                 break;
2171         default:
2172                 die("request %d not handled in switch", request);
2173         }
2175         do_scroll_view(view, lines);
2178 /* Cursor moving */
2179 static void
2180 move_view(struct view *view, enum request request)
2182         int scroll_steps = 0;
2183         int steps;
2185         switch (request) {
2186         case REQ_MOVE_FIRST_LINE:
2187                 steps = -view->lineno;
2188                 break;
2190         case REQ_MOVE_LAST_LINE:
2191                 steps = view->lines - view->lineno - 1;
2192                 break;
2194         case REQ_MOVE_PAGE_UP:
2195                 steps = view->height > view->lineno
2196                       ? -view->lineno : -view->height;
2197                 break;
2199         case REQ_MOVE_PAGE_DOWN:
2200                 steps = view->lineno + view->height >= view->lines
2201                       ? view->lines - view->lineno - 1 : view->height;
2202                 break;
2204         case REQ_MOVE_UP:
2205                 steps = -1;
2206                 break;
2208         case REQ_MOVE_DOWN:
2209                 steps = 1;
2210                 break;
2212         default:
2213                 die("request %d not handled in switch", request);
2214         }
2216         if (steps <= 0 && view->lineno == 0) {
2217                 report("Cannot move beyond the first line");
2218                 return;
2220         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2221                 report("Cannot move beyond the last line");
2222                 return;
2223         }
2225         /* Move the current line */
2226         view->lineno += steps;
2227         assert(0 <= view->lineno && view->lineno < view->lines);
2229         /* Check whether the view needs to be scrolled */
2230         if (view->lineno < view->offset ||
2231             view->lineno >= view->offset + view->height) {
2232                 scroll_steps = steps;
2233                 if (steps < 0 && -steps > view->offset) {
2234                         scroll_steps = -view->offset;
2236                 } else if (steps > 0) {
2237                         if (view->lineno == view->lines - 1 &&
2238                             view->lines > view->height) {
2239                                 scroll_steps = view->lines - view->offset - 1;
2240                                 if (scroll_steps >= view->height)
2241                                         scroll_steps -= view->height - 1;
2242                         }
2243                 }
2244         }
2246         if (!view_is_displayed(view)) {
2247                 view->offset += scroll_steps;
2248                 assert(0 <= view->offset && view->offset < view->lines);
2249                 view->ops->select(view, &view->line[view->lineno]);
2250                 return;
2251         }
2253         /* Repaint the old "current" line if we be scrolling */
2254         if (ABS(steps) < view->height)
2255                 draw_view_line(view, view->lineno - steps - view->offset);
2257         if (scroll_steps) {
2258                 do_scroll_view(view, scroll_steps);
2259                 return;
2260         }
2262         /* Draw the current line */
2263         draw_view_line(view, view->lineno - view->offset);
2265         wnoutrefresh(view->win);
2266         report("");
2270 /*
2271  * Searching
2272  */
2274 static void search_view(struct view *view, enum request request);
2276 static bool
2277 grep_text(struct view *view, const char *text[])
2279         regmatch_t pmatch;
2280         size_t i;
2282         for (i = 0; text[i]; i++)
2283                 if (*text[i] &&
2284                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2285                         return TRUE;
2286         return FALSE;
2289 static void
2290 select_view_line(struct view *view, unsigned long lineno)
2292         unsigned long old_lineno = view->lineno;
2293         unsigned long old_offset = view->offset;
2295         if (goto_view_line(view, view->offset, lineno)) {
2296                 if (view_is_displayed(view)) {
2297                         if (old_offset != view->offset) {
2298                                 redraw_view(view);
2299                         } else {
2300                                 draw_view_line(view, old_lineno - view->offset);
2301                                 draw_view_line(view, view->lineno - view->offset);
2302                                 wnoutrefresh(view->win);
2303                         }
2304                 } else {
2305                         view->ops->select(view, &view->line[view->lineno]);
2306                 }
2307         }
2310 static void
2311 find_next(struct view *view, enum request request)
2313         unsigned long lineno = view->lineno;
2314         int direction;
2316         if (!*view->grep) {
2317                 if (!*opt_search)
2318                         report("No previous search");
2319                 else
2320                         search_view(view, request);
2321                 return;
2322         }
2324         switch (request) {
2325         case REQ_SEARCH:
2326         case REQ_FIND_NEXT:
2327                 direction = 1;
2328                 break;
2330         case REQ_SEARCH_BACK:
2331         case REQ_FIND_PREV:
2332                 direction = -1;
2333                 break;
2335         default:
2336                 return;
2337         }
2339         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2340                 lineno += direction;
2342         /* Note, lineno is unsigned long so will wrap around in which case it
2343          * will become bigger than view->lines. */
2344         for (; lineno < view->lines; lineno += direction) {
2345                 if (view->ops->grep(view, &view->line[lineno])) {
2346                         select_view_line(view, lineno);
2347                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2348                         return;
2349                 }
2350         }
2352         report("No match found for '%s'", view->grep);
2355 static void
2356 search_view(struct view *view, enum request request)
2358         int regex_err;
2360         if (view->regex) {
2361                 regfree(view->regex);
2362                 *view->grep = 0;
2363         } else {
2364                 view->regex = calloc(1, sizeof(*view->regex));
2365                 if (!view->regex)
2366                         return;
2367         }
2369         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2370         if (regex_err != 0) {
2371                 char buf[SIZEOF_STR] = "unknown error";
2373                 regerror(regex_err, view->regex, buf, sizeof(buf));
2374                 report("Search failed: %s", buf);
2375                 return;
2376         }
2378         string_copy(view->grep, opt_search);
2380         find_next(view, request);
2383 /*
2384  * Incremental updating
2385  */
2387 static void
2388 reset_view(struct view *view)
2390         int i;
2392         for (i = 0; i < view->lines; i++)
2393                 free(view->line[i].data);
2394         free(view->line);
2396         view->p_offset = view->offset;
2397         view->p_yoffset = view->yoffset;
2398         view->p_lineno = view->lineno;
2400         view->line = NULL;
2401         view->offset = 0;
2402         view->yoffset = 0;
2403         view->lines  = 0;
2404         view->lineno = 0;
2405         view->vid[0] = 0;
2406         view->update_secs = 0;
2409 static const char *
2410 format_arg(const char *name)
2412         static struct {
2413                 const char *name;
2414                 size_t namelen;
2415                 const char *value;
2416                 const char *value_if_empty;
2417         } vars[] = {
2418 #define FORMAT_VAR(name, value, value_if_empty) \
2419         { name, STRING_SIZE(name), value, value_if_empty }
2420                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2421                 FORMAT_VAR("%(file)",           opt_file,       ""),
2422                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2423                 FORMAT_VAR("%(head)",           ref_head,       ""),
2424                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2425                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2426                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2427         };
2428         int i;
2430         for (i = 0; i < ARRAY_SIZE(vars); i++)
2431                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2432                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2434         report("Unknown replacement: `%s`", name);
2435         return NULL;
2438 static bool
2439 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2441         char buf[SIZEOF_STR];
2442         int argc;
2444         argv_free(*dst_argv);
2446         for (argc = 0; src_argv[argc]; argc++) {
2447                 const char *arg = src_argv[argc];
2448                 size_t bufpos = 0;
2450                 if (!strcmp(arg, "%(fileargs)")) {
2451                         if (!argv_append_array(dst_argv, opt_file_argv))
2452                                 break;
2453                         continue;
2455                 } else if (!strcmp(arg, "%(diffargs)")) {
2456                         if (!argv_append_array(dst_argv, opt_diff_argv))
2457                                 break;
2458                         continue;
2460                 } else if (!strcmp(arg, "%(blameargs)")) {
2461                         if (!argv_append_array(dst_argv, opt_blame_argv))
2462                                 break;
2463                         continue;
2465                 } else if (!strcmp(arg, "%(revargs)") ||
2466                            (first && !strcmp(arg, "%(commit)"))) {
2467                         if (!argv_append_array(dst_argv, opt_rev_argv))
2468                                 break;
2469                         continue;
2470                 }
2472                 while (arg) {
2473                         char *next = strstr(arg, "%(");
2474                         int len = next - arg;
2475                         const char *value;
2477                         if (!next) {
2478                                 len = strlen(arg);
2479                                 value = "";
2481                         } else {
2482                                 value = format_arg(next);
2484                                 if (!value) {
2485                                         return FALSE;
2486                                 }
2487                         }
2489                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2490                                 return FALSE;
2492                         arg = next ? strchr(next, ')') + 1 : NULL;
2493                 }
2495                 if (!argv_append(dst_argv, buf))
2496                         break;
2497         }
2499         return src_argv[argc] == NULL;
2502 static bool
2503 restore_view_position(struct view *view)
2505         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2506                 return FALSE;
2508         /* Changing the view position cancels the restoring. */
2509         /* FIXME: Changing back to the first line is not detected. */
2510         if (view->offset != 0 || view->lineno != 0) {
2511                 view->p_restore = FALSE;
2512                 return FALSE;
2513         }
2515         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2516             view_is_displayed(view))
2517                 werase(view->win);
2519         view->yoffset = view->p_yoffset;
2520         view->p_restore = FALSE;
2522         return TRUE;
2525 static void
2526 end_update(struct view *view, bool force)
2528         if (!view->pipe)
2529                 return;
2530         while (!view->ops->read(view, NULL))
2531                 if (!force)
2532                         return;
2533         if (force)
2534                 io_kill(view->pipe);
2535         io_done(view->pipe);
2536         view->pipe = NULL;
2539 static void
2540 setup_update(struct view *view, const char *vid)
2542         reset_view(view);
2543         string_copy_rev(view->vid, vid);
2544         view->pipe = &view->io;
2545         view->start_time = time(NULL);
2548 static bool
2549 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2551         bool extra = !!(flags & (OPEN_EXTRA));
2552         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2553         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2555         if (!reload && !strcmp(view->vid, view->id))
2556                 return TRUE;
2558         if (view->pipe) {
2559                 if (extra)
2560                         io_done(view->pipe);
2561                 else
2562                         end_update(view, TRUE);
2563         }
2565         if (!refresh) {
2566                 view->dir = dir;
2567                 if (!format_argv(&view->argv, argv, !view->prev))
2568                         return FALSE;
2570                 /* Put the current ref_* value to the view title ref
2571                  * member. This is needed by the blob view. Most other
2572                  * views sets it automatically after loading because the
2573                  * first line is a commit line. */
2574                 string_copy_rev(view->ref, view->id);
2575         }
2577         if (view->argv && view->argv[0] &&
2578             !io_run(&view->io, IO_RD, view->dir, view->argv))
2579                 return FALSE;
2581         if (!extra)
2582                 setup_update(view, view->id);
2584         return TRUE;
2587 static bool
2588 view_open(struct view *view, enum open_flags flags)
2590         return begin_update(view, NULL, NULL, flags);
2593 static bool
2594 update_view(struct view *view)
2596         char out_buffer[BUFSIZ * 2];
2597         char *line;
2598         /* Clear the view and redraw everything since the tree sorting
2599          * might have rearranged things. */
2600         bool redraw = view->lines == 0;
2601         bool can_read = TRUE;
2603         if (!view->pipe)
2604                 return TRUE;
2606         if (!io_can_read(view->pipe, FALSE)) {
2607                 if (view->lines == 0 && view_is_displayed(view)) {
2608                         time_t secs = time(NULL) - view->start_time;
2610                         if (secs > 1 && secs > view->update_secs) {
2611                                 if (view->update_secs == 0)
2612                                         redraw_view(view);
2613                                 update_view_title(view);
2614                                 view->update_secs = secs;
2615                         }
2616                 }
2617                 return TRUE;
2618         }
2620         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2621                 if (opt_iconv_in != ICONV_NONE) {
2622                         ICONV_CONST char *inbuf = line;
2623                         size_t inlen = strlen(line) + 1;
2625                         char *outbuf = out_buffer;
2626                         size_t outlen = sizeof(out_buffer);
2628                         size_t ret;
2630                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2631                         if (ret != (size_t) -1)
2632                                 line = out_buffer;
2633                 }
2635                 if (!view->ops->read(view, line)) {
2636                         report("Allocation failure");
2637                         end_update(view, TRUE);
2638                         return FALSE;
2639                 }
2640         }
2642         {
2643                 unsigned long lines = view->lines;
2644                 int digits;
2646                 for (digits = 0; lines; digits++)
2647                         lines /= 10;
2649                 /* Keep the displayed view in sync with line number scaling. */
2650                 if (digits != view->digits) {
2651                         view->digits = digits;
2652                         if (opt_line_number || view->type == VIEW_BLAME)
2653                                 redraw = TRUE;
2654                 }
2655         }
2657         if (io_error(view->pipe)) {
2658                 report("Failed to read: %s", io_strerror(view->pipe));
2659                 end_update(view, TRUE);
2661         } else if (io_eof(view->pipe)) {
2662                 if (view_is_displayed(view))
2663                         report("");
2664                 end_update(view, FALSE);
2665         }
2667         if (restore_view_position(view))
2668                 redraw = TRUE;
2670         if (!view_is_displayed(view))
2671                 return TRUE;
2673         if (redraw)
2674                 redraw_view_from(view, 0);
2675         else
2676                 redraw_view_dirty(view);
2678         /* Update the title _after_ the redraw so that if the redraw picks up a
2679          * commit reference in view->ref it'll be available here. */
2680         update_view_title(view);
2681         return TRUE;
2684 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2686 static struct line *
2687 add_line_data(struct view *view, void *data, enum line_type type)
2689         struct line *line;
2691         if (!realloc_lines(&view->line, view->lines, 1))
2692                 return NULL;
2694         line = &view->line[view->lines++];
2695         memset(line, 0, sizeof(*line));
2696         line->type = type;
2697         line->data = data;
2698         line->dirty = 1;
2700         return line;
2703 static struct line *
2704 add_line_text(struct view *view, const char *text, enum line_type type)
2706         char *data = text ? strdup(text) : NULL;
2708         return data ? add_line_data(view, data, type) : NULL;
2711 static struct line *
2712 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2714         char buf[SIZEOF_STR];
2715         va_list args;
2717         va_start(args, fmt);
2718         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2719                 buf[0] = 0;
2720         va_end(args);
2722         return buf[0] ? add_line_text(view, buf, type) : NULL;
2725 /*
2726  * View opening
2727  */
2729 static void
2730 load_view(struct view *view, enum open_flags flags)
2732         if (view->pipe)
2733                 end_update(view, TRUE);
2734         if (!view->ops->open(view, flags)) {
2735                 report("Failed to load %s view", view->name);
2736                 return;
2737         }
2738         restore_view_position(view);
2740         if (view->pipe && view->lines == 0) {
2741                 /* Clear the old view and let the incremental updating refill
2742                  * the screen. */
2743                 werase(view->win);
2744                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2745                 report("");
2746         } else if (view_is_displayed(view)) {
2747                 redraw_view(view);
2748                 report("");
2749         }
2752 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2754 static void
2755 split_view(struct view *prev, struct view *view)
2757         display[1] = view;
2758         current_view = 1;
2759         view->parent = prev;
2760         resize_display();
2762         if (prev->lineno - prev->offset >= prev->height) {
2763                 /* Take the title line into account. */
2764                 int lines = prev->lineno - prev->offset - prev->height + 1;
2766                 /* Scroll the view that was split if the current line is
2767                  * outside the new limited view. */
2768                 do_scroll_view(prev, lines);
2769         }
2771         if (view != prev && view_is_displayed(prev)) {
2772                 /* "Blur" the previous view. */
2773                 update_view_title(prev);
2774         }
2777 static void
2778 open_view(struct view *prev, enum request request, enum open_flags flags)
2780         bool split = !!(flags & OPEN_SPLIT);
2781         bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2782         struct view *view = VIEW(request);
2783         int nviews = displayed_views();
2785         assert(flags ^ OPEN_REFRESH);
2787         if (view == prev && nviews == 1 && !reload) {
2788                 report("Already in %s view", view->name);
2789                 return;
2790         }
2792         if (view->git_dir && !opt_git_dir[0]) {
2793                 report("The %s view is disabled in pager view", view->name);
2794                 return;
2795         }
2797         if (split) {
2798                 split_view(prev, view);
2799         } else {
2800                 maximize_view(view, FALSE);
2801         }
2803         /* No prev signals that this is the first loaded view. */
2804         if (prev && view != prev) {
2805                 view->prev = prev;
2806         }
2808         load_view(view, flags);
2811 static void
2812 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2814         enum request request = view - views + REQ_OFFSET + 1;
2816         if (view->pipe)
2817                 end_update(view, TRUE);
2818         view->dir = dir;
2819         
2820         if (!argv_copy(&view->argv, argv)) {
2821                 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2822         } else {
2823                 open_view(prev, request, flags | OPEN_PREPARED);
2824         }
2827 static void
2828 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2830         const char *file_argv[] = { opt_cdup, file , NULL };
2832         open_argv(prev, view, file_argv, opt_cdup, flags); 
2835 static void
2836 open_external_viewer(const char *argv[], const char *dir)
2838         def_prog_mode();           /* save current tty modes */
2839         endwin();                  /* restore original tty modes */
2840         io_run_fg(argv, dir);
2841         fprintf(stderr, "Press Enter to continue");
2842         getc(opt_tty);
2843         reset_prog_mode();
2844         redraw_display(TRUE);
2847 static void
2848 open_mergetool(const char *file)
2850         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2852         open_external_viewer(mergetool_argv, opt_cdup);
2855 static void
2856 open_editor(const char *file)
2858         const char *editor_argv[] = { "vi", file, NULL };
2859         const char *editor;
2861         editor = getenv("GIT_EDITOR");
2862         if (!editor && *opt_editor)
2863                 editor = opt_editor;
2864         if (!editor)
2865                 editor = getenv("VISUAL");
2866         if (!editor)
2867                 editor = getenv("EDITOR");
2868         if (!editor)
2869                 editor = "vi";
2871         editor_argv[0] = editor;
2872         open_external_viewer(editor_argv, opt_cdup);
2875 static void
2876 open_run_request(enum request request)
2878         struct run_request *req = get_run_request(request);
2879         const char **argv = NULL;
2881         if (!req) {
2882                 report("Unknown run request");
2883                 return;
2884         }
2886         if (format_argv(&argv, req->argv, FALSE))
2887                 open_external_viewer(argv, NULL);
2888         if (argv)
2889                 argv_free(argv);
2890         free(argv);
2893 /*
2894  * User request switch noodle
2895  */
2897 static int
2898 view_driver(struct view *view, enum request request)
2900         int i;
2902         if (request == REQ_NONE)
2903                 return TRUE;
2905         if (request > REQ_NONE) {
2906                 open_run_request(request);
2907                 view_request(view, REQ_REFRESH);
2908                 return TRUE;
2909         }
2911         request = view_request(view, request);
2912         if (request == REQ_NONE)
2913                 return TRUE;
2915         switch (request) {
2916         case REQ_MOVE_UP:
2917         case REQ_MOVE_DOWN:
2918         case REQ_MOVE_PAGE_UP:
2919         case REQ_MOVE_PAGE_DOWN:
2920         case REQ_MOVE_FIRST_LINE:
2921         case REQ_MOVE_LAST_LINE:
2922                 move_view(view, request);
2923                 break;
2925         case REQ_SCROLL_FIRST_COL:
2926         case REQ_SCROLL_LEFT:
2927         case REQ_SCROLL_RIGHT:
2928         case REQ_SCROLL_LINE_DOWN:
2929         case REQ_SCROLL_LINE_UP:
2930         case REQ_SCROLL_PAGE_DOWN:
2931         case REQ_SCROLL_PAGE_UP:
2932                 scroll_view(view, request);
2933                 break;
2935         case REQ_VIEW_BLAME:
2936                 if (!opt_file[0]) {
2937                         report("No file chosen, press %s to open tree view",
2938                                get_key(view->keymap, REQ_VIEW_TREE));
2939                         break;
2940                 }
2941                 open_view(view, request, OPEN_DEFAULT);
2942                 break;
2944         case REQ_VIEW_BLOB:
2945                 if (!ref_blob[0]) {
2946                         report("No file chosen, press %s to open tree view",
2947                                get_key(view->keymap, REQ_VIEW_TREE));
2948                         break;
2949                 }
2950                 open_view(view, request, OPEN_DEFAULT);
2951                 break;
2953         case REQ_VIEW_PAGER:
2954                 if (view == NULL) {
2955                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2956                                 die("Failed to open stdin");
2957                         open_view(view, request, OPEN_PREPARED);
2958                         break;
2959                 }
2961                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2962                         report("No pager content, press %s to run command from prompt",
2963                                get_key(view->keymap, REQ_PROMPT));
2964                         break;
2965                 }
2966                 open_view(view, request, OPEN_DEFAULT);
2967                 break;
2969         case REQ_VIEW_STAGE:
2970                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2971                         report("No stage content, press %s to open the status view and choose file",
2972                                get_key(view->keymap, REQ_VIEW_STATUS));
2973                         break;
2974                 }
2975                 open_view(view, request, OPEN_DEFAULT);
2976                 break;
2978         case REQ_VIEW_STATUS:
2979                 if (opt_is_inside_work_tree == FALSE) {
2980                         report("The status view requires a working tree");
2981                         break;
2982                 }
2983                 open_view(view, request, OPEN_DEFAULT);
2984                 break;
2986         case REQ_VIEW_MAIN:
2987         case REQ_VIEW_DIFF:
2988         case REQ_VIEW_LOG:
2989         case REQ_VIEW_TREE:
2990         case REQ_VIEW_HELP:
2991         case REQ_VIEW_BRANCH:
2992                 open_view(view, request, OPEN_DEFAULT);
2993                 break;
2995         case REQ_NEXT:
2996         case REQ_PREVIOUS:
2997                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2999                 if (view->parent) {
3000                         int line;
3002                         view = view->parent;
3003                         line = view->lineno;
3004                         move_view(view, request);
3005                         if (view_is_displayed(view))
3006                                 update_view_title(view);
3007                         if (line != view->lineno)
3008                                 view_request(view, REQ_ENTER);
3009                 } else {
3010                         move_view(view, request);
3011                 }
3012                 break;
3014         case REQ_VIEW_NEXT:
3015         {
3016                 int nviews = displayed_views();
3017                 int next_view = (current_view + 1) % nviews;
3019                 if (next_view == current_view) {
3020                         report("Only one view is displayed");
3021                         break;
3022                 }
3024                 current_view = next_view;
3025                 /* Blur out the title of the previous view. */
3026                 update_view_title(view);
3027                 report("");
3028                 break;
3029         }
3030         case REQ_REFRESH:
3031                 report("Refreshing is not yet supported for the %s view", view->name);
3032                 break;
3034         case REQ_MAXIMIZE:
3035                 if (displayed_views() == 2)
3036                         maximize_view(view, TRUE);
3037                 break;
3039         case REQ_OPTIONS:
3040         case REQ_TOGGLE_LINENO:
3041         case REQ_TOGGLE_DATE:
3042         case REQ_TOGGLE_AUTHOR:
3043         case REQ_TOGGLE_GRAPHIC:
3044         case REQ_TOGGLE_REV_GRAPH:
3045         case REQ_TOGGLE_REFS:
3046                 toggle_option(request);
3047                 break;
3049         case REQ_TOGGLE_SORT_FIELD:
3050         case REQ_TOGGLE_SORT_ORDER:
3051                 report("Sorting is not yet supported for the %s view", view->name);
3052                 break;
3054         case REQ_SEARCH:
3055         case REQ_SEARCH_BACK:
3056                 search_view(view, request);
3057                 break;
3059         case REQ_FIND_NEXT:
3060         case REQ_FIND_PREV:
3061                 find_next(view, request);
3062                 break;
3064         case REQ_STOP_LOADING:
3065                 foreach_view(view, i) {
3066                         if (view->pipe)
3067                                 report("Stopped loading the %s view", view->name),
3068                         end_update(view, TRUE);
3069                 }
3070                 break;
3072         case REQ_SHOW_VERSION:
3073                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3074                 return TRUE;
3076         case REQ_SCREEN_REDRAW:
3077                 redraw_display(TRUE);
3078                 break;
3080         case REQ_EDIT:
3081                 report("Nothing to edit");
3082                 break;
3084         case REQ_ENTER:
3085                 report("Nothing to enter");
3086                 break;
3088         case REQ_VIEW_CLOSE:
3089                 /* XXX: Mark closed views by letting view->prev point to the
3090                  * view itself. Parents to closed view should never be
3091                  * followed. */
3092                 if (view->prev && view->prev != view) {
3093                         maximize_view(view->prev, TRUE);
3094                         view->prev = view;
3095                         break;
3096                 }
3097                 /* Fall-through */
3098         case REQ_QUIT:
3099                 return FALSE;
3101         default:
3102                 report("Unknown key, press %s for help",
3103                        get_key(view->keymap, REQ_VIEW_HELP));
3104                 return TRUE;
3105         }
3107         return TRUE;
3111 /*
3112  * View backend utilities
3113  */
3115 enum sort_field {
3116         ORDERBY_NAME,
3117         ORDERBY_DATE,
3118         ORDERBY_AUTHOR,
3119 };
3121 struct sort_state {
3122         const enum sort_field *fields;
3123         size_t size, current;
3124         bool reverse;
3125 };
3127 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3128 #define get_sort_field(state) ((state).fields[(state).current])
3129 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3131 static void
3132 sort_view(struct view *view, enum request request, struct sort_state *state,
3133           int (*compare)(const void *, const void *))
3135         switch (request) {
3136         case REQ_TOGGLE_SORT_FIELD:
3137                 state->current = (state->current + 1) % state->size;
3138                 break;
3140         case REQ_TOGGLE_SORT_ORDER:
3141                 state->reverse = !state->reverse;
3142                 break;
3143         default:
3144                 die("Not a sort request");
3145         }
3147         qsort(view->line, view->lines, sizeof(*view->line), compare);
3148         redraw_view(view);
3151 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3153 /* Small author cache to reduce memory consumption. It uses binary
3154  * search to lookup or find place to position new entries. No entries
3155  * are ever freed. */
3156 static const char *
3157 get_author(const char *name)
3159         static const char **authors;
3160         static size_t authors_size;
3161         int from = 0, to = authors_size - 1;
3163         while (from <= to) {
3164                 size_t pos = (to + from) / 2;
3165                 int cmp = strcmp(name, authors[pos]);
3167                 if (!cmp)
3168                         return authors[pos];
3170                 if (cmp < 0)
3171                         to = pos - 1;
3172                 else
3173                         from = pos + 1;
3174         }
3176         if (!realloc_authors(&authors, authors_size, 1))
3177                 return NULL;
3178         name = strdup(name);
3179         if (!name)
3180                 return NULL;
3182         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3183         authors[from] = name;
3184         authors_size++;
3186         return name;
3189 static void
3190 parse_timesec(struct time *time, const char *sec)
3192         time->sec = (time_t) atol(sec);
3195 static void
3196 parse_timezone(struct time *time, const char *zone)
3198         long tz;
3200         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3201         tz += ('0' - zone[2]) * 60 * 60;
3202         tz += ('0' - zone[3]) * 60 * 10;
3203         tz += ('0' - zone[4]) * 60;
3205         if (zone[0] == '-')
3206                 tz = -tz;
3208         time->tz = tz;
3209         time->sec -= tz;
3212 /* Parse author lines where the name may be empty:
3213  *      author  <email@address.tld> 1138474660 +0100
3214  */
3215 static void
3216 parse_author_line(char *ident, const char **author, struct time *time)
3218         char *nameend = strchr(ident, '<');
3219         char *emailend = strchr(ident, '>');
3221         if (nameend && emailend)
3222                 *nameend = *emailend = 0;
3223         ident = chomp_string(ident);
3224         if (!*ident) {
3225                 if (nameend)
3226                         ident = chomp_string(nameend + 1);
3227                 if (!*ident)
3228                         ident = "Unknown";
3229         }
3231         *author = get_author(ident);
3233         /* Parse epoch and timezone */
3234         if (emailend && emailend[1] == ' ') {
3235                 char *secs = emailend + 2;
3236                 char *zone = strchr(secs, ' ');
3238                 parse_timesec(time, secs);
3240                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3241                         parse_timezone(time, zone + 1);
3242         }
3245 /*
3246  * Pager backend
3247  */
3249 static bool
3250 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3252         if (opt_line_number && draw_lineno(view, lineno))
3253                 return TRUE;
3255         draw_text(view, line->type, line->data);
3256         return TRUE;
3259 static bool
3260 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3262         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3263         char ref[SIZEOF_STR];
3265         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3266                 return TRUE;
3268         /* This is the only fatal call, since it can "corrupt" the buffer. */
3269         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3270                 return FALSE;
3272         return TRUE;
3275 static void
3276 add_pager_refs(struct view *view, struct line *line)
3278         char buf[SIZEOF_STR];
3279         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3280         struct ref_list *list;
3281         size_t bufpos = 0, i;
3282         const char *sep = "Refs: ";
3283         bool is_tag = FALSE;
3285         assert(line->type == LINE_COMMIT);
3287         list = get_ref_list(commit_id);
3288         if (!list) {
3289                 if (view->type == VIEW_DIFF)
3290                         goto try_add_describe_ref;
3291                 return;
3292         }
3294         for (i = 0; i < list->size; i++) {
3295                 struct ref *ref = list->refs[i];
3296                 const char *fmt = ref->tag    ? "%s[%s]" :
3297                                   ref->remote ? "%s<%s>" : "%s%s";
3299                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3300                         return;
3301                 sep = ", ";
3302                 if (ref->tag)
3303                         is_tag = TRUE;
3304         }
3306         if (!is_tag && view->type == VIEW_DIFF) {
3307 try_add_describe_ref:
3308                 /* Add <tag>-g<commit_id> "fake" reference. */
3309                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3310                         return;
3311         }
3313         if (bufpos == 0)
3314                 return;
3316         add_line_text(view, buf, LINE_PP_REFS);
3319 static bool
3320 pager_read(struct view *view, char *data)
3322         struct line *line;
3324         if (!data)
3325                 return TRUE;
3327         line = add_line_text(view, data, get_line_type(data));
3328         if (!line)
3329                 return FALSE;
3331         if (line->type == LINE_COMMIT &&
3332             (view->type == VIEW_DIFF ||
3333              view->type == VIEW_LOG))
3334                 add_pager_refs(view, line);
3336         return TRUE;
3339 static enum request
3340 pager_request(struct view *view, enum request request, struct line *line)
3342         int split = 0;
3344         if (request != REQ_ENTER)
3345                 return request;
3347         if (line->type == LINE_COMMIT &&
3348            (view->type == VIEW_LOG ||
3349             view->type == VIEW_PAGER)) {
3350                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3351                 split = 1;
3352         }
3354         /* Always scroll the view even if it was split. That way
3355          * you can use Enter to scroll through the log view and
3356          * split open each commit diff. */
3357         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3359         /* FIXME: A minor workaround. Scrolling the view will call report("")
3360          * but if we are scrolling a non-current view this won't properly
3361          * update the view title. */
3362         if (split)
3363                 update_view_title(view);
3365         return REQ_NONE;
3368 static bool
3369 pager_grep(struct view *view, struct line *line)
3371         const char *text[] = { line->data, NULL };
3373         return grep_text(view, text);
3376 static void
3377 pager_select(struct view *view, struct line *line)
3379         if (line->type == LINE_COMMIT) {
3380                 char *text = (char *)line->data + STRING_SIZE("commit ");
3382                 if (view->type != VIEW_PAGER)
3383                         string_copy_rev(view->ref, text);
3384                 string_copy_rev(ref_commit, text);
3385         }
3388 static struct view_ops pager_ops = {
3389         "line",
3390         view_open,
3391         pager_read,
3392         pager_draw,
3393         pager_request,
3394         pager_grep,
3395         pager_select,
3396 };
3398 static bool
3399 log_open(struct view *view, enum open_flags flags)
3401         static const char *log_argv[] = {
3402                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3403         };
3405         return begin_update(view, NULL, log_argv, flags);
3408 static enum request
3409 log_request(struct view *view, enum request request, struct line *line)
3411         switch (request) {
3412         case REQ_REFRESH:
3413                 load_refs();
3414                 refresh_view(view);
3415                 return REQ_NONE;
3416         default:
3417                 return pager_request(view, request, line);
3418         }
3421 static struct view_ops log_ops = {
3422         "line",
3423         log_open,
3424         pager_read,
3425         pager_draw,
3426         log_request,
3427         pager_grep,
3428         pager_select,
3429 };
3431 static bool
3432 diff_open(struct view *view, enum open_flags flags)
3434         static const char *diff_argv[] = {
3435                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3436                         "--patch-with-stat", "--find-copies-harder", "-C",
3437                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3438         };
3440         return begin_update(view, NULL, diff_argv, flags);
3443 static bool
3444 diff_read(struct view *view, char *data)
3446         if (!data) {
3447                 /* Fall back to retry if no diff will be shown. */
3448                 if (view->lines == 0 && opt_file_argv) {
3449                         int pos = argv_size(view->argv)
3450                                 - argv_size(opt_file_argv) - 1;
3452                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3453                                 for (; view->argv[pos]; pos++) {
3454                                         free((void *) view->argv[pos]);
3455                                         view->argv[pos] = NULL;
3456                                 }
3458                                 if (view->pipe)
3459                                         io_done(view->pipe);
3460                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3461                                         return FALSE;
3462                         }
3463                 }
3464                 return TRUE;
3465         }
3467         return pager_read(view, data);
3470 static struct view_ops diff_ops = {
3471         "line",
3472         diff_open,
3473         diff_read,
3474         pager_draw,
3475         pager_request,
3476         pager_grep,
3477         pager_select,
3478 };
3480 /*
3481  * Help backend
3482  */
3484 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3486 static bool
3487 help_open_keymap_title(struct view *view, enum keymap keymap)
3489         struct line *line;
3491         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3492                                help_keymap_hidden[keymap] ? '+' : '-',
3493                                enum_name(keymap_table[keymap]));
3494         if (line)
3495                 line->other = keymap;
3497         return help_keymap_hidden[keymap];
3500 static void
3501 help_open_keymap(struct view *view, enum keymap keymap)
3503         const char *group = NULL;
3504         char buf[SIZEOF_STR];
3505         size_t bufpos;
3506         bool add_title = TRUE;
3507         int i;
3509         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3510                 const char *key = NULL;
3512                 if (req_info[i].request == REQ_NONE)
3513                         continue;
3515                 if (!req_info[i].request) {
3516                         group = req_info[i].help;
3517                         continue;
3518                 }
3520                 key = get_keys(keymap, req_info[i].request, TRUE);
3521                 if (!key || !*key)
3522                         continue;
3524                 if (add_title && help_open_keymap_title(view, keymap))
3525                         return;
3526                 add_title = FALSE;
3528                 if (group) {
3529                         add_line_text(view, group, LINE_HELP_GROUP);
3530                         group = NULL;
3531                 }
3533                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3534                                 enum_name(req_info[i]), req_info[i].help);
3535         }
3537         group = "External commands:";
3539         for (i = 0; i < run_requests; i++) {
3540                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3541                 const char *key;
3542                 int argc;
3544                 if (!req || req->keymap != keymap)
3545                         continue;
3547                 key = get_key_name(req->key);
3548                 if (!*key)
3549                         key = "(no key defined)";
3551                 if (add_title && help_open_keymap_title(view, keymap))
3552                         return;
3553                 if (group) {
3554                         add_line_text(view, group, LINE_HELP_GROUP);
3555                         group = NULL;
3556                 }
3558                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3559                         if (!string_format_from(buf, &bufpos, "%s%s",
3560                                                 argc ? " " : "", req->argv[argc]))
3561                                 return;
3563                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3564         }
3567 static bool
3568 help_open(struct view *view, enum open_flags flags)
3570         enum keymap keymap;
3572         reset_view(view);
3573         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3574         add_line_text(view, "", LINE_DEFAULT);
3576         for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3577                 help_open_keymap(view, keymap);
3579         return TRUE;
3582 static enum request
3583 help_request(struct view *view, enum request request, struct line *line)
3585         switch (request) {
3586         case REQ_ENTER:
3587                 if (line->type == LINE_HELP_KEYMAP) {
3588                         help_keymap_hidden[line->other] =
3589                                 !help_keymap_hidden[line->other];
3590                         refresh_view(view);
3591                 }
3593                 return REQ_NONE;
3594         default:
3595                 return pager_request(view, request, line);
3596         }
3599 static struct view_ops help_ops = {
3600         "line",
3601         help_open,
3602         NULL,
3603         pager_draw,
3604         help_request,
3605         pager_grep,
3606         pager_select,
3607 };
3610 /*
3611  * Tree backend
3612  */
3614 struct tree_stack_entry {
3615         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3616         unsigned long lineno;           /* Line number to restore */
3617         char *name;                     /* Position of name in opt_path */
3618 };
3620 /* The top of the path stack. */
3621 static struct tree_stack_entry *tree_stack = NULL;
3622 unsigned long tree_lineno = 0;
3624 static void
3625 pop_tree_stack_entry(void)
3627         struct tree_stack_entry *entry = tree_stack;
3629         tree_lineno = entry->lineno;
3630         entry->name[0] = 0;
3631         tree_stack = entry->prev;
3632         free(entry);
3635 static void
3636 push_tree_stack_entry(const char *name, unsigned long lineno)
3638         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3639         size_t pathlen = strlen(opt_path);
3641         if (!entry)
3642                 return;
3644         entry->prev = tree_stack;
3645         entry->name = opt_path + pathlen;
3646         tree_stack = entry;
3648         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3649                 pop_tree_stack_entry();
3650                 return;
3651         }
3653         /* Move the current line to the first tree entry. */
3654         tree_lineno = 1;
3655         entry->lineno = lineno;
3658 /* Parse output from git-ls-tree(1):
3659  *
3660  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3661  */
3663 #define SIZEOF_TREE_ATTR \
3664         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3666 #define SIZEOF_TREE_MODE \
3667         STRING_SIZE("100644 ")
3669 #define TREE_ID_OFFSET \
3670         STRING_SIZE("100644 blob ")
3672 struct tree_entry {
3673         char id[SIZEOF_REV];
3674         mode_t mode;
3675         struct time time;               /* Date from the author ident. */
3676         const char *author;             /* Author of the commit. */
3677         char name[1];
3678 };
3680 static const char *
3681 tree_path(const struct line *line)
3683         return ((struct tree_entry *) line->data)->name;
3686 static int
3687 tree_compare_entry(const struct line *line1, const struct line *line2)
3689         if (line1->type != line2->type)
3690                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3691         return strcmp(tree_path(line1), tree_path(line2));
3694 static const enum sort_field tree_sort_fields[] = {
3695         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3696 };
3697 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3699 static int
3700 tree_compare(const void *l1, const void *l2)
3702         const struct line *line1 = (const struct line *) l1;
3703         const struct line *line2 = (const struct line *) l2;
3704         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3705         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3707         if (line1->type == LINE_TREE_HEAD)
3708                 return -1;
3709         if (line2->type == LINE_TREE_HEAD)
3710                 return 1;
3712         switch (get_sort_field(tree_sort_state)) {
3713         case ORDERBY_DATE:
3714                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3716         case ORDERBY_AUTHOR:
3717                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3719         case ORDERBY_NAME:
3720         default:
3721                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3722         }
3726 static struct line *
3727 tree_entry(struct view *view, enum line_type type, const char *path,
3728            const char *mode, const char *id)
3730         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3731         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3733         if (!entry || !line) {
3734                 free(entry);
3735                 return NULL;
3736         }
3738         strncpy(entry->name, path, strlen(path));
3739         if (mode)
3740                 entry->mode = strtoul(mode, NULL, 8);
3741         if (id)
3742                 string_copy_rev(entry->id, id);
3744         return line;
3747 static bool
3748 tree_read_date(struct view *view, char *text, bool *read_date)
3750         static const char *author_name;
3751         static struct time author_time;
3753         if (!text && *read_date) {
3754                 *read_date = FALSE;
3755                 return TRUE;
3757         } else if (!text) {
3758                 /* Find next entry to process */
3759                 const char *log_file[] = {
3760                         "git", "log", "--no-color", "--pretty=raw",
3761                                 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3762                 };
3764                 if (!view->lines) {
3765                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3766                         report("Tree is empty");
3767                         return TRUE;
3768                 }
3770                 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3771                         report("Failed to load tree data");
3772                         return TRUE;
3773                 }
3775                 *read_date = TRUE;
3776                 return FALSE;
3778         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3779                 parse_author_line(text + STRING_SIZE("author "),
3780                                   &author_name, &author_time);
3782         } else if (*text == ':') {
3783                 char *pos;
3784                 size_t annotated = 1;
3785                 size_t i;
3787                 pos = strchr(text, '\t');
3788                 if (!pos)
3789                         return TRUE;
3790                 text = pos + 1;
3791                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3792                         text += strlen(opt_path);
3793                 pos = strchr(text, '/');
3794                 if (pos)
3795                         *pos = 0;
3797                 for (i = 1; i < view->lines; i++) {
3798                         struct line *line = &view->line[i];
3799                         struct tree_entry *entry = line->data;
3801                         annotated += !!entry->author;
3802                         if (entry->author || strcmp(entry->name, text))
3803                                 continue;
3805                         entry->author = author_name;
3806                         entry->time = author_time;
3807                         line->dirty = 1;
3808                         break;
3809                 }
3811                 if (annotated == view->lines)
3812                         io_kill(view->pipe);
3813         }
3814         return TRUE;
3817 static bool
3818 tree_read(struct view *view, char *text)
3820         static bool read_date = FALSE;
3821         struct tree_entry *data;
3822         struct line *entry, *line;
3823         enum line_type type;
3824         size_t textlen = text ? strlen(text) : 0;
3825         char *path = text + SIZEOF_TREE_ATTR;
3827         if (read_date || !text)
3828                 return tree_read_date(view, text, &read_date);
3830         if (textlen <= SIZEOF_TREE_ATTR)
3831                 return FALSE;
3832         if (view->lines == 0 &&
3833             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3834                 return FALSE;
3836         /* Strip the path part ... */
3837         if (*opt_path) {
3838                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3839                 size_t striplen = strlen(opt_path);
3841                 if (pathlen > striplen)
3842                         memmove(path, path + striplen,
3843                                 pathlen - striplen + 1);
3845                 /* Insert "link" to parent directory. */
3846                 if (view->lines == 1 &&
3847                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3848                         return FALSE;
3849         }
3851         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3852         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3853         if (!entry)
3854                 return FALSE;
3855         data = entry->data;
3857         /* Skip "Directory ..." and ".." line. */
3858         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3859                 if (tree_compare_entry(line, entry) <= 0)
3860                         continue;
3862                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3864                 line->data = data;
3865                 line->type = type;
3866                 for (; line <= entry; line++)
3867                         line->dirty = line->cleareol = 1;
3868                 return TRUE;
3869         }
3871         if (tree_lineno > view->lineno) {
3872                 view->lineno = tree_lineno;
3873                 tree_lineno = 0;
3874         }
3876         return TRUE;
3879 static bool
3880 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3882         struct tree_entry *entry = line->data;
3884         if (line->type == LINE_TREE_HEAD) {
3885                 if (draw_text(view, line->type, "Directory path /"))
3886                         return TRUE;
3887         } else {
3888                 if (draw_mode(view, entry->mode))
3889                         return TRUE;
3891                 if (draw_author(view, entry->author))
3892                         return TRUE;
3894                 if (draw_date(view, &entry->time))
3895                         return TRUE;
3896         }
3898         draw_text(view, line->type, entry->name);
3899         return TRUE;
3902 static void
3903 open_blob_editor(const char *id)
3905         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3906         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3907         int fd = mkstemp(file);
3909         if (fd == -1)
3910                 report("Failed to create temporary file");
3911         else if (!io_run_append(blob_argv, fd))
3912                 report("Failed to save blob data to file");
3913         else
3914                 open_editor(file);
3915         if (fd != -1)
3916                 unlink(file);
3919 static enum request
3920 tree_request(struct view *view, enum request request, struct line *line)
3922         enum open_flags flags;
3923         struct tree_entry *entry = line->data;
3925         switch (request) {
3926         case REQ_VIEW_BLAME:
3927                 if (line->type != LINE_TREE_FILE) {
3928                         report("Blame only supported for files");
3929                         return REQ_NONE;
3930                 }
3932                 string_copy(opt_ref, view->vid);
3933                 return request;
3935         case REQ_EDIT:
3936                 if (line->type != LINE_TREE_FILE) {
3937                         report("Edit only supported for files");
3938                 } else if (!is_head_commit(view->vid)) {
3939                         open_blob_editor(entry->id);
3940                 } else {
3941                         open_editor(opt_file);
3942                 }
3943                 return REQ_NONE;
3945         case REQ_TOGGLE_SORT_FIELD:
3946         case REQ_TOGGLE_SORT_ORDER:
3947                 sort_view(view, request, &tree_sort_state, tree_compare);
3948                 return REQ_NONE;
3950         case REQ_PARENT:
3951                 if (!*opt_path) {
3952                         /* quit view if at top of tree */
3953                         return REQ_VIEW_CLOSE;
3954                 }
3955                 /* fake 'cd  ..' */
3956                 line = &view->line[1];
3957                 break;
3959         case REQ_ENTER:
3960                 break;
3962         default:
3963                 return request;
3964         }
3966         /* Cleanup the stack if the tree view is at a different tree. */
3967         while (!*opt_path && tree_stack)
3968                 pop_tree_stack_entry();
3970         switch (line->type) {
3971         case LINE_TREE_DIR:
3972                 /* Depending on whether it is a subdirectory or parent link
3973                  * mangle the path buffer. */
3974                 if (line == &view->line[1] && *opt_path) {
3975                         pop_tree_stack_entry();
3977                 } else {
3978                         const char *basename = tree_path(line);
3980                         push_tree_stack_entry(basename, view->lineno);
3981                 }
3983                 /* Trees and subtrees share the same ID, so they are not not
3984                  * unique like blobs. */
3985                 flags = OPEN_RELOAD;
3986                 request = REQ_VIEW_TREE;
3987                 break;
3989         case LINE_TREE_FILE:
3990                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3991                 request = REQ_VIEW_BLOB;
3992                 break;
3994         default:
3995                 return REQ_NONE;
3996         }
3998         open_view(view, request, flags);
3999         if (request == REQ_VIEW_TREE)
4000                 view->lineno = tree_lineno;
4002         return REQ_NONE;
4005 static bool
4006 tree_grep(struct view *view, struct line *line)
4008         struct tree_entry *entry = line->data;
4009         const char *text[] = {
4010                 entry->name,
4011                 opt_author ? entry->author : "",
4012                 mkdate(&entry->time, opt_date),
4013                 NULL
4014         };
4016         return grep_text(view, text);
4019 static void
4020 tree_select(struct view *view, struct line *line)
4022         struct tree_entry *entry = line->data;
4024         if (line->type == LINE_TREE_FILE) {
4025                 string_copy_rev(ref_blob, entry->id);
4026                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4028         } else if (line->type != LINE_TREE_DIR) {
4029                 return;
4030         }
4032         string_copy_rev(view->ref, entry->id);
4035 static bool
4036 tree_open(struct view *view, enum open_flags flags)
4038         static const char *tree_argv[] = {
4039                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4040         };
4042         if (view->lines == 0 && opt_prefix[0]) {
4043                 char *pos = opt_prefix;
4045                 while (pos && *pos) {
4046                         char *end = strchr(pos, '/');
4048                         if (end)
4049                                 *end = 0;
4050                         push_tree_stack_entry(pos, 0);
4051                         pos = end;
4052                         if (end) {
4053                                 *end = '/';
4054                                 pos++;
4055                         }
4056                 }
4058         } else if (strcmp(view->vid, view->id)) {
4059                 opt_path[0] = 0;
4060         }
4062         return begin_update(view, opt_cdup, tree_argv, flags);
4065 static struct view_ops tree_ops = {
4066         "file",
4067         tree_open,
4068         tree_read,
4069         tree_draw,
4070         tree_request,
4071         tree_grep,
4072         tree_select,
4073 };
4075 static bool
4076 blob_open(struct view *view, enum open_flags flags)
4078         static const char *blob_argv[] = {
4079                 "git", "cat-file", "blob", "%(blob)", NULL
4080         };
4082         return begin_update(view, NULL, blob_argv, flags);
4085 static bool
4086 blob_read(struct view *view, char *line)
4088         if (!line)
4089                 return TRUE;
4090         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4093 static enum request
4094 blob_request(struct view *view, enum request request, struct line *line)
4096         switch (request) {
4097         case REQ_EDIT:
4098                 open_blob_editor(view->vid);
4099                 return REQ_NONE;
4100         default:
4101                 return pager_request(view, request, line);
4102         }
4105 static struct view_ops blob_ops = {
4106         "line",
4107         blob_open,
4108         blob_read,
4109         pager_draw,
4110         blob_request,
4111         pager_grep,
4112         pager_select,
4113 };
4115 /*
4116  * Blame backend
4117  *
4118  * Loading the blame view is a two phase job:
4119  *
4120  *  1. File content is read either using opt_file from the
4121  *     filesystem or using git-cat-file.
4122  *  2. Then blame information is incrementally added by
4123  *     reading output from git-blame.
4124  */
4126 struct blame_commit {
4127         char id[SIZEOF_REV];            /* SHA1 ID. */
4128         char title[128];                /* First line of the commit message. */
4129         const char *author;             /* Author of the commit. */
4130         struct time time;               /* Date from the author ident. */
4131         char filename[128];             /* Name of file. */
4132         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4133         char parent_filename[128];      /* Parent/previous name of file. */
4134 };
4136 struct blame {
4137         struct blame_commit *commit;
4138         unsigned long lineno;
4139         char text[1];
4140 };
4142 static bool
4143 blame_open(struct view *view, enum open_flags flags)
4145         const char *file_argv[] = { opt_cdup, opt_file , NULL };
4146         char path[SIZEOF_STR];
4147         size_t i;
4149         if (!view->prev && *opt_prefix) {
4150                 string_copy(path, opt_file);
4151                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4152                         return FALSE;
4153         }
4155         if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4156                 const char *blame_cat_file_argv[] = {
4157                         "git", "cat-file", "blob", path, NULL
4158                 };
4160                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4161                     !begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4162                         return FALSE;
4163         }
4165         /* First pass: remove multiple references to the same commit. */
4166         for (i = 0; i < view->lines; i++) {
4167                 struct blame *blame = view->line[i].data;
4169                 if (blame->commit && blame->commit->id[0])
4170                         blame->commit->id[0] = 0;
4171                 else
4172                         blame->commit = NULL;
4173         }
4175         /* Second pass: free existing references. */
4176         for (i = 0; i < view->lines; i++) {
4177                 struct blame *blame = view->line[i].data;
4179                 if (blame->commit)
4180                         free(blame->commit);
4181         }
4183         string_format(view->vid, "%s:%s", opt_ref, opt_file);
4184         string_format(view->ref, "%s ...", opt_file);
4186         return TRUE;
4189 static struct blame_commit *
4190 get_blame_commit(struct view *view, const char *id)
4192         size_t i;
4194         for (i = 0; i < view->lines; i++) {
4195                 struct blame *blame = view->line[i].data;
4197                 if (!blame->commit)
4198                         continue;
4200                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4201                         return blame->commit;
4202         }
4204         {
4205                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4207                 if (commit)
4208                         string_ncopy(commit->id, id, SIZEOF_REV);
4209                 return commit;
4210         }
4213 static bool
4214 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4216         const char *pos = *posref;
4218         *posref = NULL;
4219         pos = strchr(pos + 1, ' ');
4220         if (!pos || !isdigit(pos[1]))
4221                 return FALSE;
4222         *number = atoi(pos + 1);
4223         if (*number < min || *number > max)
4224                 return FALSE;
4226         *posref = pos;
4227         return TRUE;
4230 static struct blame_commit *
4231 parse_blame_commit(struct view *view, const char *text, int *blamed)
4233         struct blame_commit *commit;
4234         struct blame *blame;
4235         const char *pos = text + SIZEOF_REV - 2;
4236         size_t orig_lineno = 0;
4237         size_t lineno;
4238         size_t group;
4240         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4241                 return NULL;
4243         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4244             !parse_number(&pos, &lineno, 1, view->lines) ||
4245             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4246                 return NULL;
4248         commit = get_blame_commit(view, text);
4249         if (!commit)
4250                 return NULL;
4252         *blamed += group;
4253         while (group--) {
4254                 struct line *line = &view->line[lineno + group - 1];
4256                 blame = line->data;
4257                 blame->commit = commit;
4258                 blame->lineno = orig_lineno + group - 1;
4259                 line->dirty = 1;
4260         }
4262         return commit;
4265 static bool
4266 blame_read_file(struct view *view, const char *line, bool *read_file)
4268         if (!line) {
4269                 const char *blame_argv[] = {
4270                         "git", "blame", "%(blameargs)", "--incremental",
4271                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4272                 };
4274                 if (view->lines == 0 && !view->prev)
4275                         die("No blame exist for %s", view->vid);
4277                 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4278                         report("Failed to load blame data");
4279                         return TRUE;
4280                 }
4282                 *read_file = FALSE;
4283                 return FALSE;
4285         } else {
4286                 size_t linelen = strlen(line);
4287                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4289                 if (!blame)
4290                         return FALSE;
4292                 blame->commit = NULL;
4293                 strncpy(blame->text, line, linelen);
4294                 blame->text[linelen] = 0;
4295                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4296         }
4299 static bool
4300 match_blame_header(const char *name, char **line)
4302         size_t namelen = strlen(name);
4303         bool matched = !strncmp(name, *line, namelen);
4305         if (matched)
4306                 *line += namelen;
4308         return matched;
4311 static bool
4312 blame_read(struct view *view, char *line)
4314         static struct blame_commit *commit = NULL;
4315         static int blamed = 0;
4316         static bool read_file = TRUE;
4318         if (read_file)
4319                 return blame_read_file(view, line, &read_file);
4321         if (!line) {
4322                 /* Reset all! */
4323                 commit = NULL;
4324                 blamed = 0;
4325                 read_file = TRUE;
4326                 string_format(view->ref, "%s", view->vid);
4327                 if (view_is_displayed(view)) {
4328                         update_view_title(view);
4329                         redraw_view_from(view, 0);
4330                 }
4331                 return TRUE;
4332         }
4334         if (!commit) {
4335                 commit = parse_blame_commit(view, line, &blamed);
4336                 string_format(view->ref, "%s %2d%%", view->vid,
4337                               view->lines ? blamed * 100 / view->lines : 0);
4339         } else if (match_blame_header("author ", &line)) {
4340                 commit->author = get_author(line);
4342         } else if (match_blame_header("author-time ", &line)) {
4343                 parse_timesec(&commit->time, line);
4345         } else if (match_blame_header("author-tz ", &line)) {
4346                 parse_timezone(&commit->time, line);
4348         } else if (match_blame_header("summary ", &line)) {
4349                 string_ncopy(commit->title, line, strlen(line));
4351         } else if (match_blame_header("previous ", &line)) {
4352                 if (strlen(line) <= SIZEOF_REV)
4353                         return FALSE;
4354                 string_copy_rev(commit->parent_id, line);
4355                 line += SIZEOF_REV;
4356                 string_ncopy(commit->parent_filename, line, strlen(line));
4358         } else if (match_blame_header("filename ", &line)) {
4359                 string_ncopy(commit->filename, line, strlen(line));
4360                 commit = NULL;
4361         }
4363         return TRUE;
4366 static bool
4367 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4369         struct blame *blame = line->data;
4370         struct time *time = NULL;
4371         const char *id = NULL, *author = NULL;
4373         if (blame->commit && *blame->commit->filename) {
4374                 id = blame->commit->id;
4375                 author = blame->commit->author;
4376                 time = &blame->commit->time;
4377         }
4379         if (draw_date(view, time))
4380                 return TRUE;
4382         if (draw_author(view, author))
4383                 return TRUE;
4385         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4386                 return TRUE;
4388         if (draw_lineno(view, lineno))
4389                 return TRUE;
4391         draw_text(view, LINE_DEFAULT, blame->text);
4392         return TRUE;
4395 static bool
4396 check_blame_commit(struct blame *blame, bool check_null_id)
4398         if (!blame->commit)
4399                 report("Commit data not loaded yet");
4400         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4401                 report("No commit exist for the selected line");
4402         else
4403                 return TRUE;
4404         return FALSE;
4407 static void
4408 setup_blame_parent_line(struct view *view, struct blame *blame)
4410         char from[SIZEOF_REF + SIZEOF_STR];
4411         char to[SIZEOF_REF + SIZEOF_STR];
4412         const char *diff_tree_argv[] = {
4413                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4414                         "-U0", from, to, "--", NULL
4415         };
4416         struct io io;
4417         int parent_lineno = -1;
4418         int blamed_lineno = -1;
4419         char *line;
4421         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4422             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4423             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4424                 return;
4426         while ((line = io_get(&io, '\n', TRUE))) {
4427                 if (*line == '@') {
4428                         char *pos = strchr(line, '+');
4430                         parent_lineno = atoi(line + 4);
4431                         if (pos)
4432                                 blamed_lineno = atoi(pos + 1);
4434                 } else if (*line == '+' && parent_lineno != -1) {
4435                         if (blame->lineno == blamed_lineno - 1 &&
4436                             !strcmp(blame->text, line + 1)) {
4437                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4438                                 break;
4439                         }
4440                         blamed_lineno++;
4441                 }
4442         }
4444         io_done(&io);
4447 static enum request
4448 blame_request(struct view *view, enum request request, struct line *line)
4450         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4451         struct blame *blame = line->data;
4453         switch (request) {
4454         case REQ_VIEW_BLAME:
4455                 if (check_blame_commit(blame, TRUE)) {
4456                         string_copy(opt_ref, blame->commit->id);
4457                         string_copy(opt_file, blame->commit->filename);
4458                         if (blame->lineno)
4459                                 view->lineno = blame->lineno;
4460                         refresh_view(view);
4461                 }
4462                 break;
4464         case REQ_PARENT:
4465                 if (!check_blame_commit(blame, TRUE))
4466                         break;
4467                 if (!*blame->commit->parent_id) {
4468                         report("The selected commit has no parents");
4469                 } else {
4470                         string_copy_rev(opt_ref, blame->commit->parent_id);
4471                         string_copy(opt_file, blame->commit->parent_filename);
4472                         setup_blame_parent_line(view, blame);
4473                         refresh_view(view);
4474                 }
4475                 break;
4477         case REQ_ENTER:
4478                 if (!check_blame_commit(blame, FALSE))
4479                         break;
4481                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4482                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4483                         break;
4485                 if (!strcmp(blame->commit->id, NULL_ID)) {
4486                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4487                         const char *diff_index_argv[] = {
4488                                 "git", "diff-index", "--root", "--patch-with-stat",
4489                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4490                         };
4492                         if (!*blame->commit->parent_id) {
4493                                 diff_index_argv[1] = "diff";
4494                                 diff_index_argv[2] = "--no-color";
4495                                 diff_index_argv[6] = "--";
4496                                 diff_index_argv[7] = "/dev/null";
4497                         }
4499                         open_argv(view, diff, diff_index_argv, NULL, flags);
4500                 } else {
4501                         open_view(view, REQ_VIEW_DIFF, flags);
4502                 }
4503                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4504                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4505                 break;
4507         default:
4508                 return request;
4509         }
4511         return REQ_NONE;
4514 static bool
4515 blame_grep(struct view *view, struct line *line)
4517         struct blame *blame = line->data;
4518         struct blame_commit *commit = blame->commit;
4519         const char *text[] = {
4520                 blame->text,
4521                 commit ? commit->title : "",
4522                 commit ? commit->id : "",
4523                 commit && opt_author ? commit->author : "",
4524                 commit ? mkdate(&commit->time, opt_date) : "",
4525                 NULL
4526         };
4528         return grep_text(view, text);
4531 static void
4532 blame_select(struct view *view, struct line *line)
4534         struct blame *blame = line->data;
4535         struct blame_commit *commit = blame->commit;
4537         if (!commit)
4538                 return;
4540         if (!strcmp(commit->id, NULL_ID))
4541                 string_ncopy(ref_commit, "HEAD", 4);
4542         else
4543                 string_copy_rev(ref_commit, commit->id);
4546 static struct view_ops blame_ops = {
4547         "line",
4548         blame_open,
4549         blame_read,
4550         blame_draw,
4551         blame_request,
4552         blame_grep,
4553         blame_select,
4554 };
4556 /*
4557  * Branch backend
4558  */
4560 struct branch {
4561         const char *author;             /* Author of the last commit. */
4562         struct time time;               /* Date of the last activity. */
4563         const struct ref *ref;          /* Name and commit ID information. */
4564 };
4566 static const struct ref branch_all;
4568 static const enum sort_field branch_sort_fields[] = {
4569         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4570 };
4571 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4573 static int
4574 branch_compare(const void *l1, const void *l2)
4576         const struct branch *branch1 = ((const struct line *) l1)->data;
4577         const struct branch *branch2 = ((const struct line *) l2)->data;
4579         switch (get_sort_field(branch_sort_state)) {
4580         case ORDERBY_DATE:
4581                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4583         case ORDERBY_AUTHOR:
4584                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4586         case ORDERBY_NAME:
4587         default:
4588                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4589         }
4592 static bool
4593 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4595         struct branch *branch = line->data;
4596         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4598         if (draw_date(view, &branch->time))
4599                 return TRUE;
4601         if (draw_author(view, branch->author))
4602                 return TRUE;
4604         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4605         return TRUE;
4608 static enum request
4609 branch_request(struct view *view, enum request request, struct line *line)
4611         struct branch *branch = line->data;
4613         switch (request) {
4614         case REQ_REFRESH:
4615                 load_refs();
4616                 refresh_view(view);
4617                 return REQ_NONE;
4619         case REQ_TOGGLE_SORT_FIELD:
4620         case REQ_TOGGLE_SORT_ORDER:
4621                 sort_view(view, request, &branch_sort_state, branch_compare);
4622                 return REQ_NONE;
4624         case REQ_ENTER:
4625         {
4626                 const struct ref *ref = branch->ref;
4627                 const char *all_branches_argv[] = {
4628                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4629                               "--topo-order",
4630                               ref == &branch_all ? "--all" : ref->name, NULL
4631                 };
4632                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4634                 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4635                 return REQ_NONE;
4636         }
4637         default:
4638                 return request;
4639         }
4642 static bool
4643 branch_read(struct view *view, char *line)
4645         static char id[SIZEOF_REV];
4646         struct branch *reference;
4647         size_t i;
4649         if (!line)
4650                 return TRUE;
4652         switch (get_line_type(line)) {
4653         case LINE_COMMIT:
4654                 string_copy_rev(id, line + STRING_SIZE("commit "));
4655                 return TRUE;
4657         case LINE_AUTHOR:
4658                 for (i = 0, reference = NULL; i < view->lines; i++) {
4659                         struct branch *branch = view->line[i].data;
4661                         if (strcmp(branch->ref->id, id))
4662                                 continue;
4664                         view->line[i].dirty = TRUE;
4665                         if (reference) {
4666                                 branch->author = reference->author;
4667                                 branch->time = reference->time;
4668                                 continue;
4669                         }
4671                         parse_author_line(line + STRING_SIZE("author "),
4672                                           &branch->author, &branch->time);
4673                         reference = branch;
4674                 }
4675                 return TRUE;
4677         default:
4678                 return TRUE;
4679         }
4683 static bool
4684 branch_open_visitor(void *data, const struct ref *ref)
4686         struct view *view = data;
4687         struct branch *branch;
4689         if (ref->tag || ref->ltag || ref->remote)
4690                 return TRUE;
4692         branch = calloc(1, sizeof(*branch));
4693         if (!branch)
4694                 return FALSE;
4696         branch->ref = ref;
4697         return !!add_line_data(view, branch, LINE_DEFAULT);
4700 static bool
4701 branch_open(struct view *view, enum open_flags flags)
4703         const char *branch_log[] = {
4704                 "git", "log", "--no-color", "--pretty=raw",
4705                         "--simplify-by-decoration", "--all", NULL
4706         };
4708         if (!begin_update(view, NULL, branch_log, flags)) {
4709                 report("Failed to load branch data");
4710                 return TRUE;
4711         }
4713         branch_open_visitor(view, &branch_all);
4714         foreach_ref(branch_open_visitor, view);
4715         view->p_restore = TRUE;
4717         return TRUE;
4720 static bool
4721 branch_grep(struct view *view, struct line *line)
4723         struct branch *branch = line->data;
4724         const char *text[] = {
4725                 branch->ref->name,
4726                 branch->author,
4727                 NULL
4728         };
4730         return grep_text(view, text);
4733 static void
4734 branch_select(struct view *view, struct line *line)
4736         struct branch *branch = line->data;
4738         string_copy_rev(view->ref, branch->ref->id);
4739         string_copy_rev(ref_commit, branch->ref->id);
4740         string_copy_rev(ref_head, branch->ref->id);
4741         string_copy_rev(ref_branch, branch->ref->name);
4744 static struct view_ops branch_ops = {
4745         "branch",
4746         branch_open,
4747         branch_read,
4748         branch_draw,
4749         branch_request,
4750         branch_grep,
4751         branch_select,
4752 };
4754 /*
4755  * Status backend
4756  */
4758 struct status {
4759         char status;
4760         struct {
4761                 mode_t mode;
4762                 char rev[SIZEOF_REV];
4763                 char name[SIZEOF_STR];
4764         } old;
4765         struct {
4766                 mode_t mode;
4767                 char rev[SIZEOF_REV];
4768                 char name[SIZEOF_STR];
4769         } new;
4770 };
4772 static char status_onbranch[SIZEOF_STR];
4773 static struct status stage_status;
4774 static enum line_type stage_line_type;
4775 static size_t stage_chunks;
4776 static int *stage_chunk;
4778 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4780 /* This should work even for the "On branch" line. */
4781 static inline bool
4782 status_has_none(struct view *view, struct line *line)
4784         return line < view->line + view->lines && !line[1].data;
4787 /* Get fields from the diff line:
4788  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4789  */
4790 static inline bool
4791 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4793         const char *old_mode = buf +  1;
4794         const char *new_mode = buf +  8;
4795         const char *old_rev  = buf + 15;
4796         const char *new_rev  = buf + 56;
4797         const char *status   = buf + 97;
4799         if (bufsize < 98 ||
4800             old_mode[-1] != ':' ||
4801             new_mode[-1] != ' ' ||
4802             old_rev[-1]  != ' ' ||
4803             new_rev[-1]  != ' ' ||
4804             status[-1]   != ' ')
4805                 return FALSE;
4807         file->status = *status;
4809         string_copy_rev(file->old.rev, old_rev);
4810         string_copy_rev(file->new.rev, new_rev);
4812         file->old.mode = strtoul(old_mode, NULL, 8);
4813         file->new.mode = strtoul(new_mode, NULL, 8);
4815         file->old.name[0] = file->new.name[0] = 0;
4817         return TRUE;
4820 static bool
4821 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4823         struct status *unmerged = NULL;
4824         char *buf;
4825         struct io io;
4827         if (!io_run(&io, IO_RD, opt_cdup, argv))
4828                 return FALSE;
4830         add_line_data(view, NULL, type);
4832         while ((buf = io_get(&io, 0, TRUE))) {
4833                 struct status *file = unmerged;
4835                 if (!file) {
4836                         file = calloc(1, sizeof(*file));
4837                         if (!file || !add_line_data(view, file, type))
4838                                 goto error_out;
4839                 }
4841                 /* Parse diff info part. */
4842                 if (status) {
4843                         file->status = status;
4844                         if (status == 'A')
4845                                 string_copy(file->old.rev, NULL_ID);
4847                 } else if (!file->status || file == unmerged) {
4848                         if (!status_get_diff(file, buf, strlen(buf)))
4849                                 goto error_out;
4851                         buf = io_get(&io, 0, TRUE);
4852                         if (!buf)
4853                                 break;
4855                         /* Collapse all modified entries that follow an
4856                          * associated unmerged entry. */
4857                         if (unmerged == file) {
4858                                 unmerged->status = 'U';
4859                                 unmerged = NULL;
4860                         } else if (file->status == 'U') {
4861                                 unmerged = file;
4862                         }
4863                 }
4865                 /* Grab the old name for rename/copy. */
4866                 if (!*file->old.name &&
4867                     (file->status == 'R' || file->status == 'C')) {
4868                         string_ncopy(file->old.name, buf, strlen(buf));
4870                         buf = io_get(&io, 0, TRUE);
4871                         if (!buf)
4872                                 break;
4873                 }
4875                 /* git-ls-files just delivers a NUL separated list of
4876                  * file names similar to the second half of the
4877                  * git-diff-* output. */
4878                 string_ncopy(file->new.name, buf, strlen(buf));
4879                 if (!*file->old.name)
4880                         string_copy(file->old.name, file->new.name);
4881                 file = NULL;
4882         }
4884         if (io_error(&io)) {
4885 error_out:
4886                 io_done(&io);
4887                 return FALSE;
4888         }
4890         if (!view->line[view->lines - 1].data)
4891                 add_line_data(view, NULL, LINE_STAT_NONE);
4893         io_done(&io);
4894         return TRUE;
4897 /* Don't show unmerged entries in the staged section. */
4898 static const char *status_diff_index_argv[] = {
4899         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4900                              "--cached", "-M", "HEAD", NULL
4901 };
4903 static const char *status_diff_files_argv[] = {
4904         "git", "diff-files", "-z", NULL
4905 };
4907 static const char *status_list_other_argv[] = {
4908         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4909 };
4911 static const char *status_list_no_head_argv[] = {
4912         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4913 };
4915 static const char *update_index_argv[] = {
4916         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4917 };
4919 /* Restore the previous line number to stay in the context or select a
4920  * line with something that can be updated. */
4921 static void
4922 status_restore(struct view *view)
4924         if (view->p_lineno >= view->lines)
4925                 view->p_lineno = view->lines - 1;
4926         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4927                 view->p_lineno++;
4928         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4929                 view->p_lineno--;
4931         /* If the above fails, always skip the "On branch" line. */
4932         if (view->p_lineno < view->lines)
4933                 view->lineno = view->p_lineno;
4934         else
4935                 view->lineno = 1;
4937         if (view->lineno < view->offset)
4938                 view->offset = view->lineno;
4939         else if (view->offset + view->height <= view->lineno)
4940                 view->offset = view->lineno - view->height + 1;
4942         view->p_restore = FALSE;
4945 static void
4946 status_update_onbranch(void)
4948         static const char *paths[][2] = {
4949                 { "rebase-apply/rebasing",      "Rebasing" },
4950                 { "rebase-apply/applying",      "Applying mailbox" },
4951                 { "rebase-apply/",              "Rebasing mailbox" },
4952                 { "rebase-merge/interactive",   "Interactive rebase" },
4953                 { "rebase-merge/",              "Rebase merge" },
4954                 { "MERGE_HEAD",                 "Merging" },
4955                 { "BISECT_LOG",                 "Bisecting" },
4956                 { "HEAD",                       "On branch" },
4957         };
4958         char buf[SIZEOF_STR];
4959         struct stat stat;
4960         int i;
4962         if (is_initial_commit()) {
4963                 string_copy(status_onbranch, "Initial commit");
4964                 return;
4965         }
4967         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4968                 char *head = opt_head;
4970                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4971                     lstat(buf, &stat) < 0)
4972                         continue;
4974                 if (!*opt_head) {
4975                         struct io io;
4977                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4978                             io_read_buf(&io, buf, sizeof(buf))) {
4979                                 head = buf;
4980                                 if (!prefixcmp(head, "refs/heads/"))
4981                                         head += STRING_SIZE("refs/heads/");
4982                         }
4983                 }
4985                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4986                         string_copy(status_onbranch, opt_head);
4987                 return;
4988         }
4990         string_copy(status_onbranch, "Not currently on any branch");
4993 /* First parse staged info using git-diff-index(1), then parse unstaged
4994  * info using git-diff-files(1), and finally untracked files using
4995  * git-ls-files(1). */
4996 static bool
4997 status_open(struct view *view, enum open_flags flags)
4999         reset_view(view);
5001         add_line_data(view, NULL, LINE_STAT_HEAD);
5002         status_update_onbranch();
5004         io_run_bg(update_index_argv);
5006         if (is_initial_commit()) {
5007                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5008                         return FALSE;
5009         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5010                 return FALSE;
5011         }
5013         if (!opt_untracked_dirs_content)
5014                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5016         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5017             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5018                 return FALSE;
5020         /* Restore the exact position or use the specialized restore
5021          * mode? */
5022         if (!view->p_restore)
5023                 status_restore(view);
5024         return TRUE;
5027 static bool
5028 status_draw(struct view *view, struct line *line, unsigned int lineno)
5030         struct status *status = line->data;
5031         enum line_type type;
5032         const char *text;
5034         if (!status) {
5035                 switch (line->type) {
5036                 case LINE_STAT_STAGED:
5037                         type = LINE_STAT_SECTION;
5038                         text = "Changes to be committed:";
5039                         break;
5041                 case LINE_STAT_UNSTAGED:
5042                         type = LINE_STAT_SECTION;
5043                         text = "Changed but not updated:";
5044                         break;
5046                 case LINE_STAT_UNTRACKED:
5047                         type = LINE_STAT_SECTION;
5048                         text = "Untracked files:";
5049                         break;
5051                 case LINE_STAT_NONE:
5052                         type = LINE_DEFAULT;
5053                         text = "  (no files)";
5054                         break;
5056                 case LINE_STAT_HEAD:
5057                         type = LINE_STAT_HEAD;
5058                         text = status_onbranch;
5059                         break;
5061                 default:
5062                         return FALSE;
5063                 }
5064         } else {
5065                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5067                 buf[0] = status->status;
5068                 if (draw_text(view, line->type, buf))
5069                         return TRUE;
5070                 type = LINE_DEFAULT;
5071                 text = status->new.name;
5072         }
5074         draw_text(view, type, text);
5075         return TRUE;
5078 static enum request
5079 status_enter(struct view *view, struct line *line)
5081         struct status *status = line->data;
5082         const char *oldpath = status ? status->old.name : NULL;
5083         /* Diffs for unmerged entries are empty when passing the new
5084          * path, so leave it empty. */
5085         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5086         const char *info;
5087         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5088         struct view *stage = VIEW(REQ_VIEW_STAGE);
5090         if (line->type == LINE_STAT_NONE ||
5091             (!status && line[1].type == LINE_STAT_NONE)) {
5092                 report("No file to diff");
5093                 return REQ_NONE;
5094         }
5096         switch (line->type) {
5097         case LINE_STAT_STAGED:
5098                 if (is_initial_commit()) {
5099                         const char *no_head_diff_argv[] = {
5100                                 "git", "diff", "--no-color", "--patch-with-stat",
5101                                         "--", "/dev/null", newpath, NULL
5102                         };
5104                         open_argv(view, stage, no_head_diff_argv, opt_cdup, flags); 
5105                 } else {
5106                         const char *index_show_argv[] = {
5107                                 "git", "diff-index", "--root", "--patch-with-stat",
5108                                         "-C", "-M", "--cached", "HEAD", "--",
5109                                         oldpath, newpath, NULL
5110                         };
5112                         open_argv(view, stage, index_show_argv, opt_cdup, flags);
5113                 }
5115                 if (status)
5116                         info = "Staged changes to %s";
5117                 else
5118                         info = "Staged changes";
5119                 break;
5121         case LINE_STAT_UNSTAGED:
5122         {
5123                 const char *files_show_argv[] = {
5124                         "git", "diff-files", "--root", "--patch-with-stat",
5125                                 "-C", "-M", "--", oldpath, newpath, NULL
5126                 };
5128                 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5129                 if (status)
5130                         info = "Unstaged changes to %s";
5131                 else
5132                         info = "Unstaged changes";
5133                 break;
5134         }
5135         case LINE_STAT_UNTRACKED:
5136                 if (!newpath) {
5137                         report("No file to show");
5138                         return REQ_NONE;
5139                 }
5141                 if (!suffixcmp(status->new.name, -1, "/")) {
5142                         report("Cannot display a directory");
5143                         return REQ_NONE;
5144                 }
5146                 open_file(view, stage, newpath, flags);
5147                 info = "Untracked file %s";
5148                 break;
5150         case LINE_STAT_HEAD:
5151                 return REQ_NONE;
5153         default:
5154                 die("line type %d not handled in switch", line->type);
5155         }
5157         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5158                 if (status) {
5159                         stage_status = *status;
5160                 } else {
5161                         memset(&stage_status, 0, sizeof(stage_status));
5162                 }
5164                 stage_line_type = line->type;
5165                 stage_chunks = 0;
5166                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5167         }
5169         return REQ_NONE;
5172 static bool
5173 status_exists(struct status *status, enum line_type type)
5175         struct view *view = VIEW(REQ_VIEW_STATUS);
5176         unsigned long lineno;
5178         for (lineno = 0; lineno < view->lines; lineno++) {
5179                 struct line *line = &view->line[lineno];
5180                 struct status *pos = line->data;
5182                 if (line->type != type)
5183                         continue;
5184                 if (!pos && (!status || !status->status) && line[1].data) {
5185                         select_view_line(view, lineno);
5186                         return TRUE;
5187                 }
5188                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5189                         select_view_line(view, lineno);
5190                         return TRUE;
5191                 }
5192         }
5194         return FALSE;
5198 static bool
5199 status_update_prepare(struct io *io, enum line_type type)
5201         const char *staged_argv[] = {
5202                 "git", "update-index", "-z", "--index-info", NULL
5203         };
5204         const char *others_argv[] = {
5205                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5206         };
5208         switch (type) {
5209         case LINE_STAT_STAGED:
5210                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5212         case LINE_STAT_UNSTAGED:
5213         case LINE_STAT_UNTRACKED:
5214                 return io_run(io, IO_WR, opt_cdup, others_argv);
5216         default:
5217                 die("line type %d not handled in switch", type);
5218                 return FALSE;
5219         }
5222 static bool
5223 status_update_write(struct io *io, struct status *status, enum line_type type)
5225         char buf[SIZEOF_STR];
5226         size_t bufsize = 0;
5228         switch (type) {
5229         case LINE_STAT_STAGED:
5230                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5231                                         status->old.mode,
5232                                         status->old.rev,
5233                                         status->old.name, 0))
5234                         return FALSE;
5235                 break;
5237         case LINE_STAT_UNSTAGED:
5238         case LINE_STAT_UNTRACKED:
5239                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5240                         return FALSE;
5241                 break;
5243         default:
5244                 die("line type %d not handled in switch", type);
5245         }
5247         return io_write(io, buf, bufsize);
5250 static bool
5251 status_update_file(struct status *status, enum line_type type)
5253         struct io io;
5254         bool result;
5256         if (!status_update_prepare(&io, type))
5257                 return FALSE;
5259         result = status_update_write(&io, status, type);
5260         return io_done(&io) && result;
5263 static bool
5264 status_update_files(struct view *view, struct line *line)
5266         char buf[sizeof(view->ref)];
5267         struct io io;
5268         bool result = TRUE;
5269         struct line *pos = view->line + view->lines;
5270         int files = 0;
5271         int file, done;
5272         int cursor_y = -1, cursor_x = -1;
5274         if (!status_update_prepare(&io, line->type))
5275                 return FALSE;
5277         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5278                 files++;
5280         string_copy(buf, view->ref);
5281         getsyx(cursor_y, cursor_x);
5282         for (file = 0, done = 5; result && file < files; line++, file++) {
5283                 int almost_done = file * 100 / files;
5285                 if (almost_done > done) {
5286                         done = almost_done;
5287                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5288                                       file, files, done);
5289                         update_view_title(view);
5290                         setsyx(cursor_y, cursor_x);
5291                         doupdate();
5292                 }
5293                 result = status_update_write(&io, line->data, line->type);
5294         }
5295         string_copy(view->ref, buf);
5297         return io_done(&io) && result;
5300 static bool
5301 status_update(struct view *view)
5303         struct line *line = &view->line[view->lineno];
5305         assert(view->lines);
5307         if (!line->data) {
5308                 /* This should work even for the "On branch" line. */
5309                 if (line < view->line + view->lines && !line[1].data) {
5310                         report("Nothing to update");
5311                         return FALSE;
5312                 }
5314                 if (!status_update_files(view, line + 1)) {
5315                         report("Failed to update file status");
5316                         return FALSE;
5317                 }
5319         } else if (!status_update_file(line->data, line->type)) {
5320                 report("Failed to update file status");
5321                 return FALSE;
5322         }
5324         return TRUE;
5327 static bool
5328 status_revert(struct status *status, enum line_type type, bool has_none)
5330         if (!status || type != LINE_STAT_UNSTAGED) {
5331                 if (type == LINE_STAT_STAGED) {
5332                         report("Cannot revert changes to staged files");
5333                 } else if (type == LINE_STAT_UNTRACKED) {
5334                         report("Cannot revert changes to untracked files");
5335                 } else if (has_none) {
5336                         report("Nothing to revert");
5337                 } else {
5338                         report("Cannot revert changes to multiple files");
5339                 }
5341         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5342                 char mode[10] = "100644";
5343                 const char *reset_argv[] = {
5344                         "git", "update-index", "--cacheinfo", mode,
5345                                 status->old.rev, status->old.name, NULL
5346                 };
5347                 const char *checkout_argv[] = {
5348                         "git", "checkout", "--", status->old.name, NULL
5349                 };
5351                 if (status->status == 'U') {
5352                         string_format(mode, "%5o", status->old.mode);
5354                         if (status->old.mode == 0 && status->new.mode == 0) {
5355                                 reset_argv[2] = "--force-remove";
5356                                 reset_argv[3] = status->old.name;
5357                                 reset_argv[4] = NULL;
5358                         }
5360                         if (!io_run_fg(reset_argv, opt_cdup))
5361                                 return FALSE;
5362                         if (status->old.mode == 0 && status->new.mode == 0)
5363                                 return TRUE;
5364                 }
5366                 return io_run_fg(checkout_argv, opt_cdup);
5367         }
5369         return FALSE;
5372 static enum request
5373 status_request(struct view *view, enum request request, struct line *line)
5375         struct status *status = line->data;
5377         switch (request) {
5378         case REQ_STATUS_UPDATE:
5379                 if (!status_update(view))
5380                         return REQ_NONE;
5381                 break;
5383         case REQ_STATUS_REVERT:
5384                 if (!status_revert(status, line->type, status_has_none(view, line)))
5385                         return REQ_NONE;
5386                 break;
5388         case REQ_STATUS_MERGE:
5389                 if (!status || status->status != 'U') {
5390                         report("Merging only possible for files with unmerged status ('U').");
5391                         return REQ_NONE;
5392                 }
5393                 open_mergetool(status->new.name);
5394                 break;
5396         case REQ_EDIT:
5397                 if (!status)
5398                         return request;
5399                 if (status->status == 'D') {
5400                         report("File has been deleted.");
5401                         return REQ_NONE;
5402                 }
5404                 open_editor(status->new.name);
5405                 break;
5407         case REQ_VIEW_BLAME:
5408                 if (status)
5409                         opt_ref[0] = 0;
5410                 return request;
5412         case REQ_ENTER:
5413                 /* After returning the status view has been split to
5414                  * show the stage view. No further reloading is
5415                  * necessary. */
5416                 return status_enter(view, line);
5418         case REQ_REFRESH:
5419                 /* Simply reload the view. */
5420                 break;
5422         default:
5423                 return request;
5424         }
5426         refresh_view(view);
5428         return REQ_NONE;
5431 static void
5432 status_select(struct view *view, struct line *line)
5434         struct status *status = line->data;
5435         char file[SIZEOF_STR] = "all files";
5436         const char *text;
5437         const char *key;
5439         if (status && !string_format(file, "'%s'", status->new.name))
5440                 return;
5442         if (!status && line[1].type == LINE_STAT_NONE)
5443                 line++;
5445         switch (line->type) {
5446         case LINE_STAT_STAGED:
5447                 text = "Press %s to unstage %s for commit";
5448                 break;
5450         case LINE_STAT_UNSTAGED:
5451                 text = "Press %s to stage %s for commit";
5452                 break;
5454         case LINE_STAT_UNTRACKED:
5455                 text = "Press %s to stage %s for addition";
5456                 break;
5458         case LINE_STAT_HEAD:
5459         case LINE_STAT_NONE:
5460                 text = "Nothing to update";
5461                 break;
5463         default:
5464                 die("line type %d not handled in switch", line->type);
5465         }
5467         if (status && status->status == 'U') {
5468                 text = "Press %s to resolve conflict in %s";
5469                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5471         } else {
5472                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5473         }
5475         string_format(view->ref, text, key, file);
5476         if (status)
5477                 string_copy(opt_file, status->new.name);
5480 static bool
5481 status_grep(struct view *view, struct line *line)
5483         struct status *status = line->data;
5485         if (status) {
5486                 const char buf[2] = { status->status, 0 };
5487                 const char *text[] = { status->new.name, buf, NULL };
5489                 return grep_text(view, text);
5490         }
5492         return FALSE;
5495 static struct view_ops status_ops = {
5496         "file",
5497         status_open,
5498         NULL,
5499         status_draw,
5500         status_request,
5501         status_grep,
5502         status_select,
5503 };
5506 static bool
5507 stage_diff_write(struct io *io, struct line *line, struct line *end)
5509         while (line < end) {
5510                 if (!io_write(io, line->data, strlen(line->data)) ||
5511                     !io_write(io, "\n", 1))
5512                         return FALSE;
5513                 line++;
5514                 if (line->type == LINE_DIFF_CHUNK ||
5515                     line->type == LINE_DIFF_HEADER)
5516                         break;
5517         }
5519         return TRUE;
5522 static struct line *
5523 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5525         for (; view->line < line; line--)
5526                 if (line->type == type)
5527                         return line;
5529         return NULL;
5532 static bool
5533 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5535         const char *apply_argv[SIZEOF_ARG] = {
5536                 "git", "apply", "--whitespace=nowarn", NULL
5537         };
5538         struct line *diff_hdr;
5539         struct io io;
5540         int argc = 3;
5542         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5543         if (!diff_hdr)
5544                 return FALSE;
5546         if (!revert)
5547                 apply_argv[argc++] = "--cached";
5548         if (revert || stage_line_type == LINE_STAT_STAGED)
5549                 apply_argv[argc++] = "-R";
5550         apply_argv[argc++] = "-";
5551         apply_argv[argc++] = NULL;
5552         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5553                 return FALSE;
5555         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5556             !stage_diff_write(&io, chunk, view->line + view->lines))
5557                 chunk = NULL;
5559         io_done(&io);
5560         io_run_bg(update_index_argv);
5562         return chunk ? TRUE : FALSE;
5565 static bool
5566 stage_update(struct view *view, struct line *line)
5568         struct line *chunk = NULL;
5570         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5571                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5573         if (chunk) {
5574                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5575                         report("Failed to apply chunk");
5576                         return FALSE;
5577                 }
5579         } else if (!stage_status.status) {
5580                 view = VIEW(REQ_VIEW_STATUS);
5582                 for (line = view->line; line < view->line + view->lines; line++)
5583                         if (line->type == stage_line_type)
5584                                 break;
5586                 if (!status_update_files(view, line + 1)) {
5587                         report("Failed to update files");
5588                         return FALSE;
5589                 }
5591         } else if (!status_update_file(&stage_status, stage_line_type)) {
5592                 report("Failed to update file");
5593                 return FALSE;
5594         }
5596         return TRUE;
5599 static bool
5600 stage_revert(struct view *view, struct line *line)
5602         struct line *chunk = NULL;
5604         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5605                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5607         if (chunk) {
5608                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5609                         return FALSE;
5611                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5612                         report("Failed to revert chunk");
5613                         return FALSE;
5614                 }
5615                 return TRUE;
5617         } else {
5618                 return status_revert(stage_status.status ? &stage_status : NULL,
5619                                      stage_line_type, FALSE);
5620         }
5624 static void
5625 stage_next(struct view *view, struct line *line)
5627         int i;
5629         if (!stage_chunks) {
5630                 for (line = view->line; line < view->line + view->lines; line++) {
5631                         if (line->type != LINE_DIFF_CHUNK)
5632                                 continue;
5634                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5635                                 report("Allocation failure");
5636                                 return;
5637                         }
5639                         stage_chunk[stage_chunks++] = line - view->line;
5640                 }
5641         }
5643         for (i = 0; i < stage_chunks; i++) {
5644                 if (stage_chunk[i] > view->lineno) {
5645                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5646                         report("Chunk %d of %d", i + 1, stage_chunks);
5647                         return;
5648                 }
5649         }
5651         report("No next chunk found");
5654 static enum request
5655 stage_request(struct view *view, enum request request, struct line *line)
5657         switch (request) {
5658         case REQ_STATUS_UPDATE:
5659                 if (!stage_update(view, line))
5660                         return REQ_NONE;
5661                 break;
5663         case REQ_STATUS_REVERT:
5664                 if (!stage_revert(view, line))
5665                         return REQ_NONE;
5666                 break;
5668         case REQ_STAGE_NEXT:
5669                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5670                         report("File is untracked; press %s to add",
5671                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5672                         return REQ_NONE;
5673                 }
5674                 stage_next(view, line);
5675                 return REQ_NONE;
5677         case REQ_EDIT:
5678                 if (!stage_status.new.name[0])
5679                         return request;
5680                 if (stage_status.status == 'D') {
5681                         report("File has been deleted.");
5682                         return REQ_NONE;
5683                 }
5685                 open_editor(stage_status.new.name);
5686                 break;
5688         case REQ_REFRESH:
5689                 /* Reload everything ... */
5690                 break;
5692         case REQ_VIEW_BLAME:
5693                 if (stage_status.new.name[0]) {
5694                         string_copy(opt_file, stage_status.new.name);
5695                         opt_ref[0] = 0;
5696                 }
5697                 return request;
5699         case REQ_ENTER:
5700                 return pager_request(view, request, line);
5702         default:
5703                 return request;
5704         }
5706         refresh_view(view->parent);
5708         /* Check whether the staged entry still exists, and close the
5709          * stage view if it doesn't. */
5710         if (!status_exists(&stage_status, stage_line_type)) {
5711                 status_restore(VIEW(REQ_VIEW_STATUS));
5712                 return REQ_VIEW_CLOSE;
5713         }
5715         refresh_view(view);
5717         return REQ_NONE;
5720 static struct view_ops stage_ops = {
5721         "line",
5722         view_open,
5723         pager_read,
5724         pager_draw,
5725         stage_request,
5726         pager_grep,
5727         pager_select,
5728 };
5731 /*
5732  * Revision graph
5733  */
5735 static const enum line_type graph_colors[] = {
5736         LINE_GRAPH_LINE_0,
5737         LINE_GRAPH_LINE_1,
5738         LINE_GRAPH_LINE_2,
5739         LINE_GRAPH_LINE_3,
5740         LINE_GRAPH_LINE_4,
5741         LINE_GRAPH_LINE_5,
5742         LINE_GRAPH_LINE_6,
5743 };
5745 static enum line_type get_graph_color(struct graph_symbol *symbol)
5747         if (symbol->commit)
5748                 return LINE_GRAPH_COMMIT;
5749         assert(symbol->color < ARRAY_SIZE(graph_colors));
5750         return graph_colors[symbol->color];
5753 static bool
5754 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5756         const char *chars = graph_symbol_to_utf8(symbol);
5758         return draw_text(view, color, chars + !!first); 
5761 static bool
5762 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5764         const char *chars = graph_symbol_to_ascii(symbol);
5766         return draw_text(view, color, chars + !!first); 
5769 static bool
5770 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5772         const chtype *chars = graph_symbol_to_chtype(symbol);
5774         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5777 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5779 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5781         static const draw_graph_fn fns[] = {
5782                 draw_graph_ascii,
5783                 draw_graph_chtype,
5784                 draw_graph_utf8
5785         };
5786         draw_graph_fn fn = fns[opt_line_graphics];
5787         int i;
5789         for (i = 0; i < canvas->size; i++) {
5790                 struct graph_symbol *symbol = &canvas->symbols[i];
5791                 enum line_type color = get_graph_color(symbol);
5793                 if (fn(view, symbol, color, i == 0))
5794                         return TRUE;
5795         }
5797         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5800 /*
5801  * Main view backend
5802  */
5804 struct commit {
5805         char id[SIZEOF_REV];            /* SHA1 ID. */
5806         char title[128];                /* First line of the commit message. */
5807         const char *author;             /* Author of the commit. */
5808         struct time time;               /* Date from the author ident. */
5809         struct ref_list *refs;          /* Repository references. */
5810         struct graph_canvas graph;      /* Ancestry chain graphics. */
5811 };
5813 static bool
5814 main_open(struct view *view, enum open_flags flags)
5816         static const char *main_argv[] = {
5817                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5818                         "--topo-order", "%(diffargs)", "%(revargs)",
5819                         "--", "%(fileargs)", NULL
5820         };
5822         return begin_update(view, NULL, main_argv, flags);
5825 static bool
5826 main_draw(struct view *view, struct line *line, unsigned int lineno)
5828         struct commit *commit = line->data;
5830         if (!commit->author)
5831                 return FALSE;
5833         if (draw_date(view, &commit->time))
5834                 return TRUE;
5836         if (draw_author(view, commit->author))
5837                 return TRUE;
5839         if (opt_rev_graph && draw_graph(view, &commit->graph))
5840                 return TRUE;
5842         if (draw_refs(view, commit->refs))
5843                 return TRUE;
5845         draw_text(view, LINE_DEFAULT, commit->title);
5846         return TRUE;
5849 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5850 static bool
5851 main_read(struct view *view, char *line)
5853         static struct graph graph;
5854         enum line_type type;
5855         struct commit *commit;
5857         if (!line) {
5858                 if (!view->lines && !view->prev)
5859                         die("No revisions match the given arguments.");
5860                 if (view->lines > 0) {
5861                         commit = view->line[view->lines - 1].data;
5862                         view->line[view->lines - 1].dirty = 1;
5863                         if (!commit->author) {
5864                                 view->lines--;
5865                                 free(commit);
5866                         }
5867                 }
5869                 done_graph(&graph);
5870                 return TRUE;
5871         }
5873         type = get_line_type(line);
5874         if (type == LINE_COMMIT) {
5875                 bool is_boundary;
5877                 commit = calloc(1, sizeof(struct commit));
5878                 if (!commit)
5879                         return FALSE;
5881                 line += STRING_SIZE("commit ");
5882                 is_boundary = *line == '-';
5883                 if (is_boundary)
5884                         line++;
5886                 string_copy_rev(commit->id, line);
5887                 commit->refs = get_ref_list(commit->id);
5888                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5889                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5890                 return TRUE;
5891         }
5893         if (!view->lines)
5894                 return TRUE;
5895         commit = view->line[view->lines - 1].data;
5897         switch (type) {
5898         case LINE_PARENT:
5899                 if (!graph.has_parents)
5900                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5901                 break;
5903         case LINE_AUTHOR:
5904                 parse_author_line(line + STRING_SIZE("author "),
5905                                   &commit->author, &commit->time);
5906                 graph_render_parents(&graph);
5907                 break;
5909         default:
5910                 /* Fill in the commit title if it has not already been set. */
5911                 if (commit->title[0])
5912                         break;
5914                 /* Require titles to start with a non-space character at the
5915                  * offset used by git log. */
5916                 if (strncmp(line, "    ", 4))
5917                         break;
5918                 line += 4;
5919                 /* Well, if the title starts with a whitespace character,
5920                  * try to be forgiving.  Otherwise we end up with no title. */
5921                 while (isspace(*line))
5922                         line++;
5923                 if (*line == '\0')
5924                         break;
5925                 /* FIXME: More graceful handling of titles; append "..." to
5926                  * shortened titles, etc. */
5928                 string_expand(commit->title, sizeof(commit->title), line, 1);
5929                 view->line[view->lines - 1].dirty = 1;
5930         }
5932         return TRUE;
5935 static enum request
5936 main_request(struct view *view, enum request request, struct line *line)
5938         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5940         switch (request) {
5941         case REQ_ENTER:
5942                 if (view_is_displayed(view) && display[0] != view)
5943                         maximize_view(view, TRUE);
5944                 open_view(view, REQ_VIEW_DIFF, flags);
5945                 break;
5946         case REQ_REFRESH:
5947                 load_refs();
5948                 refresh_view(view);
5949                 break;
5950         default:
5951                 return request;
5952         }
5954         return REQ_NONE;
5957 static bool
5958 grep_refs(struct ref_list *list, regex_t *regex)
5960         regmatch_t pmatch;
5961         size_t i;
5963         if (!opt_show_refs || !list)
5964                 return FALSE;
5966         for (i = 0; i < list->size; i++) {
5967                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5968                         return TRUE;
5969         }
5971         return FALSE;
5974 static bool
5975 main_grep(struct view *view, struct line *line)
5977         struct commit *commit = line->data;
5978         const char *text[] = {
5979                 commit->title,
5980                 opt_author ? commit->author : "",
5981                 mkdate(&commit->time, opt_date),
5982                 NULL
5983         };
5985         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5988 static void
5989 main_select(struct view *view, struct line *line)
5991         struct commit *commit = line->data;
5993         string_copy_rev(view->ref, commit->id);
5994         string_copy_rev(ref_commit, view->ref);
5997 static struct view_ops main_ops = {
5998         "commit",
5999         main_open,
6000         main_read,
6001         main_draw,
6002         main_request,
6003         main_grep,
6004         main_select,
6005 };
6008 /*
6009  * Status management
6010  */
6012 /* Whether or not the curses interface has been initialized. */
6013 static bool cursed = FALSE;
6015 /* Terminal hacks and workarounds. */
6016 static bool use_scroll_redrawwin;
6017 static bool use_scroll_status_wclear;
6019 /* The status window is used for polling keystrokes. */
6020 static WINDOW *status_win;
6022 /* Reading from the prompt? */
6023 static bool input_mode = FALSE;
6025 static bool status_empty = FALSE;
6027 /* Update status and title window. */
6028 static void
6029 report(const char *msg, ...)
6031         struct view *view = display[current_view];
6033         if (input_mode)
6034                 return;
6036         if (!view) {
6037                 char buf[SIZEOF_STR];
6038                 va_list args;
6040                 va_start(args, msg);
6041                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6042                         buf[sizeof(buf) - 1] = 0;
6043                         buf[sizeof(buf) - 2] = '.';
6044                         buf[sizeof(buf) - 3] = '.';
6045                         buf[sizeof(buf) - 4] = '.';
6046                 }
6047                 va_end(args);
6048                 die("%s", buf);
6049         }
6051         if (!status_empty || *msg) {
6052                 va_list args;
6054                 va_start(args, msg);
6056                 wmove(status_win, 0, 0);
6057                 if (view->has_scrolled && use_scroll_status_wclear)
6058                         wclear(status_win);
6059                 if (*msg) {
6060                         vwprintw(status_win, msg, args);
6061                         status_empty = FALSE;
6062                 } else {
6063                         status_empty = TRUE;
6064                 }
6065                 wclrtoeol(status_win);
6066                 wnoutrefresh(status_win);
6068                 va_end(args);
6069         }
6071         update_view_title(view);
6074 static void
6075 init_display(void)
6077         const char *term;
6078         int x, y;
6080         /* Initialize the curses library */
6081         if (isatty(STDIN_FILENO)) {
6082                 cursed = !!initscr();
6083                 opt_tty = stdin;
6084         } else {
6085                 /* Leave stdin and stdout alone when acting as a pager. */
6086                 opt_tty = fopen("/dev/tty", "r+");
6087                 if (!opt_tty)
6088                         die("Failed to open /dev/tty");
6089                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6090         }
6092         if (!cursed)
6093                 die("Failed to initialize curses");
6095         nonl();         /* Disable conversion and detect newlines from input. */
6096         cbreak();       /* Take input chars one at a time, no wait for \n */
6097         noecho();       /* Don't echo input */
6098         leaveok(stdscr, FALSE);
6100         if (has_colors())
6101                 init_colors();
6103         getmaxyx(stdscr, y, x);
6104         status_win = newwin(1, x, y - 1, 0);
6105         if (!status_win)
6106                 die("Failed to create status window");
6108         /* Enable keyboard mapping */
6109         keypad(status_win, TRUE);
6110         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6112 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6113         set_tabsize(opt_tab_size);
6114 #else
6115         TABSIZE = opt_tab_size;
6116 #endif
6118         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6119         if (term && !strcmp(term, "gnome-terminal")) {
6120                 /* In the gnome-terminal-emulator, the message from
6121                  * scrolling up one line when impossible followed by
6122                  * scrolling down one line causes corruption of the
6123                  * status line. This is fixed by calling wclear. */
6124                 use_scroll_status_wclear = TRUE;
6125                 use_scroll_redrawwin = FALSE;
6127         } else if (term && !strcmp(term, "xrvt-xpm")) {
6128                 /* No problems with full optimizations in xrvt-(unicode)
6129                  * and aterm. */
6130                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6132         } else {
6133                 /* When scrolling in (u)xterm the last line in the
6134                  * scrolling direction will update slowly. */
6135                 use_scroll_redrawwin = TRUE;
6136                 use_scroll_status_wclear = FALSE;
6137         }
6140 static int
6141 get_input(int prompt_position)
6143         struct view *view;
6144         int i, key, cursor_y, cursor_x;
6146         if (prompt_position)
6147                 input_mode = TRUE;
6149         while (TRUE) {
6150                 bool loading = FALSE;
6152                 foreach_view (view, i) {
6153                         update_view(view);
6154                         if (view_is_displayed(view) && view->has_scrolled &&
6155                             use_scroll_redrawwin)
6156                                 redrawwin(view->win);
6157                         view->has_scrolled = FALSE;
6158                         if (view->pipe)
6159                                 loading = TRUE;
6160                 }
6162                 /* Update the cursor position. */
6163                 if (prompt_position) {
6164                         getbegyx(status_win, cursor_y, cursor_x);
6165                         cursor_x = prompt_position;
6166                 } else {
6167                         view = display[current_view];
6168                         getbegyx(view->win, cursor_y, cursor_x);
6169                         cursor_x = view->width - 1;
6170                         cursor_y += view->lineno - view->offset;
6171                 }
6172                 setsyx(cursor_y, cursor_x);
6174                 /* Refresh, accept single keystroke of input */
6175                 doupdate();
6176                 nodelay(status_win, loading);
6177                 key = wgetch(status_win);
6179                 /* wgetch() with nodelay() enabled returns ERR when
6180                  * there's no input. */
6181                 if (key == ERR) {
6183                 } else if (key == KEY_RESIZE) {
6184                         int height, width;
6186                         getmaxyx(stdscr, height, width);
6188                         wresize(status_win, 1, width);
6189                         mvwin(status_win, height - 1, 0);
6190                         wnoutrefresh(status_win);
6191                         resize_display();
6192                         redraw_display(TRUE);
6194                 } else {
6195                         input_mode = FALSE;
6196                         return key;
6197                 }
6198         }
6201 static char *
6202 prompt_input(const char *prompt, input_handler handler, void *data)
6204         enum input_status status = INPUT_OK;
6205         static char buf[SIZEOF_STR];
6206         size_t pos = 0;
6208         buf[pos] = 0;
6210         while (status == INPUT_OK || status == INPUT_SKIP) {
6211                 int key;
6213                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6214                 wclrtoeol(status_win);
6216                 key = get_input(pos + 1);
6217                 switch (key) {
6218                 case KEY_RETURN:
6219                 case KEY_ENTER:
6220                 case '\n':
6221                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6222                         break;
6224                 case KEY_BACKSPACE:
6225                         if (pos > 0)
6226                                 buf[--pos] = 0;
6227                         else
6228                                 status = INPUT_CANCEL;
6229                         break;
6231                 case KEY_ESC:
6232                         status = INPUT_CANCEL;
6233                         break;
6235                 default:
6236                         if (pos >= sizeof(buf)) {
6237                                 report("Input string too long");
6238                                 return NULL;
6239                         }
6241                         status = handler(data, buf, key);
6242                         if (status == INPUT_OK)
6243                                 buf[pos++] = (char) key;
6244                 }
6245         }
6247         /* Clear the status window */
6248         status_empty = FALSE;
6249         report("");
6251         if (status == INPUT_CANCEL)
6252                 return NULL;
6254         buf[pos++] = 0;
6256         return buf;
6259 static enum input_status
6260 prompt_yesno_handler(void *data, char *buf, int c)
6262         if (c == 'y' || c == 'Y')
6263                 return INPUT_STOP;
6264         if (c == 'n' || c == 'N')
6265                 return INPUT_CANCEL;
6266         return INPUT_SKIP;
6269 static bool
6270 prompt_yesno(const char *prompt)
6272         char prompt2[SIZEOF_STR];
6274         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6275                 return FALSE;
6277         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6280 static enum input_status
6281 read_prompt_handler(void *data, char *buf, int c)
6283         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6286 static char *
6287 read_prompt(const char *prompt)
6289         return prompt_input(prompt, read_prompt_handler, NULL);
6292 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6294         enum input_status status = INPUT_OK;
6295         int size = 0;
6297         while (items[size].text)
6298                 size++;
6300         while (status == INPUT_OK) {
6301                 const struct menu_item *item = &items[*selected];
6302                 int key;
6303                 int i;
6305                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6306                           prompt, *selected + 1, size);
6307                 if (item->hotkey)
6308                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6309                 wprintw(status_win, "%s", item->text);
6310                 wclrtoeol(status_win);
6312                 key = get_input(COLS - 1);
6313                 switch (key) {
6314                 case KEY_RETURN:
6315                 case KEY_ENTER:
6316                 case '\n':
6317                         status = INPUT_STOP;
6318                         break;
6320                 case KEY_LEFT:
6321                 case KEY_UP:
6322                         *selected = *selected - 1;
6323                         if (*selected < 0)
6324                                 *selected = size - 1;
6325                         break;
6327                 case KEY_RIGHT:
6328                 case KEY_DOWN:
6329                         *selected = (*selected + 1) % size;
6330                         break;
6332                 case KEY_ESC:
6333                         status = INPUT_CANCEL;
6334                         break;
6336                 default:
6337                         for (i = 0; items[i].text; i++)
6338                                 if (items[i].hotkey == key) {
6339                                         *selected = i;
6340                                         status = INPUT_STOP;
6341                                         break;
6342                                 }
6343                 }
6344         }
6346         /* Clear the status window */
6347         status_empty = FALSE;
6348         report("");
6350         return status != INPUT_CANCEL;
6353 /*
6354  * Repository properties
6355  */
6357 static struct ref **refs = NULL;
6358 static size_t refs_size = 0;
6359 static struct ref *refs_head = NULL;
6361 static struct ref_list **ref_lists = NULL;
6362 static size_t ref_lists_size = 0;
6364 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6365 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6366 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6368 static int
6369 compare_refs(const void *ref1_, const void *ref2_)
6371         const struct ref *ref1 = *(const struct ref **)ref1_;
6372         const struct ref *ref2 = *(const struct ref **)ref2_;
6374         if (ref1->tag != ref2->tag)
6375                 return ref2->tag - ref1->tag;
6376         if (ref1->ltag != ref2->ltag)
6377                 return ref2->ltag - ref2->ltag;
6378         if (ref1->head != ref2->head)
6379                 return ref2->head - ref1->head;
6380         if (ref1->tracked != ref2->tracked)
6381                 return ref2->tracked - ref1->tracked;
6382         if (ref1->remote != ref2->remote)
6383                 return ref2->remote - ref1->remote;
6384         return strcmp(ref1->name, ref2->name);
6387 static void
6388 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6390         size_t i;
6392         for (i = 0; i < refs_size; i++)
6393                 if (!visitor(data, refs[i]))
6394                         break;
6397 static struct ref *
6398 get_ref_head()
6400         return refs_head;
6403 static struct ref_list *
6404 get_ref_list(const char *id)
6406         struct ref_list *list;
6407         size_t i;
6409         for (i = 0; i < ref_lists_size; i++)
6410                 if (!strcmp(id, ref_lists[i]->id))
6411                         return ref_lists[i];
6413         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6414                 return NULL;
6415         list = calloc(1, sizeof(*list));
6416         if (!list)
6417                 return NULL;
6419         for (i = 0; i < refs_size; i++) {
6420                 if (!strcmp(id, refs[i]->id) &&
6421                     realloc_refs_list(&list->refs, list->size, 1))
6422                         list->refs[list->size++] = refs[i];
6423         }
6425         if (!list->refs) {
6426                 free(list);
6427                 return NULL;
6428         }
6430         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6431         ref_lists[ref_lists_size++] = list;
6432         return list;
6435 static int
6436 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6438         struct ref *ref = NULL;
6439         bool tag = FALSE;
6440         bool ltag = FALSE;
6441         bool remote = FALSE;
6442         bool tracked = FALSE;
6443         bool head = FALSE;
6444         int from = 0, to = refs_size - 1;
6446         if (!prefixcmp(name, "refs/tags/")) {
6447                 if (!suffixcmp(name, namelen, "^{}")) {
6448                         namelen -= 3;
6449                         name[namelen] = 0;
6450                 } else {
6451                         ltag = TRUE;
6452                 }
6454                 tag = TRUE;
6455                 namelen -= STRING_SIZE("refs/tags/");
6456                 name    += STRING_SIZE("refs/tags/");
6458         } else if (!prefixcmp(name, "refs/remotes/")) {
6459                 remote = TRUE;
6460                 namelen -= STRING_SIZE("refs/remotes/");
6461                 name    += STRING_SIZE("refs/remotes/");
6462                 tracked  = !strcmp(opt_remote, name);
6464         } else if (!prefixcmp(name, "refs/heads/")) {
6465                 namelen -= STRING_SIZE("refs/heads/");
6466                 name    += STRING_SIZE("refs/heads/");
6467                 if (!strncmp(opt_head, name, namelen))
6468                         return OK;
6470         } else if (!strcmp(name, "HEAD")) {
6471                 head     = TRUE;
6472                 if (*opt_head) {
6473                         namelen  = strlen(opt_head);
6474                         name     = opt_head;
6475                 }
6476         }
6478         /* If we are reloading or it's an annotated tag, replace the
6479          * previous SHA1 with the resolved commit id; relies on the fact
6480          * git-ls-remote lists the commit id of an annotated tag right
6481          * before the commit id it points to. */
6482         while (from <= to) {
6483                 size_t pos = (to + from) / 2;
6484                 int cmp = strcmp(name, refs[pos]->name);
6486                 if (!cmp) {
6487                         ref = refs[pos];
6488                         break;
6489                 }
6491                 if (cmp < 0)
6492                         to = pos - 1;
6493                 else
6494                         from = pos + 1;
6495         }
6497         if (!ref) {
6498                 if (!realloc_refs(&refs, refs_size, 1))
6499                         return ERR;
6500                 ref = calloc(1, sizeof(*ref) + namelen);
6501                 if (!ref)
6502                         return ERR;
6503                 memmove(refs + from + 1, refs + from,
6504                         (refs_size - from) * sizeof(*refs));
6505                 refs[from] = ref;
6506                 strncpy(ref->name, name, namelen);
6507                 refs_size++;
6508         }
6510         ref->head = head;
6511         ref->tag = tag;
6512         ref->ltag = ltag;
6513         ref->remote = remote;
6514         ref->tracked = tracked;
6515         string_copy_rev(ref->id, id);
6517         if (head)
6518                 refs_head = ref;
6519         return OK;
6522 static int
6523 load_refs(void)
6525         const char *head_argv[] = {
6526                 "git", "symbolic-ref", "HEAD", NULL
6527         };
6528         static const char *ls_remote_argv[SIZEOF_ARG] = {
6529                 "git", "ls-remote", opt_git_dir, NULL
6530         };
6531         static bool init = FALSE;
6532         size_t i;
6534         if (!init) {
6535                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6536                         die("TIG_LS_REMOTE contains too many arguments");
6537                 init = TRUE;
6538         }
6540         if (!*opt_git_dir)
6541                 return OK;
6543         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6544             !prefixcmp(opt_head, "refs/heads/")) {
6545                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6547                 memmove(opt_head, offset, strlen(offset) + 1);
6548         }
6550         refs_head = NULL;
6551         for (i = 0; i < refs_size; i++)
6552                 refs[i]->id[0] = 0;
6554         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6555                 return ERR;
6557         /* Update the ref lists to reflect changes. */
6558         for (i = 0; i < ref_lists_size; i++) {
6559                 struct ref_list *list = ref_lists[i];
6560                 size_t old, new;
6562                 for (old = new = 0; old < list->size; old++)
6563                         if (!strcmp(list->id, list->refs[old]->id))
6564                                 list->refs[new++] = list->refs[old];
6565                 list->size = new;
6566         }
6568         return OK;
6571 static void
6572 set_remote_branch(const char *name, const char *value, size_t valuelen)
6574         if (!strcmp(name, ".remote")) {
6575                 string_ncopy(opt_remote, value, valuelen);
6577         } else if (*opt_remote && !strcmp(name, ".merge")) {
6578                 size_t from = strlen(opt_remote);
6580                 if (!prefixcmp(value, "refs/heads/"))
6581                         value += STRING_SIZE("refs/heads/");
6583                 if (!string_format_from(opt_remote, &from, "/%s", value))
6584                         opt_remote[0] = 0;
6585         }
6588 static void
6589 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6591         const char *argv[SIZEOF_ARG] = { name, "=" };
6592         int argc = 1 + (cmd == option_set_command);
6593         enum option_code error;
6595         if (!argv_from_string(argv, &argc, value))
6596                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6597         else
6598                 error = cmd(argc, argv);
6600         if (error != OPT_OK)
6601                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6604 static bool
6605 set_environment_variable(const char *name, const char *value)
6607         size_t len = strlen(name) + 1 + strlen(value) + 1;
6608         char *env = malloc(len);
6610         if (env &&
6611             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6612             putenv(env) == 0)
6613                 return TRUE;
6614         free(env);
6615         return FALSE;
6618 static void
6619 set_work_tree(const char *value)
6621         char cwd[SIZEOF_STR];
6623         if (!getcwd(cwd, sizeof(cwd)))
6624                 die("Failed to get cwd path: %s", strerror(errno));
6625         if (chdir(opt_git_dir) < 0)
6626                 die("Failed to chdir(%s): %s", strerror(errno));
6627         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6628                 die("Failed to get git path: %s", strerror(errno));
6629         if (chdir(cwd) < 0)
6630                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6631         if (chdir(value) < 0)
6632                 die("Failed to chdir(%s): %s", value, strerror(errno));
6633         if (!getcwd(cwd, sizeof(cwd)))
6634                 die("Failed to get cwd path: %s", strerror(errno));
6635         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6636                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6637         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6638                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6639         opt_is_inside_work_tree = TRUE;
6642 static int
6643 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6645         if (!strcmp(name, "i18n.commitencoding"))
6646                 string_ncopy(opt_encoding, value, valuelen);
6648         else if (!strcmp(name, "core.editor"))
6649                 string_ncopy(opt_editor, value, valuelen);
6651         else if (!strcmp(name, "core.worktree"))
6652                 set_work_tree(value);
6654         else if (!prefixcmp(name, "tig.color."))
6655                 set_repo_config_option(name + 10, value, option_color_command);
6657         else if (!prefixcmp(name, "tig.bind."))
6658                 set_repo_config_option(name + 9, value, option_bind_command);
6660         else if (!prefixcmp(name, "tig."))
6661                 set_repo_config_option(name + 4, value, option_set_command);
6663         else if (*opt_head && !prefixcmp(name, "branch.") &&
6664                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6665                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6667         return OK;
6670 static int
6671 load_git_config(void)
6673         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6675         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6678 static int
6679 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6681         if (!opt_git_dir[0]) {
6682                 string_ncopy(opt_git_dir, name, namelen);
6684         } else if (opt_is_inside_work_tree == -1) {
6685                 /* This can be 3 different values depending on the
6686                  * version of git being used. If git-rev-parse does not
6687                  * understand --is-inside-work-tree it will simply echo
6688                  * the option else either "true" or "false" is printed.
6689                  * Default to true for the unknown case. */
6690                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6692         } else if (*name == '.') {
6693                 string_ncopy(opt_cdup, name, namelen);
6695         } else {
6696                 string_ncopy(opt_prefix, name, namelen);
6697         }
6699         return OK;
6702 static int
6703 load_repo_info(void)
6705         const char *rev_parse_argv[] = {
6706                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6707                         "--show-cdup", "--show-prefix", NULL
6708         };
6710         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6714 /*
6715  * Main
6716  */
6718 static const char usage[] =
6719 "tig " TIG_VERSION " (" __DATE__ ")\n"
6720 "\n"
6721 "Usage: tig        [options] [revs] [--] [paths]\n"
6722 "   or: tig show   [options] [revs] [--] [paths]\n"
6723 "   or: tig blame  [options] [rev] [--] path\n"
6724 "   or: tig status\n"
6725 "   or: tig <      [git command output]\n"
6726 "\n"
6727 "Options:\n"
6728 "  -v, --version   Show version and exit\n"
6729 "  -h, --help      Show help message and exit";
6731 static void __NORETURN
6732 quit(int sig)
6734         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6735         if (cursed)
6736                 endwin();
6737         exit(0);
6740 static void __NORETURN
6741 die(const char *err, ...)
6743         va_list args;
6745         endwin();
6747         va_start(args, err);
6748         fputs("tig: ", stderr);
6749         vfprintf(stderr, err, args);
6750         fputs("\n", stderr);
6751         va_end(args);
6753         exit(1);
6756 static void
6757 warn(const char *msg, ...)
6759         va_list args;
6761         va_start(args, msg);
6762         fputs("tig warning: ", stderr);
6763         vfprintf(stderr, msg, args);
6764         fputs("\n", stderr);
6765         va_end(args);
6768 static int
6769 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6771         const char ***filter_args = data;
6773         return argv_append(filter_args, name) ? OK : ERR;
6776 static void
6777 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6779         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6780         const char **all_argv = NULL;
6782         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6783             !argv_append_array(&all_argv, argv) ||
6784             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6785                 die("Failed to split arguments");
6786         argv_free(all_argv);
6787         free(all_argv);
6790 static void
6791 filter_options(const char *argv[])
6793         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6794         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6795         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6798 static enum request
6799 parse_options(int argc, const char *argv[])
6801         enum request request = REQ_VIEW_MAIN;
6802         const char *subcommand;
6803         bool seen_dashdash = FALSE;
6804         const char **filter_argv = NULL;
6805         int i;
6807         if (!isatty(STDIN_FILENO))
6808                 return REQ_VIEW_PAGER;
6810         if (argc <= 1)
6811                 return REQ_VIEW_MAIN;
6813         subcommand = argv[1];
6814         if (!strcmp(subcommand, "status")) {
6815                 if (argc > 2)
6816                         warn("ignoring arguments after `%s'", subcommand);
6817                 return REQ_VIEW_STATUS;
6819         } else if (!strcmp(subcommand, "blame")) {
6820                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6821                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6822                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6824                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6825                         die("invalid number of options to blame\n\n%s", usage);
6827                 if (opt_rev_argv) {
6828                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6829                 }
6831                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6832                 return REQ_VIEW_BLAME;
6834         } else if (!strcmp(subcommand, "show")) {
6835                 request = REQ_VIEW_DIFF;
6837         } else {
6838                 subcommand = NULL;
6839         }
6841         for (i = 1 + !!subcommand; i < argc; i++) {
6842                 const char *opt = argv[i];
6844                 if (seen_dashdash) {
6845                         argv_append(&opt_file_argv, opt);
6846                         continue;
6848                 } else if (!strcmp(opt, "--")) {
6849                         seen_dashdash = TRUE;
6850                         continue;
6852                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6853                         printf("tig version %s\n", TIG_VERSION);
6854                         quit(0);
6856                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6857                         printf("%s\n", usage);
6858                         quit(0);
6860                 } else if (!strcmp(opt, "--all")) {
6861                         argv_append(&opt_rev_argv, opt);
6862                         continue;
6863                 }
6865                 if (!argv_append(&filter_argv, opt))
6866                         die("command too long");
6867         }
6869         if (filter_argv)
6870                 filter_options(filter_argv);
6872         return request;
6875 int
6876 main(int argc, const char *argv[])
6878         const char *codeset = "UTF-8";
6879         enum request request = parse_options(argc, argv);
6880         struct view *view;
6882         signal(SIGINT, quit);
6883         signal(SIGPIPE, SIG_IGN);
6885         if (setlocale(LC_ALL, "")) {
6886                 codeset = nl_langinfo(CODESET);
6887         }
6889         if (load_repo_info() == ERR)
6890                 die("Failed to load repo info.");
6892         if (load_options() == ERR)
6893                 die("Failed to load user config.");
6895         if (load_git_config() == ERR)
6896                 die("Failed to load repo config.");
6898         /* Require a git repository unless when running in pager mode. */
6899         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6900                 die("Not a git repository");
6902         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6903                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6904                 if (opt_iconv_in == ICONV_NONE)
6905                         die("Failed to initialize character set conversion");
6906         }
6908         if (codeset && strcmp(codeset, "UTF-8")) {
6909                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6910                 if (opt_iconv_out == ICONV_NONE)
6911                         die("Failed to initialize character set conversion");
6912         }
6914         if (load_refs() == ERR)
6915                 die("Failed to load refs.");
6917         init_display();
6919         while (view_driver(display[current_view], request)) {
6920                 int key = get_input(0);
6922                 view = display[current_view];
6923                 request = get_keybinding(view->keymap, key);
6925                 /* Some low-level request handling. This keeps access to
6926                  * status_win restricted. */
6927                 switch (request) {
6928                 case REQ_NONE:
6929                         report("Unknown key, press %s for help",
6930                                get_key(view->keymap, REQ_VIEW_HELP));
6931                         break;
6932                 case REQ_PROMPT:
6933                 {
6934                         char *cmd = read_prompt(":");
6936                         if (cmd && isdigit(*cmd)) {
6937                                 int lineno = view->lineno + 1;
6939                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6940                                         select_view_line(view, lineno - 1);
6941                                         report("");
6942                                 } else {
6943                                         report("Unable to parse '%s' as a line number", cmd);
6944                                 }
6946                         } else if (cmd) {
6947                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6948                                 const char *argv[SIZEOF_ARG] = { "git" };
6949                                 int argc = 1;
6951                                 /* When running random commands, initially show the
6952                                  * command in the title. However, it maybe later be
6953                                  * overwritten if a commit line is selected. */
6954                                 string_ncopy(next->ref, cmd, strlen(cmd));
6956                                 if (!argv_from_string(argv, &argc, cmd)) {
6957                                         report("Too many arguments");
6958                                 } else {
6959                                         open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6960                                 }
6961                         }
6963                         request = REQ_NONE;
6964                         break;
6965                 }
6966                 case REQ_SEARCH:
6967                 case REQ_SEARCH_BACK:
6968                 {
6969                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6970                         char *search = read_prompt(prompt);
6972                         if (search)
6973                                 string_ncopy(opt_search, search, strlen(search));
6974                         else if (*opt_search)
6975                                 request = request == REQ_SEARCH ?
6976                                         REQ_FIND_NEXT :
6977                                         REQ_FIND_PREV;
6978                         else
6979                                 request = REQ_NONE;
6980                         break;
6981                 }
6982                 default:
6983                         break;
6984                 }
6985         }
6987         quit(0);
6989         return 0;