Code

8b46fa7f79629ed6bde86251f838530c05dcc071
[tig.git] / tig.c
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU General Public License as
5  * published by the Free Software Foundation; either version 2 of
6  * the License, or (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24         char id[SIZEOF_REV];    /* Commit SHA1 ID */
25         unsigned int head:1;    /* Is it the current HEAD? */
26         unsigned int tag:1;     /* Is it a tag? */
27         unsigned int ltag:1;    /* If so, is the tag local? */
28         unsigned int remote:1;  /* Is it a remote ref? */
29         unsigned int tracked:1; /* Is it the remote for the current HEAD? */
30         char name[1];           /* Ref name; tag or head names are shortened. */
31 };
33 struct ref_list {
34         char id[SIZEOF_REV];    /* Commit SHA1 ID */
35         size_t size;            /* Number of refs. */
36         struct ref **refs;      /* References for this ID. */
37 };
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45         INPUT_OK,
46         INPUT_SKIP,
47         INPUT_STOP,
48         INPUT_CANCEL
49 };
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57         int hotkey;
58         const char *text;
59         void *data;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 enum graphic {
65         GRAPHIC_ASCII = 0,
66         GRAPHIC_DEFAULT,
67         GRAPHIC_UTF8
68 };
70 static const struct enum_map graphic_map[] = {
71 #define GRAPHIC_(name) ENUM_MAP(#name, GRAPHIC_##name)
72         GRAPHIC_(ASCII),
73         GRAPHIC_(DEFAULT),
74         GRAPHIC_(UTF8)
75 #undef  GRAPHIC_
76 };
78 #define DATE_INFO \
79         DATE_(NO), \
80         DATE_(DEFAULT), \
81         DATE_(LOCAL), \
82         DATE_(RELATIVE), \
83         DATE_(SHORT)
85 enum date {
86 #define DATE_(name) DATE_##name
87         DATE_INFO
88 #undef  DATE_
89 };
91 static const struct enum_map date_map[] = {
92 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
93         DATE_INFO
94 #undef  DATE_
95 };
97 struct time {
98         time_t sec;
99         int tz;
100 };
102 static inline int timecmp(const struct time *t1, const struct time *t2)
104         return t1->sec - t2->sec;
107 static const char *
108 mkdate(const struct time *time, enum date date)
110         static char buf[DATE_COLS + 1];
111         static const struct enum_map reldate[] = {
112                 { "second", 1,                  60 * 2 },
113                 { "minute", 60,                 60 * 60 * 2 },
114                 { "hour",   60 * 60,            60 * 60 * 24 * 2 },
115                 { "day",    60 * 60 * 24,       60 * 60 * 24 * 7 * 2 },
116                 { "week",   60 * 60 * 24 * 7,   60 * 60 * 24 * 7 * 5 },
117                 { "month",  60 * 60 * 24 * 30,  60 * 60 * 24 * 30 * 12 },
118         };
119         struct tm tm;
121         if (!date || !time || !time->sec)
122                 return "";
124         if (date == DATE_RELATIVE) {
125                 struct timeval now;
126                 time_t date = time->sec + time->tz;
127                 time_t seconds;
128                 int i;
130                 gettimeofday(&now, NULL);
131                 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
132                 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
133                         if (seconds >= reldate[i].value)
134                                 continue;
136                         seconds /= reldate[i].namelen;
137                         if (!string_format(buf, "%ld %s%s %s",
138                                            seconds, reldate[i].name,
139                                            seconds > 1 ? "s" : "",
140                                            now.tv_sec >= date ? "ago" : "ahead"))
141                                 break;
142                         return buf;
143                 }
144         }
146         if (date == DATE_LOCAL) {
147                 time_t date = time->sec + time->tz;
148                 localtime_r(&date, &tm);
149         }
150         else {
151                 gmtime_r(&time->sec, &tm);
152         }
153         return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
157 #define AUTHOR_VALUES \
158         AUTHOR_(NO), \
159         AUTHOR_(FULL), \
160         AUTHOR_(ABBREVIATED)
162 enum author {
163 #define AUTHOR_(name) AUTHOR_##name
164         AUTHOR_VALUES,
165 #undef  AUTHOR_
166         AUTHOR_DEFAULT = AUTHOR_FULL
167 };
169 static const struct enum_map author_map[] = {
170 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
171         AUTHOR_VALUES
172 #undef  AUTHOR_
173 };
175 static const char *
176 get_author_initials(const char *author)
178         static char initials[AUTHOR_COLS * 6 + 1];
179         size_t pos = 0;
180         const char *end = strchr(author, '\0');
182 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
184         memset(initials, 0, sizeof(initials));
185         while (author < end) {
186                 unsigned char bytes;
187                 size_t i;
189                 while (is_initial_sep(*author))
190                         author++;
192                 bytes = utf8_char_length(author, end);
193                 if (bytes < sizeof(initials) - 1 - pos) {
194                         while (bytes--) {
195                                 initials[pos++] = *author++;
196                         }
197                 }
199                 for (i = pos; author < end && !is_initial_sep(*author); author++) {
200                         if (i < sizeof(initials) - 1)
201                                 initials[i++] = *author;
202                 }
204                 initials[i++] = 0;
205         }
207         return initials;
211 /*
212  * User requests
213  */
215 #define REQ_INFO \
216         /* XXX: Keep the view request first and in sync with views[]. */ \
217         REQ_GROUP("View switching") \
218         REQ_(VIEW_MAIN,         "Show main view"), \
219         REQ_(VIEW_DIFF,         "Show diff view"), \
220         REQ_(VIEW_LOG,          "Show log view"), \
221         REQ_(VIEW_TREE,         "Show tree view"), \
222         REQ_(VIEW_BLOB,         "Show blob view"), \
223         REQ_(VIEW_BLAME,        "Show blame view"), \
224         REQ_(VIEW_BRANCH,       "Show branch view"), \
225         REQ_(VIEW_HELP,         "Show help page"), \
226         REQ_(VIEW_PAGER,        "Show pager view"), \
227         REQ_(VIEW_STATUS,       "Show status view"), \
228         REQ_(VIEW_STAGE,        "Show stage view"), \
229         \
230         REQ_GROUP("View manipulation") \
231         REQ_(ENTER,             "Enter current line and scroll"), \
232         REQ_(NEXT,              "Move to next"), \
233         REQ_(PREVIOUS,          "Move to previous"), \
234         REQ_(PARENT,            "Move to parent"), \
235         REQ_(VIEW_NEXT,         "Move focus to next view"), \
236         REQ_(REFRESH,           "Reload and refresh"), \
237         REQ_(MAXIMIZE,          "Maximize the current view"), \
238         REQ_(VIEW_CLOSE,        "Close the current view"), \
239         REQ_(QUIT,              "Close all views and quit"), \
240         \
241         REQ_GROUP("View specific requests") \
242         REQ_(STATUS_UPDATE,     "Update file status"), \
243         REQ_(STATUS_REVERT,     "Revert file changes"), \
244         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
245         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
246         \
247         REQ_GROUP("Cursor navigation") \
248         REQ_(MOVE_UP,           "Move cursor one line up"), \
249         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
250         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
251         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
252         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
253         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
254         \
255         REQ_GROUP("Scrolling") \
256         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
257         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
258         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
259         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
260         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
261         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
262         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
263         \
264         REQ_GROUP("Searching") \
265         REQ_(SEARCH,            "Search the view"), \
266         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
267         REQ_(FIND_NEXT,         "Find next search match"), \
268         REQ_(FIND_PREV,         "Find previous search match"), \
269         \
270         REQ_GROUP("Option manipulation") \
271         REQ_(OPTIONS,           "Open option menu"), \
272         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
273         REQ_(TOGGLE_DATE,       "Toggle date display"), \
274         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
275         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
276         REQ_(TOGGLE_GRAPHIC,    "Toggle (line) graphics mode"), \
277         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
278         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
279         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
280         \
281         REQ_GROUP("Misc") \
282         REQ_(PROMPT,            "Bring up the prompt"), \
283         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
284         REQ_(SHOW_VERSION,      "Show version information"), \
285         REQ_(STOP_LOADING,      "Stop all loading views"), \
286         REQ_(EDIT,              "Open in editor"), \
287         REQ_(NONE,              "Do nothing")
290 /* User action requests. */
291 enum request {
292 #define REQ_GROUP(help)
293 #define REQ_(req, help) REQ_##req
295         /* Offset all requests to avoid conflicts with ncurses getch values. */
296         REQ_UNKNOWN = KEY_MAX + 1,
297         REQ_OFFSET,
298         REQ_INFO
300 #undef  REQ_GROUP
301 #undef  REQ_
302 };
304 struct request_info {
305         enum request request;
306         const char *name;
307         int namelen;
308         const char *help;
309 };
311 static const struct request_info req_info[] = {
312 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
313 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
314         REQ_INFO
315 #undef  REQ_GROUP
316 #undef  REQ_
317 };
319 static enum request
320 get_request(const char *name)
322         int namelen = strlen(name);
323         int i;
325         for (i = 0; i < ARRAY_SIZE(req_info); i++)
326                 if (enum_equals(req_info[i], name, namelen))
327                         return req_info[i].request;
329         return REQ_UNKNOWN;
333 /*
334  * Options
335  */
337 /* Option and state variables. */
338 static enum graphic opt_line_graphics   = GRAPHIC_DEFAULT;
339 static enum date opt_date               = DATE_DEFAULT;
340 static enum author opt_author           = AUTHOR_DEFAULT;
341 static bool opt_rev_graph               = TRUE;
342 static bool opt_line_number             = FALSE;
343 static bool opt_show_refs               = TRUE;
344 static bool opt_untracked_dirs_content  = TRUE;
345 static int opt_num_interval             = 5;
346 static double opt_hscroll               = 0.50;
347 static double opt_scale_split_view      = 2.0 / 3.0;
348 static int opt_tab_size                 = 8;
349 static int opt_author_cols              = AUTHOR_COLS;
350 static char opt_path[SIZEOF_STR]        = "";
351 static char opt_file[SIZEOF_STR]        = "";
352 static char opt_ref[SIZEOF_REF]         = "";
353 static char opt_head[SIZEOF_REF]        = "";
354 static char opt_remote[SIZEOF_REF]      = "";
355 static char opt_encoding[20]            = "UTF-8";
356 static iconv_t opt_iconv_in             = ICONV_NONE;
357 static iconv_t opt_iconv_out            = ICONV_NONE;
358 static char opt_search[SIZEOF_STR]      = "";
359 static char opt_cdup[SIZEOF_STR]        = "";
360 static char opt_prefix[SIZEOF_STR]      = "";
361 static char opt_git_dir[SIZEOF_STR]     = "";
362 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
363 static char opt_editor[SIZEOF_STR]      = "";
364 static FILE *opt_tty                    = NULL;
365 static const char **opt_diff_argv       = NULL;
366 static const char **opt_rev_argv        = NULL;
367 static const char **opt_file_argv       = NULL;
368 static const char **opt_blame_argv      = NULL;
370 #define is_initial_commit()     (!get_ref_head())
371 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
374 /*
375  * Line-oriented content detection.
376  */
378 #define LINE_INFO \
379 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
380 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
381 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
382 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
383 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
384 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
385 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
386 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
387 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
388 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
389 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
390 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
391 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
392 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
393 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
394 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
395 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
396 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
397 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
398 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
399 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
400 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
401 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
402 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
403 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
404 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
405 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
406 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
407 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
408 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
409 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
410 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
411 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
412 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
413 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
414 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
415 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
416 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
417 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
418 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
419 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
420 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
421 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
422 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
423 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
424 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
425 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
426 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
427 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
428 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
429 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
430 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
431 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
432 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
433 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
434 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
435 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
436 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
437 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
438 LINE(GRAPH_LINE_0, "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
439 LINE(GRAPH_LINE_1, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
440 LINE(GRAPH_LINE_2, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
441 LINE(GRAPH_LINE_3, "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
442 LINE(GRAPH_LINE_4, "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
443 LINE(GRAPH_LINE_5, "",                  COLOR_WHITE,    COLOR_DEFAULT,  0), \
444 LINE(GRAPH_LINE_6, "",                  COLOR_RED,      COLOR_DEFAULT,  0), \
445 LINE(GRAPH_COMMIT, "",                  COLOR_BLUE,     COLOR_DEFAULT,  0)
447 enum line_type {
448 #define LINE(type, line, fg, bg, attr) \
449         LINE_##type
450         LINE_INFO,
451         LINE_NONE
452 #undef  LINE
453 };
455 struct line_info {
456         const char *name;       /* Option name. */
457         int namelen;            /* Size of option name. */
458         const char *line;       /* The start of line to match. */
459         int linelen;            /* Size of string to match. */
460         int fg, bg, attr;       /* Color and text attributes for the lines. */
461 };
463 static struct line_info line_info[] = {
464 #define LINE(type, line, fg, bg, attr) \
465         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
466         LINE_INFO
467 #undef  LINE
468 };
470 static enum line_type
471 get_line_type(const char *line)
473         int linelen = strlen(line);
474         enum line_type type;
476         for (type = 0; type < ARRAY_SIZE(line_info); type++)
477                 /* Case insensitive search matches Signed-off-by lines better. */
478                 if (linelen >= line_info[type].linelen &&
479                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
480                         return type;
482         return LINE_DEFAULT;
485 static inline int
486 get_line_attr(enum line_type type)
488         assert(type < ARRAY_SIZE(line_info));
489         return COLOR_PAIR(type) | line_info[type].attr;
492 static struct line_info *
493 get_line_info(const char *name)
495         size_t namelen = strlen(name);
496         enum line_type type;
498         for (type = 0; type < ARRAY_SIZE(line_info); type++)
499                 if (enum_equals(line_info[type], name, namelen))
500                         return &line_info[type];
502         return NULL;
505 static void
506 init_colors(void)
508         int default_bg = line_info[LINE_DEFAULT].bg;
509         int default_fg = line_info[LINE_DEFAULT].fg;
510         enum line_type type;
512         start_color();
514         if (assume_default_colors(default_fg, default_bg) == ERR) {
515                 default_bg = COLOR_BLACK;
516                 default_fg = COLOR_WHITE;
517         }
519         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
520                 struct line_info *info = &line_info[type];
521                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
522                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
524                 init_pair(type, fg, bg);
525         }
528 struct line {
529         enum line_type type;
531         /* State flags */
532         unsigned int selected:1;
533         unsigned int dirty:1;
534         unsigned int cleareol:1;
535         unsigned int other:16;
537         void *data;             /* User data */
538 };
541 /*
542  * Keys
543  */
545 struct keybinding {
546         int alias;
547         enum request request;
548 };
550 static struct keybinding default_keybindings[] = {
551         /* View switching */
552         { 'm',          REQ_VIEW_MAIN },
553         { 'd',          REQ_VIEW_DIFF },
554         { 'l',          REQ_VIEW_LOG },
555         { 't',          REQ_VIEW_TREE },
556         { 'f',          REQ_VIEW_BLOB },
557         { 'B',          REQ_VIEW_BLAME },
558         { 'H',          REQ_VIEW_BRANCH },
559         { 'p',          REQ_VIEW_PAGER },
560         { 'h',          REQ_VIEW_HELP },
561         { 'S',          REQ_VIEW_STATUS },
562         { 'c',          REQ_VIEW_STAGE },
564         /* View manipulation */
565         { 'q',          REQ_VIEW_CLOSE },
566         { KEY_TAB,      REQ_VIEW_NEXT },
567         { KEY_RETURN,   REQ_ENTER },
568         { KEY_UP,       REQ_PREVIOUS },
569         { KEY_CTL('P'), REQ_PREVIOUS },
570         { KEY_DOWN,     REQ_NEXT },
571         { KEY_CTL('N'), REQ_NEXT },
572         { 'R',          REQ_REFRESH },
573         { KEY_F(5),     REQ_REFRESH },
574         { 'O',          REQ_MAXIMIZE },
576         /* Cursor navigation */
577         { 'k',          REQ_MOVE_UP },
578         { 'j',          REQ_MOVE_DOWN },
579         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
580         { KEY_END,      REQ_MOVE_LAST_LINE },
581         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
582         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
583         { ' ',          REQ_MOVE_PAGE_DOWN },
584         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
585         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
586         { 'b',          REQ_MOVE_PAGE_UP },
587         { '-',          REQ_MOVE_PAGE_UP },
589         /* Scrolling */
590         { '|',          REQ_SCROLL_FIRST_COL },
591         { KEY_LEFT,     REQ_SCROLL_LEFT },
592         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
593         { KEY_IC,       REQ_SCROLL_LINE_UP },
594         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
595         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
596         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
597         { 'w',          REQ_SCROLL_PAGE_UP },
598         { 's',          REQ_SCROLL_PAGE_DOWN },
600         /* Searching */
601         { '/',          REQ_SEARCH },
602         { '?',          REQ_SEARCH_BACK },
603         { 'n',          REQ_FIND_NEXT },
604         { 'N',          REQ_FIND_PREV },
606         /* Misc */
607         { 'Q',          REQ_QUIT },
608         { 'z',          REQ_STOP_LOADING },
609         { 'v',          REQ_SHOW_VERSION },
610         { 'r',          REQ_SCREEN_REDRAW },
611         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
612         { 'o',          REQ_OPTIONS },
613         { '.',          REQ_TOGGLE_LINENO },
614         { 'D',          REQ_TOGGLE_DATE },
615         { 'A',          REQ_TOGGLE_AUTHOR },
616         { 'g',          REQ_TOGGLE_REV_GRAPH },
617         { '~',          REQ_TOGGLE_GRAPHIC },
618         { 'F',          REQ_TOGGLE_REFS },
619         { 'I',          REQ_TOGGLE_SORT_ORDER },
620         { 'i',          REQ_TOGGLE_SORT_FIELD },
621         { ':',          REQ_PROMPT },
622         { 'u',          REQ_STATUS_UPDATE },
623         { '!',          REQ_STATUS_REVERT },
624         { 'M',          REQ_STATUS_MERGE },
625         { '@',          REQ_STAGE_NEXT },
626         { ',',          REQ_PARENT },
627         { 'e',          REQ_EDIT },
628 };
630 #define KEYMAP_INFO \
631         KEYMAP_(GENERIC), \
632         KEYMAP_(MAIN), \
633         KEYMAP_(DIFF), \
634         KEYMAP_(LOG), \
635         KEYMAP_(TREE), \
636         KEYMAP_(BLOB), \
637         KEYMAP_(BLAME), \
638         KEYMAP_(BRANCH), \
639         KEYMAP_(PAGER), \
640         KEYMAP_(HELP), \
641         KEYMAP_(STATUS), \
642         KEYMAP_(STAGE)
644 enum keymap {
645 #define KEYMAP_(name) KEYMAP_##name
646         KEYMAP_INFO
647 #undef  KEYMAP_
648 };
650 static const struct enum_map keymap_table[] = {
651 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
652         KEYMAP_INFO
653 #undef  KEYMAP_
654 };
656 #define set_keymap(map, name) map_enum(map, keymap_table, name)
658 struct keybinding_table {
659         struct keybinding *data;
660         size_t size;
661 };
663 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
665 static void
666 add_keybinding(enum keymap keymap, enum request request, int key)
668         struct keybinding_table *table = &keybindings[keymap];
669         size_t i;
671         for (i = 0; i < keybindings[keymap].size; i++) {
672                 if (keybindings[keymap].data[i].alias == key) {
673                         keybindings[keymap].data[i].request = request;
674                         return;
675                 }
676         }
678         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
679         if (!table->data)
680                 die("Failed to allocate keybinding");
681         table->data[table->size].alias = key;
682         table->data[table->size++].request = request;
684         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
685                 int i;
687                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
688                         if (default_keybindings[i].alias == key)
689                                 default_keybindings[i].request = REQ_NONE;
690         }
693 /* Looks for a key binding first in the given map, then in the generic map, and
694  * lastly in the default keybindings. */
695 static enum request
696 get_keybinding(enum keymap keymap, int key)
698         size_t i;
700         for (i = 0; i < keybindings[keymap].size; i++)
701                 if (keybindings[keymap].data[i].alias == key)
702                         return keybindings[keymap].data[i].request;
704         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
705                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
706                         return keybindings[KEYMAP_GENERIC].data[i].request;
708         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
709                 if (default_keybindings[i].alias == key)
710                         return default_keybindings[i].request;
712         return (enum request) key;
716 struct key {
717         const char *name;
718         int value;
719 };
721 static const struct key key_table[] = {
722         { "Enter",      KEY_RETURN },
723         { "Space",      ' ' },
724         { "Backspace",  KEY_BACKSPACE },
725         { "Tab",        KEY_TAB },
726         { "Escape",     KEY_ESC },
727         { "Left",       KEY_LEFT },
728         { "Right",      KEY_RIGHT },
729         { "Up",         KEY_UP },
730         { "Down",       KEY_DOWN },
731         { "Insert",     KEY_IC },
732         { "Delete",     KEY_DC },
733         { "Hash",       '#' },
734         { "Home",       KEY_HOME },
735         { "End",        KEY_END },
736         { "PageUp",     KEY_PPAGE },
737         { "PageDown",   KEY_NPAGE },
738         { "F1",         KEY_F(1) },
739         { "F2",         KEY_F(2) },
740         { "F3",         KEY_F(3) },
741         { "F4",         KEY_F(4) },
742         { "F5",         KEY_F(5) },
743         { "F6",         KEY_F(6) },
744         { "F7",         KEY_F(7) },
745         { "F8",         KEY_F(8) },
746         { "F9",         KEY_F(9) },
747         { "F10",        KEY_F(10) },
748         { "F11",        KEY_F(11) },
749         { "F12",        KEY_F(12) },
750 };
752 static int
753 get_key_value(const char *name)
755         int i;
757         for (i = 0; i < ARRAY_SIZE(key_table); i++)
758                 if (!strcasecmp(key_table[i].name, name))
759                         return key_table[i].value;
761         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
762                 return (int)name[1] & 0x1f;
763         if (strlen(name) == 1 && isprint(*name))
764                 return (int) *name;
765         return ERR;
768 static const char *
769 get_key_name(int key_value)
771         static char key_char[] = "'X'\0";
772         const char *seq = NULL;
773         int key;
775         for (key = 0; key < ARRAY_SIZE(key_table); key++)
776                 if (key_table[key].value == key_value)
777                         seq = key_table[key].name;
779         if (seq == NULL && key_value < 0x7f) {
780                 char *s = key_char + 1;
782                 if (key_value >= 0x20) {
783                         *s++ = key_value;
784                 } else {
785                         *s++ = '^';
786                         *s++ = 0x40 | (key_value & 0x1f);
787                 }
788                 *s++ = '\'';
789                 *s++ = '\0';
790                 seq = key_char;
791         }
793         return seq ? seq : "(no key)";
796 static bool
797 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
799         const char *sep = *pos > 0 ? ", " : "";
800         const char *keyname = get_key_name(keybinding->alias);
802         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
805 static bool
806 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
807                            enum keymap keymap, bool all)
809         int i;
811         for (i = 0; i < keybindings[keymap].size; i++) {
812                 if (keybindings[keymap].data[i].request == request) {
813                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
814                                 return FALSE;
815                         if (!all)
816                                 break;
817                 }
818         }
820         return TRUE;
823 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
825 static const char *
826 get_keys(enum keymap keymap, enum request request, bool all)
828         static char buf[BUFSIZ];
829         size_t pos = 0;
830         int i;
832         buf[pos] = 0;
834         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
835                 return "Too many keybindings!";
836         if (pos > 0 && !all)
837                 return buf;
839         if (keymap != KEYMAP_GENERIC) {
840                 /* Only the generic keymap includes the default keybindings when
841                  * listing all keys. */
842                 if (all)
843                         return buf;
845                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
846                         return "Too many keybindings!";
847                 if (pos)
848                         return buf;
849         }
851         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
852                 if (default_keybindings[i].request == request) {
853                         if (!append_key(buf, &pos, &default_keybindings[i]))
854                                 return "Too many keybindings!";
855                         if (!all)
856                                 return buf;
857                 }
858         }
860         return buf;
863 struct run_request {
864         enum keymap keymap;
865         int key;
866         const char **argv;
867 };
869 static struct run_request *run_request;
870 static size_t run_requests;
872 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
874 static enum request
875 add_run_request(enum keymap keymap, int key, const char **argv)
877         struct run_request *req;
879         if (!realloc_run_requests(&run_request, run_requests, 1))
880                 return REQ_NONE;
882         req = &run_request[run_requests];
883         req->keymap = keymap;
884         req->key = key;
885         req->argv = NULL;
887         if (!argv_copy(&req->argv, argv))
888                 return REQ_NONE;
890         return REQ_NONE + ++run_requests;
893 static struct run_request *
894 get_run_request(enum request request)
896         if (request <= REQ_NONE)
897                 return NULL;
898         return &run_request[request - REQ_NONE - 1];
901 static void
902 add_builtin_run_requests(void)
904         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
905         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
906         const char *commit[] = { "git", "commit", NULL };
907         const char *gc[] = { "git", "gc", NULL };
908         struct run_request reqs[] = {
909                 { KEYMAP_MAIN,    'C', cherry_pick },
910                 { KEYMAP_STATUS,  'C', commit },
911                 { KEYMAP_BRANCH,  'C', checkout },
912                 { KEYMAP_GENERIC, 'G', gc },
913         };
914         int i;
916         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
917                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
919                 if (req != reqs[i].key)
920                         continue;
921                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
922                 if (req != REQ_NONE)
923                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
924         }
927 /*
928  * User config file handling.
929  */
931 #define OPT_ERR_INFO \
932         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
933         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
934         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
935         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
936         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
937         OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
938         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
939         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
940         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
941         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
942         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
943         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
944         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
945         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
946         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
947         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
948         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
950 enum option_code {
951 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
952         OPT_ERR_INFO
953 #undef  OPT_ERR_
954         OPT_OK
955 };
957 static const char *option_errors[] = {
958 #define OPT_ERR_(name, msg) msg
959         OPT_ERR_INFO
960 #undef  OPT_ERR_
961 };
963 static const struct enum_map color_map[] = {
964 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
965         COLOR_MAP(DEFAULT),
966         COLOR_MAP(BLACK),
967         COLOR_MAP(BLUE),
968         COLOR_MAP(CYAN),
969         COLOR_MAP(GREEN),
970         COLOR_MAP(MAGENTA),
971         COLOR_MAP(RED),
972         COLOR_MAP(WHITE),
973         COLOR_MAP(YELLOW),
974 };
976 static const struct enum_map attr_map[] = {
977 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
978         ATTR_MAP(NORMAL),
979         ATTR_MAP(BLINK),
980         ATTR_MAP(BOLD),
981         ATTR_MAP(DIM),
982         ATTR_MAP(REVERSE),
983         ATTR_MAP(STANDOUT),
984         ATTR_MAP(UNDERLINE),
985 };
987 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
989 static enum option_code
990 parse_step(double *opt, const char *arg)
992         *opt = atoi(arg);
993         if (!strchr(arg, '%'))
994                 return OPT_OK;
996         /* "Shift down" so 100% and 1 does not conflict. */
997         *opt = (*opt - 1) / 100;
998         if (*opt >= 1.0) {
999                 *opt = 0.99;
1000                 return OPT_ERR_INVALID_STEP_VALUE;
1001         }
1002         if (*opt < 0.0) {
1003                 *opt = 1;
1004                 return OPT_ERR_INVALID_STEP_VALUE;
1005         }
1006         return OPT_OK;
1009 static enum option_code
1010 parse_int(int *opt, const char *arg, int min, int max)
1012         int value = atoi(arg);
1014         if (min <= value && value <= max) {
1015                 *opt = value;
1016                 return OPT_OK;
1017         }
1019         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1022 static bool
1023 set_color(int *color, const char *name)
1025         if (map_enum(color, color_map, name))
1026                 return TRUE;
1027         if (!prefixcmp(name, "color"))
1028                 return parse_int(color, name + 5, 0, 255) == OK;
1029         return FALSE;
1032 /* Wants: object fgcolor bgcolor [attribute] */
1033 static enum option_code
1034 option_color_command(int argc, const char *argv[])
1036         struct line_info *info;
1038         if (argc < 3)
1039                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1041         info = get_line_info(argv[0]);
1042         if (!info) {
1043                 static const struct enum_map obsolete[] = {
1044                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1045                         ENUM_MAP("main-date",   LINE_DATE),
1046                         ENUM_MAP("main-author", LINE_AUTHOR),
1047                 };
1048                 int index;
1050                 if (!map_enum(&index, obsolete, argv[0]))
1051                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1052                 info = &line_info[index];
1053         }
1055         if (!set_color(&info->fg, argv[1]) ||
1056             !set_color(&info->bg, argv[2]))
1057                 return OPT_ERR_UNKNOWN_COLOR;
1059         info->attr = 0;
1060         while (argc-- > 3) {
1061                 int attr;
1063                 if (!set_attribute(&attr, argv[argc]))
1064                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1065                 info->attr |= attr;
1066         }
1068         return OPT_OK;
1071 static enum option_code
1072 parse_bool(bool *opt, const char *arg)
1074         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1075                 ? TRUE : FALSE;
1076         return OPT_OK;
1079 static enum option_code
1080 parse_enum_do(unsigned int *opt, const char *arg,
1081               const struct enum_map *map, size_t map_size)
1083         bool is_true;
1085         assert(map_size > 1);
1087         if (map_enum_do(map, map_size, (int *) opt, arg))
1088                 return OPT_OK;
1090         parse_bool(&is_true, arg);
1091         *opt = is_true ? map[1].value : map[0].value;
1092         return OPT_OK;
1095 #define parse_enum(opt, arg, map) \
1096         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1098 static enum option_code
1099 parse_string(char *opt, const char *arg, size_t optsize)
1101         int arglen = strlen(arg);
1103         switch (arg[0]) {
1104         case '\"':
1105         case '\'':
1106                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1107                         return OPT_ERR_UNMATCHED_QUOTATION;
1108                 arg += 1; arglen -= 2;
1109         default:
1110                 string_ncopy_do(opt, optsize, arg, arglen);
1111                 return OPT_OK;
1112         }
1115 static enum option_code
1116 parse_args(const char ***args, const char *argv[])
1118         if (*args == NULL && !argv_copy(args, argv))
1119                 return OPT_ERR_OUT_OF_MEMORY;
1120         return OPT_OK;
1123 /* Wants: name = value */
1124 static enum option_code
1125 option_set_command(int argc, const char *argv[])
1127         if (argc < 3)
1128                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1130         if (strcmp(argv[1], "="))
1131                 return OPT_ERR_NO_VALUE_ASSIGNED;
1133         if (!strcmp(argv[0], "blame-options"))
1134                 return parse_args(&opt_blame_argv, argv + 2);
1136         if (argc != 3)
1137                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1139         if (!strcmp(argv[0], "show-author"))
1140                 return parse_enum(&opt_author, argv[2], author_map);
1142         if (!strcmp(argv[0], "show-date"))
1143                 return parse_enum(&opt_date, argv[2], date_map);
1145         if (!strcmp(argv[0], "show-rev-graph"))
1146                 return parse_bool(&opt_rev_graph, argv[2]);
1148         if (!strcmp(argv[0], "show-refs"))
1149                 return parse_bool(&opt_show_refs, argv[2]);
1151         if (!strcmp(argv[0], "show-line-numbers"))
1152                 return parse_bool(&opt_line_number, argv[2]);
1154         if (!strcmp(argv[0], "line-graphics"))
1155                 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1157         if (!strcmp(argv[0], "line-number-interval"))
1158                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1160         if (!strcmp(argv[0], "author-width"))
1161                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1163         if (!strcmp(argv[0], "horizontal-scroll"))
1164                 return parse_step(&opt_hscroll, argv[2]);
1166         if (!strcmp(argv[0], "split-view-height"))
1167                 return parse_step(&opt_scale_split_view, argv[2]);
1169         if (!strcmp(argv[0], "tab-size"))
1170                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1172         if (!strcmp(argv[0], "commit-encoding"))
1173                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1175         if (!strcmp(argv[0], "status-untracked-dirs"))
1176                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1178         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1181 /* Wants: mode request key */
1182 static enum option_code
1183 option_bind_command(int argc, const char *argv[])
1185         enum request request;
1186         int keymap = -1;
1187         int key;
1189         if (argc < 3)
1190                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1192         if (!set_keymap(&keymap, argv[0]))
1193                 return OPT_ERR_UNKNOWN_KEY_MAP;
1195         key = get_key_value(argv[1]);
1196         if (key == ERR)
1197                 return OPT_ERR_UNKNOWN_KEY;
1199         request = get_request(argv[2]);
1200         if (request == REQ_UNKNOWN) {
1201                 static const struct enum_map obsolete[] = {
1202                         ENUM_MAP("cherry-pick",         REQ_NONE),
1203                         ENUM_MAP("screen-resize",       REQ_NONE),
1204                         ENUM_MAP("tree-parent",         REQ_PARENT),
1205                 };
1206                 int alias;
1208                 if (map_enum(&alias, obsolete, argv[2])) {
1209                         if (alias != REQ_NONE)
1210                                 add_keybinding(keymap, alias, key);
1211                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1212                 }
1213         }
1214         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1215                 request = add_run_request(keymap, key, argv + 2);
1216         if (request == REQ_UNKNOWN)
1217                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1219         add_keybinding(keymap, request, key);
1221         return OPT_OK;
1224 static enum option_code
1225 set_option(const char *opt, char *value)
1227         const char *argv[SIZEOF_ARG];
1228         int argc = 0;
1230         if (!argv_from_string(argv, &argc, value))
1231                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1233         if (!strcmp(opt, "color"))
1234                 return option_color_command(argc, argv);
1236         if (!strcmp(opt, "set"))
1237                 return option_set_command(argc, argv);
1239         if (!strcmp(opt, "bind"))
1240                 return option_bind_command(argc, argv);
1242         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1245 struct config_state {
1246         int lineno;
1247         bool errors;
1248 };
1250 static int
1251 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1253         struct config_state *config = data;
1254         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1256         config->lineno++;
1258         /* Check for comment markers, since read_properties() will
1259          * only ensure opt and value are split at first " \t". */
1260         optlen = strcspn(opt, "#");
1261         if (optlen == 0)
1262                 return OK;
1264         if (opt[optlen] == 0) {
1265                 /* Look for comment endings in the value. */
1266                 size_t len = strcspn(value, "#");
1268                 if (len < valuelen) {
1269                         valuelen = len;
1270                         value[valuelen] = 0;
1271                 }
1273                 status = set_option(opt, value);
1274         }
1276         if (status != OPT_OK) {
1277                 warn("Error on line %d, near '%.*s': %s",
1278                      config->lineno, (int) optlen, opt, option_errors[status]);
1279                 config->errors = TRUE;
1280         }
1282         /* Always keep going if errors are encountered. */
1283         return OK;
1286 static void
1287 load_option_file(const char *path)
1289         struct config_state config = { 0, FALSE };
1290         struct io io;
1292         /* It's OK that the file doesn't exist. */
1293         if (!io_open(&io, "%s", path))
1294                 return;
1296         if (io_load(&io, " \t", read_option, &config) == ERR ||
1297             config.errors == TRUE)
1298                 warn("Errors while loading %s.", path);
1301 static int
1302 load_options(void)
1304         const char *home = getenv("HOME");
1305         const char *tigrc_user = getenv("TIGRC_USER");
1306         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1307         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1308         char buf[SIZEOF_STR];
1310         if (!tigrc_system)
1311                 tigrc_system = SYSCONFDIR "/tigrc";
1312         load_option_file(tigrc_system);
1314         if (!tigrc_user) {
1315                 if (!home || !string_format(buf, "%s/.tigrc", home))
1316                         return ERR;
1317                 tigrc_user = buf;
1318         }
1319         load_option_file(tigrc_user);
1321         /* Add _after_ loading config files to avoid adding run requests
1322          * that conflict with keybindings. */
1323         add_builtin_run_requests();
1325         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1326                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1327                 int argc = 0;
1329                 if (!string_format(buf, "%s", tig_diff_opts) ||
1330                     !argv_from_string(diff_opts, &argc, buf))
1331                         die("TIG_DIFF_OPTS contains too many arguments");
1332                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1333                         die("Failed to format TIG_DIFF_OPTS arguments");
1334         }
1336         return OK;
1340 /*
1341  * The viewer
1342  */
1344 struct view;
1345 struct view_ops;
1347 /* The display array of active views and the index of the current view. */
1348 static struct view *display[2];
1349 static WINDOW *display_win[2];
1350 static WINDOW *display_title[2];
1351 static unsigned int current_view;
1353 #define foreach_displayed_view(view, i) \
1354         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1356 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1358 /* Current head and commit ID */
1359 static char ref_blob[SIZEOF_REF]        = "";
1360 static char ref_commit[SIZEOF_REF]      = "HEAD";
1361 static char ref_head[SIZEOF_REF]        = "HEAD";
1362 static char ref_branch[SIZEOF_REF]      = "";
1364 enum view_type {
1365         VIEW_MAIN,
1366         VIEW_DIFF,
1367         VIEW_LOG,
1368         VIEW_TREE,
1369         VIEW_BLOB,
1370         VIEW_BLAME,
1371         VIEW_BRANCH,
1372         VIEW_HELP,
1373         VIEW_PAGER,
1374         VIEW_STATUS,
1375         VIEW_STAGE,
1376 };
1378 struct view {
1379         enum view_type type;    /* View type */
1380         const char *name;       /* View name */
1381         const char *id;         /* Points to either of ref_{head,commit,blob} */
1383         struct view_ops *ops;   /* View operations */
1385         enum keymap keymap;     /* What keymap does this view have */
1386         bool git_dir;           /* Whether the view requires a git directory. */
1388         char ref[SIZEOF_REF];   /* Hovered commit reference */
1389         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1391         int height, width;      /* The width and height of the main window */
1392         WINDOW *win;            /* The main window */
1394         /* Navigation */
1395         unsigned long offset;   /* Offset of the window top */
1396         unsigned long yoffset;  /* Offset from the window side. */
1397         unsigned long lineno;   /* Current line number */
1398         unsigned long p_offset; /* Previous offset of the window top */
1399         unsigned long p_yoffset;/* Previous offset from the window side */
1400         unsigned long p_lineno; /* Previous current line number */
1401         bool p_restore;         /* Should the previous position be restored. */
1403         /* Searching */
1404         char grep[SIZEOF_STR];  /* Search string */
1405         regex_t *regex;         /* Pre-compiled regexp */
1407         /* If non-NULL, points to the view that opened this view. If this view
1408          * is closed tig will switch back to the parent view. */
1409         struct view *parent;
1410         struct view *prev;
1412         /* Buffering */
1413         size_t lines;           /* Total number of lines */
1414         struct line *line;      /* Line index */
1415         unsigned int digits;    /* Number of digits in the lines member. */
1417         /* Drawing */
1418         struct line *curline;   /* Line currently being drawn. */
1419         enum line_type curtype; /* Attribute currently used for drawing. */
1420         unsigned long col;      /* Column when drawing. */
1421         bool has_scrolled;      /* View was scrolled. */
1423         /* Loading */
1424         const char **argv;      /* Shell command arguments. */
1425         const char *dir;        /* Directory from which to execute. */
1426         struct io io;
1427         struct io *pipe;
1428         time_t start_time;
1429         time_t update_secs;
1430 };
1432 enum open_flags {
1433         OPEN_DEFAULT = 0,       /* Use default view switching. */
1434         OPEN_SPLIT = 1,         /* Split current view. */
1435         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1436         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
1437         OPEN_PREPARED = 32,     /* Open already prepared command. */
1438 };
1440 struct view_ops {
1441         /* What type of content being displayed. Used in the title bar. */
1442         const char *type;
1443         /* Open and reads in all view content. */
1444         bool (*open)(struct view *view, enum open_flags flags);
1445         /* Read one line; updates view->line. */
1446         bool (*read)(struct view *view, char *data);
1447         /* Draw one line; @lineno must be < view->height. */
1448         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1449         /* Depending on view handle a special requests. */
1450         enum request (*request)(struct view *view, enum request request, struct line *line);
1451         /* Search for regexp in a line. */
1452         bool (*grep)(struct view *view, struct line *line);
1453         /* Select line */
1454         void (*select)(struct view *view, struct line *line);
1455 };
1457 static struct view_ops blame_ops;
1458 static struct view_ops blob_ops;
1459 static struct view_ops diff_ops;
1460 static struct view_ops help_ops;
1461 static struct view_ops log_ops;
1462 static struct view_ops main_ops;
1463 static struct view_ops pager_ops;
1464 static struct view_ops stage_ops;
1465 static struct view_ops status_ops;
1466 static struct view_ops tree_ops;
1467 static struct view_ops branch_ops;
1469 #define VIEW_STR(type, name, ref, ops, map, git) \
1470         { type, name, ref, ops, map, git }
1472 #define VIEW_(id, name, ops, git, ref) \
1473         VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1475 static struct view views[] = {
1476         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1477         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1478         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1479         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1480         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1481         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1482         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1483         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1484         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1485         VIEW_(STATUS, "status", &status_ops, TRUE,  ""),
1486         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1487 };
1489 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1491 #define foreach_view(view, i) \
1492         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1494 #define view_is_displayed(view) \
1495         (view == display[0] || view == display[1])
1497 static enum request
1498 view_request(struct view *view, enum request request)
1500         if (!view || !view->lines)
1501                 return request;
1502         return view->ops->request(view, request, &view->line[view->lineno]);
1506 /*
1507  * View drawing.
1508  */
1510 static inline void
1511 set_view_attr(struct view *view, enum line_type type)
1513         if (!view->curline->selected && view->curtype != type) {
1514                 (void) wattrset(view->win, get_line_attr(type));
1515                 wchgat(view->win, -1, 0, type, NULL);
1516                 view->curtype = type;
1517         }
1520 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1522 static bool
1523 draw_chars(struct view *view, enum line_type type, const char *string,
1524            int max_len, bool use_tilde)
1526         static char out_buffer[BUFSIZ * 2];
1527         int len = 0;
1528         int col = 0;
1529         int trimmed = FALSE;
1530         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1532         if (max_len <= 0)
1533                 return VIEW_MAX_LEN(view) <= 0;
1535         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1537         set_view_attr(view, type);
1538         if (len > 0) {
1539                 if (opt_iconv_out != ICONV_NONE) {
1540                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1541                         size_t inlen = len + 1;
1543                         char *outbuf = out_buffer;
1544                         size_t outlen = sizeof(out_buffer);
1546                         size_t ret;
1548                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1549                         if (ret != (size_t) -1) {
1550                                 string = out_buffer;
1551                                 len = sizeof(out_buffer) - outlen;
1552                         }
1553                 }
1555                 waddnstr(view->win, string, len);
1557                 if (trimmed && use_tilde) {
1558                         set_view_attr(view, LINE_DELIMITER);
1559                         waddch(view->win, '~');
1560                         col++;
1561                 }
1562         }
1564         view->col += col;
1565         return VIEW_MAX_LEN(view) <= 0;
1568 static bool
1569 draw_space(struct view *view, enum line_type type, int max, int spaces)
1571         static char space[] = "                    ";
1573         spaces = MIN(max, spaces);
1575         while (spaces > 0) {
1576                 int len = MIN(spaces, sizeof(space) - 1);
1578                 if (draw_chars(view, type, space, len, FALSE))
1579                         return TRUE;
1580                 spaces -= len;
1581         }
1583         return VIEW_MAX_LEN(view) <= 0;
1586 static bool
1587 draw_text(struct view *view, enum line_type type, const char *string)
1589         char text[SIZEOF_STR];
1591         do {
1592                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1594                 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1595                         return TRUE;
1596                 string += pos;
1597         } while (*string);
1599         return VIEW_MAX_LEN(view) <= 0;
1602 static bool
1603 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1605         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1606         int max = VIEW_MAX_LEN(view);
1607         int i;
1609         if (max < size)
1610                 size = max;
1612         set_view_attr(view, type);
1613         /* Using waddch() instead of waddnstr() ensures that
1614          * they'll be rendered correctly for the cursor line. */
1615         for (i = skip; i < size; i++)
1616                 waddch(view->win, graphic[i]);
1618         view->col += size;
1619         if (separator) {
1620                 if (size < max && skip <= size)
1621                         waddch(view->win, ' ');
1622                 view->col++;
1623         }
1625         return VIEW_MAX_LEN(view) <= 0;
1628 static bool
1629 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1631         int max = MIN(VIEW_MAX_LEN(view), len);
1632         int col = view->col;
1634         if (!text) 
1635                 return draw_space(view, type, max, max);
1637         return draw_chars(view, type, text, max - 1, trim)
1638             || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1641 static bool
1642 draw_date(struct view *view, struct time *time)
1644         const char *date = mkdate(time, opt_date);
1645         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1647         if (opt_date == DATE_NO)
1648                 return FALSE;
1650         return draw_field(view, LINE_DATE, date, cols, FALSE);
1653 static bool
1654 draw_author(struct view *view, const char *author)
1656         bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1657         bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1659         if (opt_author == AUTHOR_NO)
1660                 return FALSE;
1662         if (abbreviate && author)
1663                 author = get_author_initials(author);
1665         return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1668 static bool
1669 draw_mode(struct view *view, mode_t mode)
1671         const char *str;
1673         if (S_ISDIR(mode))
1674                 str = "drwxr-xr-x";
1675         else if (S_ISLNK(mode))
1676                 str = "lrwxrwxrwx";
1677         else if (S_ISGITLINK(mode))
1678                 str = "m---------";
1679         else if (S_ISREG(mode) && mode & S_IXUSR)
1680                 str = "-rwxr-xr-x";
1681         else if (S_ISREG(mode))
1682                 str = "-rw-r--r--";
1683         else
1684                 str = "----------";
1686         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1689 static bool
1690 draw_lineno(struct view *view, unsigned int lineno)
1692         char number[10];
1693         int digits3 = view->digits < 3 ? 3 : view->digits;
1694         int max = MIN(VIEW_MAX_LEN(view), digits3);
1695         char *text = NULL;
1696         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1698         lineno += view->offset + 1;
1699         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1700                 static char fmt[] = "%1ld";
1702                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1703                 if (string_format(number, fmt, lineno))
1704                         text = number;
1705         }
1706         if (text)
1707                 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1708         else
1709                 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1710         return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1713 static bool
1714 draw_view_line(struct view *view, unsigned int lineno)
1716         struct line *line;
1717         bool selected = (view->offset + lineno == view->lineno);
1719         assert(view_is_displayed(view));
1721         if (view->offset + lineno >= view->lines)
1722                 return FALSE;
1724         line = &view->line[view->offset + lineno];
1726         wmove(view->win, lineno, 0);
1727         if (line->cleareol)
1728                 wclrtoeol(view->win);
1729         view->col = 0;
1730         view->curline = line;
1731         view->curtype = LINE_NONE;
1732         line->selected = FALSE;
1733         line->dirty = line->cleareol = 0;
1735         if (selected) {
1736                 set_view_attr(view, LINE_CURSOR);
1737                 line->selected = TRUE;
1738                 view->ops->select(view, line);
1739         }
1741         return view->ops->draw(view, line, lineno);
1744 static void
1745 redraw_view_dirty(struct view *view)
1747         bool dirty = FALSE;
1748         int lineno;
1750         for (lineno = 0; lineno < view->height; lineno++) {
1751                 if (view->offset + lineno >= view->lines)
1752                         break;
1753                 if (!view->line[view->offset + lineno].dirty)
1754                         continue;
1755                 dirty = TRUE;
1756                 if (!draw_view_line(view, lineno))
1757                         break;
1758         }
1760         if (!dirty)
1761                 return;
1762         wnoutrefresh(view->win);
1765 static void
1766 redraw_view_from(struct view *view, int lineno)
1768         assert(0 <= lineno && lineno < view->height);
1770         for (; lineno < view->height; lineno++) {
1771                 if (!draw_view_line(view, lineno))
1772                         break;
1773         }
1775         wnoutrefresh(view->win);
1778 static void
1779 redraw_view(struct view *view)
1781         werase(view->win);
1782         redraw_view_from(view, 0);
1786 static void
1787 update_view_title(struct view *view)
1789         char buf[SIZEOF_STR];
1790         char state[SIZEOF_STR];
1791         size_t bufpos = 0, statelen = 0;
1792         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1794         assert(view_is_displayed(view));
1796         if (view->type != VIEW_STATUS && view->lines) {
1797                 unsigned int view_lines = view->offset + view->height;
1798                 unsigned int lines = view->lines
1799                                    ? MIN(view_lines, view->lines) * 100 / view->lines
1800                                    : 0;
1802                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1803                                    view->ops->type,
1804                                    view->lineno + 1,
1805                                    view->lines,
1806                                    lines);
1808         }
1810         if (view->pipe) {
1811                 time_t secs = time(NULL) - view->start_time;
1813                 /* Three git seconds are a long time ... */
1814                 if (secs > 2)
1815                         string_format_from(state, &statelen, " loading %lds", secs);
1816         }
1818         string_format_from(buf, &bufpos, "[%s]", view->name);
1819         if (*view->ref && bufpos < view->width) {
1820                 size_t refsize = strlen(view->ref);
1821                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1823                 if (minsize < view->width)
1824                         refsize = view->width - minsize + 7;
1825                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1826         }
1828         if (statelen && bufpos < view->width) {
1829                 string_format_from(buf, &bufpos, "%s", state);
1830         }
1832         if (view == display[current_view])
1833                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1834         else
1835                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1837         mvwaddnstr(window, 0, 0, buf, bufpos);
1838         wclrtoeol(window);
1839         wnoutrefresh(window);
1842 static int
1843 apply_step(double step, int value)
1845         if (step >= 1)
1846                 return (int) step;
1847         value *= step + 0.01;
1848         return value ? value : 1;
1851 static void
1852 resize_display(void)
1854         int offset, i;
1855         struct view *base = display[0];
1856         struct view *view = display[1] ? display[1] : display[0];
1858         /* Setup window dimensions */
1860         getmaxyx(stdscr, base->height, base->width);
1862         /* Make room for the status window. */
1863         base->height -= 1;
1865         if (view != base) {
1866                 /* Horizontal split. */
1867                 view->width   = base->width;
1868                 view->height  = apply_step(opt_scale_split_view, base->height);
1869                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
1870                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1871                 base->height -= view->height;
1873                 /* Make room for the title bar. */
1874                 view->height -= 1;
1875         }
1877         /* Make room for the title bar. */
1878         base->height -= 1;
1880         offset = 0;
1882         foreach_displayed_view (view, i) {
1883                 if (!display_win[i]) {
1884                         display_win[i] = newwin(view->height, view->width, offset, 0);
1885                         if (!display_win[i])
1886                                 die("Failed to create %s view", view->name);
1888                         scrollok(display_win[i], FALSE);
1890                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
1891                         if (!display_title[i])
1892                                 die("Failed to create title window");
1894                 } else {
1895                         wresize(display_win[i], view->height, view->width);
1896                         mvwin(display_win[i],   offset, 0);
1897                         mvwin(display_title[i], offset + view->height, 0);
1898                 }
1900                 view->win = display_win[i];
1902                 offset += view->height + 1;
1903         }
1906 static void
1907 redraw_display(bool clear)
1909         struct view *view;
1910         int i;
1912         foreach_displayed_view (view, i) {
1913                 if (clear)
1914                         wclear(view->win);
1915                 redraw_view(view);
1916                 update_view_title(view);
1917         }
1921 /*
1922  * Option management
1923  */
1925 #define TOGGLE_MENU \
1926         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
1927         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
1928         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
1929         TOGGLE_(GRAPHIC,   '~', "graphics",          &opt_line_graphics, graphic_map) \
1930         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
1931         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
1933 static void
1934 toggle_option(enum request request)
1936         const struct {
1937                 enum request request;
1938                 const struct enum_map *map;
1939                 size_t map_size;
1940         } data[] = {            
1941 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1942                 TOGGLE_MENU
1943 #undef  TOGGLE_
1944         };
1945         const struct menu_item menu[] = {
1946 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1947                 TOGGLE_MENU
1948 #undef  TOGGLE_
1949                 { 0 }
1950         };
1951         int i = 0;
1953         if (request == REQ_OPTIONS) {
1954                 if (!prompt_menu("Toggle option", menu, &i))
1955                         return;
1956         } else {
1957                 while (i < ARRAY_SIZE(data) && data[i].request != request)
1958                         i++;
1959                 if (i >= ARRAY_SIZE(data))
1960                         die("Invalid request (%d)", request);
1961         }
1963         if (data[i].map != NULL) {
1964                 unsigned int *opt = menu[i].data;
1966                 *opt = (*opt + 1) % data[i].map_size;
1967                 redraw_display(FALSE);
1968                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1970         } else {
1971                 bool *option = menu[i].data;
1973                 *option = !*option;
1974                 redraw_display(FALSE);
1975                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1976         }
1979 static void
1980 maximize_view(struct view *view)
1982         memset(display, 0, sizeof(display));
1983         current_view = 0;
1984         display[current_view] = view;
1985         resize_display();
1986         redraw_display(FALSE);
1987         report("");
1991 /*
1992  * Navigation
1993  */
1995 static bool
1996 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1998         if (lineno >= view->lines)
1999                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2001         if (offset > lineno || offset + view->height <= lineno) {
2002                 unsigned long half = view->height / 2;
2004                 if (lineno > half)
2005                         offset = lineno - half;
2006                 else
2007                         offset = 0;
2008         }
2010         if (offset != view->offset || lineno != view->lineno) {
2011                 view->offset = offset;
2012                 view->lineno = lineno;
2013                 return TRUE;
2014         }
2016         return FALSE;
2019 /* Scrolling backend */
2020 static void
2021 do_scroll_view(struct view *view, int lines)
2023         bool redraw_current_line = FALSE;
2025         /* The rendering expects the new offset. */
2026         view->offset += lines;
2028         assert(0 <= view->offset && view->offset < view->lines);
2029         assert(lines);
2031         /* Move current line into the view. */
2032         if (view->lineno < view->offset) {
2033                 view->lineno = view->offset;
2034                 redraw_current_line = TRUE;
2035         } else if (view->lineno >= view->offset + view->height) {
2036                 view->lineno = view->offset + view->height - 1;
2037                 redraw_current_line = TRUE;
2038         }
2040         assert(view->offset <= view->lineno && view->lineno < view->lines);
2042         /* Redraw the whole screen if scrolling is pointless. */
2043         if (view->height < ABS(lines)) {
2044                 redraw_view(view);
2046         } else {
2047                 int line = lines > 0 ? view->height - lines : 0;
2048                 int end = line + ABS(lines);
2050                 scrollok(view->win, TRUE);
2051                 wscrl(view->win, lines);
2052                 scrollok(view->win, FALSE);
2054                 while (line < end && draw_view_line(view, line))
2055                         line++;
2057                 if (redraw_current_line)
2058                         draw_view_line(view, view->lineno - view->offset);
2059                 wnoutrefresh(view->win);
2060         }
2062         view->has_scrolled = TRUE;
2063         report("");
2066 /* Scroll frontend */
2067 static void
2068 scroll_view(struct view *view, enum request request)
2070         int lines = 1;
2072         assert(view_is_displayed(view));
2074         switch (request) {
2075         case REQ_SCROLL_FIRST_COL:
2076                 view->yoffset = 0;
2077                 redraw_view_from(view, 0);
2078                 report("");
2079                 return;
2080         case REQ_SCROLL_LEFT:
2081                 if (view->yoffset == 0) {
2082                         report("Cannot scroll beyond the first column");
2083                         return;
2084                 }
2085                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2086                         view->yoffset = 0;
2087                 else
2088                         view->yoffset -= apply_step(opt_hscroll, view->width);
2089                 redraw_view_from(view, 0);
2090                 report("");
2091                 return;
2092         case REQ_SCROLL_RIGHT:
2093                 view->yoffset += apply_step(opt_hscroll, view->width);
2094                 redraw_view(view);
2095                 report("");
2096                 return;
2097         case REQ_SCROLL_PAGE_DOWN:
2098                 lines = view->height;
2099         case REQ_SCROLL_LINE_DOWN:
2100                 if (view->offset + lines > view->lines)
2101                         lines = view->lines - view->offset;
2103                 if (lines == 0 || view->offset + view->height >= view->lines) {
2104                         report("Cannot scroll beyond the last line");
2105                         return;
2106                 }
2107                 break;
2109         case REQ_SCROLL_PAGE_UP:
2110                 lines = view->height;
2111         case REQ_SCROLL_LINE_UP:
2112                 if (lines > view->offset)
2113                         lines = view->offset;
2115                 if (lines == 0) {
2116                         report("Cannot scroll beyond the first line");
2117                         return;
2118                 }
2120                 lines = -lines;
2121                 break;
2123         default:
2124                 die("request %d not handled in switch", request);
2125         }
2127         do_scroll_view(view, lines);
2130 /* Cursor moving */
2131 static void
2132 move_view(struct view *view, enum request request)
2134         int scroll_steps = 0;
2135         int steps;
2137         switch (request) {
2138         case REQ_MOVE_FIRST_LINE:
2139                 steps = -view->lineno;
2140                 break;
2142         case REQ_MOVE_LAST_LINE:
2143                 steps = view->lines - view->lineno - 1;
2144                 break;
2146         case REQ_MOVE_PAGE_UP:
2147                 steps = view->height > view->lineno
2148                       ? -view->lineno : -view->height;
2149                 break;
2151         case REQ_MOVE_PAGE_DOWN:
2152                 steps = view->lineno + view->height >= view->lines
2153                       ? view->lines - view->lineno - 1 : view->height;
2154                 break;
2156         case REQ_MOVE_UP:
2157                 steps = -1;
2158                 break;
2160         case REQ_MOVE_DOWN:
2161                 steps = 1;
2162                 break;
2164         default:
2165                 die("request %d not handled in switch", request);
2166         }
2168         if (steps <= 0 && view->lineno == 0) {
2169                 report("Cannot move beyond the first line");
2170                 return;
2172         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2173                 report("Cannot move beyond the last line");
2174                 return;
2175         }
2177         /* Move the current line */
2178         view->lineno += steps;
2179         assert(0 <= view->lineno && view->lineno < view->lines);
2181         /* Check whether the view needs to be scrolled */
2182         if (view->lineno < view->offset ||
2183             view->lineno >= view->offset + view->height) {
2184                 scroll_steps = steps;
2185                 if (steps < 0 && -steps > view->offset) {
2186                         scroll_steps = -view->offset;
2188                 } else if (steps > 0) {
2189                         if (view->lineno == view->lines - 1 &&
2190                             view->lines > view->height) {
2191                                 scroll_steps = view->lines - view->offset - 1;
2192                                 if (scroll_steps >= view->height)
2193                                         scroll_steps -= view->height - 1;
2194                         }
2195                 }
2196         }
2198         if (!view_is_displayed(view)) {
2199                 view->offset += scroll_steps;
2200                 assert(0 <= view->offset && view->offset < view->lines);
2201                 view->ops->select(view, &view->line[view->lineno]);
2202                 return;
2203         }
2205         /* Repaint the old "current" line if we be scrolling */
2206         if (ABS(steps) < view->height)
2207                 draw_view_line(view, view->lineno - steps - view->offset);
2209         if (scroll_steps) {
2210                 do_scroll_view(view, scroll_steps);
2211                 return;
2212         }
2214         /* Draw the current line */
2215         draw_view_line(view, view->lineno - view->offset);
2217         wnoutrefresh(view->win);
2218         report("");
2222 /*
2223  * Searching
2224  */
2226 static void search_view(struct view *view, enum request request);
2228 static bool
2229 grep_text(struct view *view, const char *text[])
2231         regmatch_t pmatch;
2232         size_t i;
2234         for (i = 0; text[i]; i++)
2235                 if (*text[i] &&
2236                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2237                         return TRUE;
2238         return FALSE;
2241 static void
2242 select_view_line(struct view *view, unsigned long lineno)
2244         unsigned long old_lineno = view->lineno;
2245         unsigned long old_offset = view->offset;
2247         if (goto_view_line(view, view->offset, lineno)) {
2248                 if (view_is_displayed(view)) {
2249                         if (old_offset != view->offset) {
2250                                 redraw_view(view);
2251                         } else {
2252                                 draw_view_line(view, old_lineno - view->offset);
2253                                 draw_view_line(view, view->lineno - view->offset);
2254                                 wnoutrefresh(view->win);
2255                         }
2256                 } else {
2257                         view->ops->select(view, &view->line[view->lineno]);
2258                 }
2259         }
2262 static void
2263 find_next(struct view *view, enum request request)
2265         unsigned long lineno = view->lineno;
2266         int direction;
2268         if (!*view->grep) {
2269                 if (!*opt_search)
2270                         report("No previous search");
2271                 else
2272                         search_view(view, request);
2273                 return;
2274         }
2276         switch (request) {
2277         case REQ_SEARCH:
2278         case REQ_FIND_NEXT:
2279                 direction = 1;
2280                 break;
2282         case REQ_SEARCH_BACK:
2283         case REQ_FIND_PREV:
2284                 direction = -1;
2285                 break;
2287         default:
2288                 return;
2289         }
2291         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2292                 lineno += direction;
2294         /* Note, lineno is unsigned long so will wrap around in which case it
2295          * will become bigger than view->lines. */
2296         for (; lineno < view->lines; lineno += direction) {
2297                 if (view->ops->grep(view, &view->line[lineno])) {
2298                         select_view_line(view, lineno);
2299                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2300                         return;
2301                 }
2302         }
2304         report("No match found for '%s'", view->grep);
2307 static void
2308 search_view(struct view *view, enum request request)
2310         int regex_err;
2312         if (view->regex) {
2313                 regfree(view->regex);
2314                 *view->grep = 0;
2315         } else {
2316                 view->regex = calloc(1, sizeof(*view->regex));
2317                 if (!view->regex)
2318                         return;
2319         }
2321         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2322         if (regex_err != 0) {
2323                 char buf[SIZEOF_STR] = "unknown error";
2325                 regerror(regex_err, view->regex, buf, sizeof(buf));
2326                 report("Search failed: %s", buf);
2327                 return;
2328         }
2330         string_copy(view->grep, opt_search);
2332         find_next(view, request);
2335 /*
2336  * Incremental updating
2337  */
2339 static void
2340 reset_view(struct view *view)
2342         int i;
2344         for (i = 0; i < view->lines; i++)
2345                 free(view->line[i].data);
2346         free(view->line);
2348         view->p_offset = view->offset;
2349         view->p_yoffset = view->yoffset;
2350         view->p_lineno = view->lineno;
2352         view->line = NULL;
2353         view->offset = 0;
2354         view->yoffset = 0;
2355         view->lines  = 0;
2356         view->lineno = 0;
2357         view->vid[0] = 0;
2358         view->update_secs = 0;
2361 static const char *
2362 format_arg(const char *name)
2364         static struct {
2365                 const char *name;
2366                 size_t namelen;
2367                 const char *value;
2368                 const char *value_if_empty;
2369         } vars[] = {
2370 #define FORMAT_VAR(name, value, value_if_empty) \
2371         { name, STRING_SIZE(name), value, value_if_empty }
2372                 FORMAT_VAR("%(directory)",      opt_path,       "."),
2373                 FORMAT_VAR("%(file)",           opt_file,       ""),
2374                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2375                 FORMAT_VAR("%(head)",           ref_head,       ""),
2376                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2377                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2378                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2379         };
2380         int i;
2382         for (i = 0; i < ARRAY_SIZE(vars); i++)
2383                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2384                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2386         report("Unknown replacement: `%s`", name);
2387         return NULL;
2390 static bool
2391 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2393         char buf[SIZEOF_STR];
2394         int argc;
2396         argv_free(*dst_argv);
2398         for (argc = 0; src_argv[argc]; argc++) {
2399                 const char *arg = src_argv[argc];
2400                 size_t bufpos = 0;
2402                 if (!strcmp(arg, "%(fileargs)")) {
2403                         if (!argv_append_array(dst_argv, opt_file_argv))
2404                                 break;
2405                         continue;
2407                 } else if (!strcmp(arg, "%(diffargs)")) {
2408                         if (!argv_append_array(dst_argv, opt_diff_argv))
2409                                 break;
2410                         continue;
2412                 } else if (!strcmp(arg, "%(blameargs)")) {
2413                         if (!argv_append_array(dst_argv, opt_blame_argv))
2414                                 break;
2415                         continue;
2417                 } else if (!strcmp(arg, "%(revargs)") ||
2418                            (first && !strcmp(arg, "%(commit)"))) {
2419                         if (!argv_append_array(dst_argv, opt_rev_argv))
2420                                 break;
2421                         continue;
2422                 }
2424                 while (arg) {
2425                         char *next = strstr(arg, "%(");
2426                         int len = next - arg;
2427                         const char *value;
2429                         if (!next || !replace) {
2430                                 len = strlen(arg);
2431                                 value = "";
2433                         } else {
2434                                 value = format_arg(next);
2436                                 if (!value) {
2437                                         return FALSE;
2438                                 }
2439                         }
2441                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2442                                 return FALSE;
2444                         arg = next && replace ? strchr(next, ')') + 1 : NULL;
2445                 }
2447                 if (!argv_append(dst_argv, buf))
2448                         break;
2449         }
2451         return src_argv[argc] == NULL;
2454 static bool
2455 restore_view_position(struct view *view)
2457         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2458                 return FALSE;
2460         /* Changing the view position cancels the restoring. */
2461         /* FIXME: Changing back to the first line is not detected. */
2462         if (view->offset != 0 || view->lineno != 0) {
2463                 view->p_restore = FALSE;
2464                 return FALSE;
2465         }
2467         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2468             view_is_displayed(view))
2469                 werase(view->win);
2471         view->yoffset = view->p_yoffset;
2472         view->p_restore = FALSE;
2474         return TRUE;
2477 static void
2478 end_update(struct view *view, bool force)
2480         if (!view->pipe)
2481                 return;
2482         while (!view->ops->read(view, NULL))
2483                 if (!force)
2484                         return;
2485         if (force)
2486                 io_kill(view->pipe);
2487         io_done(view->pipe);
2488         view->pipe = NULL;
2491 static void
2492 setup_update(struct view *view, const char *vid)
2494         reset_view(view);
2495         string_copy_rev(view->vid, vid);
2496         view->pipe = &view->io;
2497         view->start_time = time(NULL);
2500 static bool
2501 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2503         view->dir = dir;
2504         return format_argv(&view->argv, argv, replace, !view->prev);
2507 static bool
2508 prepare_update(struct view *view, const char *argv[], const char *dir)
2510         if (view->pipe)
2511                 end_update(view, TRUE);
2512         return prepare_io(view, dir, argv, FALSE);
2515 static bool
2516 start_update(struct view *view, const char **argv, const char *dir)
2518         if (view->pipe)
2519                 io_done(view->pipe);
2520         return prepare_io(view, dir, argv, FALSE) &&
2521                io_run(&view->io, IO_RD, dir, view->argv);
2524 static bool
2525 prepare_update_file(struct view *view, const char *name)
2527         const char *file_argv[] = { opt_cdup, name , NULL };
2529         if (view->pipe)
2530                 end_update(view, TRUE);
2531         return argv_copy(&view->argv, file_argv);
2534 static bool
2535 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2537         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2538         bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2540         if (!reload && !strcmp(view->vid, view->id))
2541                 return TRUE;
2543         if (view->pipe)
2544                 end_update(view, TRUE);
2546         if (!refresh) {
2547                 if (!prepare_io(view, dir, argv, TRUE))
2548                         return FALSE;
2550                 /* Put the current ref_* value to the view title ref
2551                  * member. This is needed by the blob view. Most other
2552                  * views sets it automatically after loading because the
2553                  * first line is a commit line. */
2554                 string_copy_rev(view->ref, view->id);
2555         }
2557         if (view->argv && view->argv[0] &&
2558             !io_run(&view->io, IO_RD, view->dir, view->argv))
2559                 return FALSE;
2560         else if (view->argv && !strcmp(view->argv[0], opt_cdup) &&
2561                  !io_open(&view->io, "%s%s", opt_cdup, view->argv[1]))
2562                 return FALSE;
2564         setup_update(view, view->id);
2566         return TRUE;
2569 static bool
2570 view_open(struct view *view, enum open_flags flags)
2572         return begin_update(view, NULL, NULL, flags);
2575 static bool
2576 update_view(struct view *view)
2578         char out_buffer[BUFSIZ * 2];
2579         char *line;
2580         /* Clear the view and redraw everything since the tree sorting
2581          * might have rearranged things. */
2582         bool redraw = view->lines == 0;
2583         bool can_read = TRUE;
2585         if (!view->pipe)
2586                 return TRUE;
2588         if (!io_can_read(view->pipe, FALSE)) {
2589                 if (view->lines == 0 && view_is_displayed(view)) {
2590                         time_t secs = time(NULL) - view->start_time;
2592                         if (secs > 1 && secs > view->update_secs) {
2593                                 if (view->update_secs == 0)
2594                                         redraw_view(view);
2595                                 update_view_title(view);
2596                                 view->update_secs = secs;
2597                         }
2598                 }
2599                 return TRUE;
2600         }
2602         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2603                 if (opt_iconv_in != ICONV_NONE) {
2604                         ICONV_CONST char *inbuf = line;
2605                         size_t inlen = strlen(line) + 1;
2607                         char *outbuf = out_buffer;
2608                         size_t outlen = sizeof(out_buffer);
2610                         size_t ret;
2612                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2613                         if (ret != (size_t) -1)
2614                                 line = out_buffer;
2615                 }
2617                 if (!view->ops->read(view, line)) {
2618                         report("Allocation failure");
2619                         end_update(view, TRUE);
2620                         return FALSE;
2621                 }
2622         }
2624         {
2625                 unsigned long lines = view->lines;
2626                 int digits;
2628                 for (digits = 0; lines; digits++)
2629                         lines /= 10;
2631                 /* Keep the displayed view in sync with line number scaling. */
2632                 if (digits != view->digits) {
2633                         view->digits = digits;
2634                         if (opt_line_number || view->type == VIEW_BLAME)
2635                                 redraw = TRUE;
2636                 }
2637         }
2639         if (io_error(view->pipe)) {
2640                 report("Failed to read: %s", io_strerror(view->pipe));
2641                 end_update(view, TRUE);
2643         } else if (io_eof(view->pipe)) {
2644                 if (view_is_displayed(view))
2645                         report("");
2646                 end_update(view, FALSE);
2647         }
2649         if (restore_view_position(view))
2650                 redraw = TRUE;
2652         if (!view_is_displayed(view))
2653                 return TRUE;
2655         if (redraw)
2656                 redraw_view_from(view, 0);
2657         else
2658                 redraw_view_dirty(view);
2660         /* Update the title _after_ the redraw so that if the redraw picks up a
2661          * commit reference in view->ref it'll be available here. */
2662         update_view_title(view);
2663         return TRUE;
2666 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2668 static struct line *
2669 add_line_data(struct view *view, void *data, enum line_type type)
2671         struct line *line;
2673         if (!realloc_lines(&view->line, view->lines, 1))
2674                 return NULL;
2676         line = &view->line[view->lines++];
2677         memset(line, 0, sizeof(*line));
2678         line->type = type;
2679         line->data = data;
2680         line->dirty = 1;
2682         return line;
2685 static struct line *
2686 add_line_text(struct view *view, const char *text, enum line_type type)
2688         char *data = text ? strdup(text) : NULL;
2690         return data ? add_line_data(view, data, type) : NULL;
2693 static struct line *
2694 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2696         char buf[SIZEOF_STR];
2697         va_list args;
2699         va_start(args, fmt);
2700         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2701                 buf[0] = 0;
2702         va_end(args);
2704         return buf[0] ? add_line_text(view, buf, type) : NULL;
2707 /*
2708  * View opening
2709  */
2711 static void
2712 open_view(struct view *prev, enum request request, enum open_flags flags)
2714         bool split = !!(flags & OPEN_SPLIT);
2715         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2716         bool nomaximize = !!(flags & OPEN_REFRESH);
2717         struct view *view = VIEW(request);
2718         int nviews = displayed_views();
2719         struct view *base_view = display[0];
2721         if (view == prev && nviews == 1 && !reload) {
2722                 report("Already in %s view", view->name);
2723                 return;
2724         }
2726         if (view->git_dir && !opt_git_dir[0]) {
2727                 report("The %s view is disabled in pager view", view->name);
2728                 return;
2729         }
2731         if (split) {
2732                 display[1] = view;
2733                 current_view = 1;
2734                 view->parent = prev;
2735         } else if (!nomaximize) {
2736                 /* Maximize the current view. */
2737                 memset(display, 0, sizeof(display));
2738                 current_view = 0;
2739                 display[current_view] = view;
2740         }
2742         /* No prev signals that this is the first loaded view. */
2743         if (prev && view != prev) {
2744                 view->prev = prev;
2745         }
2747         /* Resize the view when switching between split- and full-screen,
2748          * or when switching between two different full-screen views. */
2749         if (nviews != displayed_views() ||
2750             (nviews == 1 && base_view != display[0]))
2751                 resize_display();
2753         if (view->ops->open) {
2754                 if (view->pipe)
2755                         end_update(view, TRUE);
2756                 if (!view->ops->open(view, flags)) {
2757                         report("Failed to load %s view", view->name);
2758                         return;
2759                 }
2760                 restore_view_position(view);
2761         }
2763         if (split && prev->lineno - prev->offset >= prev->height) {
2764                 /* Take the title line into account. */
2765                 int lines = prev->lineno - prev->offset - prev->height + 1;
2767                 /* Scroll the view that was split if the current line is
2768                  * outside the new limited view. */
2769                 do_scroll_view(prev, lines);
2770         }
2772         if (prev && view != prev && split && view_is_displayed(prev)) {
2773                 /* "Blur" the previous view. */
2774                 update_view_title(prev);
2775         }
2777         if (view->pipe && view->lines == 0) {
2778                 /* Clear the old view and let the incremental updating refill
2779                  * the screen. */
2780                 werase(view->win);
2781                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2782                 report("");
2783         } else if (view_is_displayed(view)) {
2784                 redraw_view(view);
2785                 report("");
2786         }
2789 static void
2790 open_external_viewer(const char *argv[], const char *dir)
2792         def_prog_mode();           /* save current tty modes */
2793         endwin();                  /* restore original tty modes */
2794         io_run_fg(argv, dir);
2795         fprintf(stderr, "Press Enter to continue");
2796         getc(opt_tty);
2797         reset_prog_mode();
2798         redraw_display(TRUE);
2801 static void
2802 open_mergetool(const char *file)
2804         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2806         open_external_viewer(mergetool_argv, opt_cdup);
2809 static void
2810 open_editor(const char *file)
2812         const char *editor_argv[] = { "vi", file, NULL };
2813         const char *editor;
2815         editor = getenv("GIT_EDITOR");
2816         if (!editor && *opt_editor)
2817                 editor = opt_editor;
2818         if (!editor)
2819                 editor = getenv("VISUAL");
2820         if (!editor)
2821                 editor = getenv("EDITOR");
2822         if (!editor)
2823                 editor = "vi";
2825         editor_argv[0] = editor;
2826         open_external_viewer(editor_argv, opt_cdup);
2829 static void
2830 open_run_request(enum request request)
2832         struct run_request *req = get_run_request(request);
2833         const char **argv = NULL;
2835         if (!req) {
2836                 report("Unknown run request");
2837                 return;
2838         }
2840         if (format_argv(&argv, req->argv, TRUE, FALSE))
2841                 open_external_viewer(argv, NULL);
2842         if (argv)
2843                 argv_free(argv);
2844         free(argv);
2847 /*
2848  * User request switch noodle
2849  */
2851 static int
2852 view_driver(struct view *view, enum request request)
2854         int i;
2856         if (request == REQ_NONE)
2857                 return TRUE;
2859         if (request > REQ_NONE) {
2860                 open_run_request(request);
2861                 view_request(view, REQ_REFRESH);
2862                 return TRUE;
2863         }
2865         request = view_request(view, request);
2866         if (request == REQ_NONE)
2867                 return TRUE;
2869         switch (request) {
2870         case REQ_MOVE_UP:
2871         case REQ_MOVE_DOWN:
2872         case REQ_MOVE_PAGE_UP:
2873         case REQ_MOVE_PAGE_DOWN:
2874         case REQ_MOVE_FIRST_LINE:
2875         case REQ_MOVE_LAST_LINE:
2876                 move_view(view, request);
2877                 break;
2879         case REQ_SCROLL_FIRST_COL:
2880         case REQ_SCROLL_LEFT:
2881         case REQ_SCROLL_RIGHT:
2882         case REQ_SCROLL_LINE_DOWN:
2883         case REQ_SCROLL_LINE_UP:
2884         case REQ_SCROLL_PAGE_DOWN:
2885         case REQ_SCROLL_PAGE_UP:
2886                 scroll_view(view, request);
2887                 break;
2889         case REQ_VIEW_BLAME:
2890                 if (!opt_file[0]) {
2891                         report("No file chosen, press %s to open tree view",
2892                                get_key(view->keymap, REQ_VIEW_TREE));
2893                         break;
2894                 }
2895                 open_view(view, request, OPEN_DEFAULT);
2896                 break;
2898         case REQ_VIEW_BLOB:
2899                 if (!ref_blob[0]) {
2900                         report("No file chosen, press %s to open tree view",
2901                                get_key(view->keymap, REQ_VIEW_TREE));
2902                         break;
2903                 }
2904                 open_view(view, request, OPEN_DEFAULT);
2905                 break;
2907         case REQ_VIEW_PAGER:
2908                 if (view == NULL) {
2909                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2910                                 die("Failed to open stdin");
2911                         open_view(view, request, OPEN_PREPARED);
2912                         break;
2913                 }
2915                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2916                         report("No pager content, press %s to run command from prompt",
2917                                get_key(view->keymap, REQ_PROMPT));
2918                         break;
2919                 }
2920                 open_view(view, request, OPEN_DEFAULT);
2921                 break;
2923         case REQ_VIEW_STAGE:
2924                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2925                         report("No stage content, press %s to open the status view and choose file",
2926                                get_key(view->keymap, REQ_VIEW_STATUS));
2927                         break;
2928                 }
2929                 open_view(view, request, OPEN_DEFAULT);
2930                 break;
2932         case REQ_VIEW_STATUS:
2933                 if (opt_is_inside_work_tree == FALSE) {
2934                         report("The status view requires a working tree");
2935                         break;
2936                 }
2937                 open_view(view, request, OPEN_DEFAULT);
2938                 break;
2940         case REQ_VIEW_MAIN:
2941         case REQ_VIEW_DIFF:
2942         case REQ_VIEW_LOG:
2943         case REQ_VIEW_TREE:
2944         case REQ_VIEW_HELP:
2945         case REQ_VIEW_BRANCH:
2946                 open_view(view, request, OPEN_DEFAULT);
2947                 break;
2949         case REQ_NEXT:
2950         case REQ_PREVIOUS:
2951                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2953                 if (view->parent) {
2954                         int line;
2956                         view = view->parent;
2957                         line = view->lineno;
2958                         move_view(view, request);
2959                         if (view_is_displayed(view))
2960                                 update_view_title(view);
2961                         if (line != view->lineno)
2962                                 view_request(view, REQ_ENTER);
2963                 } else {
2964                         move_view(view, request);
2965                 }
2966                 break;
2968         case REQ_VIEW_NEXT:
2969         {
2970                 int nviews = displayed_views();
2971                 int next_view = (current_view + 1) % nviews;
2973                 if (next_view == current_view) {
2974                         report("Only one view is displayed");
2975                         break;
2976                 }
2978                 current_view = next_view;
2979                 /* Blur out the title of the previous view. */
2980                 update_view_title(view);
2981                 report("");
2982                 break;
2983         }
2984         case REQ_REFRESH:
2985                 report("Refreshing is not yet supported for the %s view", view->name);
2986                 break;
2988         case REQ_MAXIMIZE:
2989                 if (displayed_views() == 2)
2990                         maximize_view(view);
2991                 break;
2993         case REQ_OPTIONS:
2994         case REQ_TOGGLE_LINENO:
2995         case REQ_TOGGLE_DATE:
2996         case REQ_TOGGLE_AUTHOR:
2997         case REQ_TOGGLE_GRAPHIC:
2998         case REQ_TOGGLE_REV_GRAPH:
2999         case REQ_TOGGLE_REFS:
3000                 toggle_option(request);
3001                 break;
3003         case REQ_TOGGLE_SORT_FIELD:
3004         case REQ_TOGGLE_SORT_ORDER:
3005                 report("Sorting is not yet supported for the %s view", view->name);
3006                 break;
3008         case REQ_SEARCH:
3009         case REQ_SEARCH_BACK:
3010                 search_view(view, request);
3011                 break;
3013         case REQ_FIND_NEXT:
3014         case REQ_FIND_PREV:
3015                 find_next(view, request);
3016                 break;
3018         case REQ_STOP_LOADING:
3019                 foreach_view(view, i) {
3020                         if (view->pipe)
3021                                 report("Stopped loading the %s view", view->name),
3022                         end_update(view, TRUE);
3023                 }
3024                 break;
3026         case REQ_SHOW_VERSION:
3027                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3028                 return TRUE;
3030         case REQ_SCREEN_REDRAW:
3031                 redraw_display(TRUE);
3032                 break;
3034         case REQ_EDIT:
3035                 report("Nothing to edit");
3036                 break;
3038         case REQ_ENTER:
3039                 report("Nothing to enter");
3040                 break;
3042         case REQ_VIEW_CLOSE:
3043                 /* XXX: Mark closed views by letting view->prev point to the
3044                  * view itself. Parents to closed view should never be
3045                  * followed. */
3046                 if (view->prev && view->prev != view) {
3047                         maximize_view(view->prev);
3048                         view->prev = view;
3049                         break;
3050                 }
3051                 /* Fall-through */
3052         case REQ_QUIT:
3053                 return FALSE;
3055         default:
3056                 report("Unknown key, press %s for help",
3057                        get_key(view->keymap, REQ_VIEW_HELP));
3058                 return TRUE;
3059         }
3061         return TRUE;
3065 /*
3066  * View backend utilities
3067  */
3069 enum sort_field {
3070         ORDERBY_NAME,
3071         ORDERBY_DATE,
3072         ORDERBY_AUTHOR,
3073 };
3075 struct sort_state {
3076         const enum sort_field *fields;
3077         size_t size, current;
3078         bool reverse;
3079 };
3081 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3082 #define get_sort_field(state) ((state).fields[(state).current])
3083 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3085 static void
3086 sort_view(struct view *view, enum request request, struct sort_state *state,
3087           int (*compare)(const void *, const void *))
3089         switch (request) {
3090         case REQ_TOGGLE_SORT_FIELD:
3091                 state->current = (state->current + 1) % state->size;
3092                 break;
3094         case REQ_TOGGLE_SORT_ORDER:
3095                 state->reverse = !state->reverse;
3096                 break;
3097         default:
3098                 die("Not a sort request");
3099         }
3101         qsort(view->line, view->lines, sizeof(*view->line), compare);
3102         redraw_view(view);
3105 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3107 /* Small author cache to reduce memory consumption. It uses binary
3108  * search to lookup or find place to position new entries. No entries
3109  * are ever freed. */
3110 static const char *
3111 get_author(const char *name)
3113         static const char **authors;
3114         static size_t authors_size;
3115         int from = 0, to = authors_size - 1;
3117         while (from <= to) {
3118                 size_t pos = (to + from) / 2;
3119                 int cmp = strcmp(name, authors[pos]);
3121                 if (!cmp)
3122                         return authors[pos];
3124                 if (cmp < 0)
3125                         to = pos - 1;
3126                 else
3127                         from = pos + 1;
3128         }
3130         if (!realloc_authors(&authors, authors_size, 1))
3131                 return NULL;
3132         name = strdup(name);
3133         if (!name)
3134                 return NULL;
3136         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3137         authors[from] = name;
3138         authors_size++;
3140         return name;
3143 static void
3144 parse_timesec(struct time *time, const char *sec)
3146         time->sec = (time_t) atol(sec);
3149 static void
3150 parse_timezone(struct time *time, const char *zone)
3152         long tz;
3154         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3155         tz += ('0' - zone[2]) * 60 * 60;
3156         tz += ('0' - zone[3]) * 60 * 10;
3157         tz += ('0' - zone[4]) * 60;
3159         if (zone[0] == '-')
3160                 tz = -tz;
3162         time->tz = tz;
3163         time->sec -= tz;
3166 /* Parse author lines where the name may be empty:
3167  *      author  <email@address.tld> 1138474660 +0100
3168  */
3169 static void
3170 parse_author_line(char *ident, const char **author, struct time *time)
3172         char *nameend = strchr(ident, '<');
3173         char *emailend = strchr(ident, '>');
3175         if (nameend && emailend)
3176                 *nameend = *emailend = 0;
3177         ident = chomp_string(ident);
3178         if (!*ident) {
3179                 if (nameend)
3180                         ident = chomp_string(nameend + 1);
3181                 if (!*ident)
3182                         ident = "Unknown";
3183         }
3185         *author = get_author(ident);
3187         /* Parse epoch and timezone */
3188         if (emailend && emailend[1] == ' ') {
3189                 char *secs = emailend + 2;
3190                 char *zone = strchr(secs, ' ');
3192                 parse_timesec(time, secs);
3194                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3195                         parse_timezone(time, zone + 1);
3196         }
3199 /*
3200  * Pager backend
3201  */
3203 static bool
3204 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3206         if (opt_line_number && draw_lineno(view, lineno))
3207                 return TRUE;
3209         draw_text(view, line->type, line->data);
3210         return TRUE;
3213 static bool
3214 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3216         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3217         char ref[SIZEOF_STR];
3219         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3220                 return TRUE;
3222         /* This is the only fatal call, since it can "corrupt" the buffer. */
3223         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3224                 return FALSE;
3226         return TRUE;
3229 static void
3230 add_pager_refs(struct view *view, struct line *line)
3232         char buf[SIZEOF_STR];
3233         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3234         struct ref_list *list;
3235         size_t bufpos = 0, i;
3236         const char *sep = "Refs: ";
3237         bool is_tag = FALSE;
3239         assert(line->type == LINE_COMMIT);
3241         list = get_ref_list(commit_id);
3242         if (!list) {
3243                 if (view->type == VIEW_DIFF)
3244                         goto try_add_describe_ref;
3245                 return;
3246         }
3248         for (i = 0; i < list->size; i++) {
3249                 struct ref *ref = list->refs[i];
3250                 const char *fmt = ref->tag    ? "%s[%s]" :
3251                                   ref->remote ? "%s<%s>" : "%s%s";
3253                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3254                         return;
3255                 sep = ", ";
3256                 if (ref->tag)
3257                         is_tag = TRUE;
3258         }
3260         if (!is_tag && view->type == VIEW_DIFF) {
3261 try_add_describe_ref:
3262                 /* Add <tag>-g<commit_id> "fake" reference. */
3263                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3264                         return;
3265         }
3267         if (bufpos == 0)
3268                 return;
3270         add_line_text(view, buf, LINE_PP_REFS);
3273 static bool
3274 pager_read(struct view *view, char *data)
3276         struct line *line;
3278         if (!data)
3279                 return TRUE;
3281         line = add_line_text(view, data, get_line_type(data));
3282         if (!line)
3283                 return FALSE;
3285         if (line->type == LINE_COMMIT &&
3286             (view->type == VIEW_DIFF ||
3287              view->type == VIEW_LOG))
3288                 add_pager_refs(view, line);
3290         return TRUE;
3293 static enum request
3294 pager_request(struct view *view, enum request request, struct line *line)
3296         int split = 0;
3298         if (request != REQ_ENTER)
3299                 return request;
3301         if (line->type == LINE_COMMIT &&
3302            (view->type == VIEW_LOG ||
3303             view->type == VIEW_PAGER)) {
3304                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3305                 split = 1;
3306         }
3308         /* Always scroll the view even if it was split. That way
3309          * you can use Enter to scroll through the log view and
3310          * split open each commit diff. */
3311         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3313         /* FIXME: A minor workaround. Scrolling the view will call report("")
3314          * but if we are scrolling a non-current view this won't properly
3315          * update the view title. */
3316         if (split)
3317                 update_view_title(view);
3319         return REQ_NONE;
3322 static bool
3323 pager_grep(struct view *view, struct line *line)
3325         const char *text[] = { line->data, NULL };
3327         return grep_text(view, text);
3330 static void
3331 pager_select(struct view *view, struct line *line)
3333         if (line->type == LINE_COMMIT) {
3334                 char *text = (char *)line->data + STRING_SIZE("commit ");
3336                 if (view->type != VIEW_PAGER)
3337                         string_copy_rev(view->ref, text);
3338                 string_copy_rev(ref_commit, text);
3339         }
3342 static struct view_ops pager_ops = {
3343         "line",
3344         view_open,
3345         pager_read,
3346         pager_draw,
3347         pager_request,
3348         pager_grep,
3349         pager_select,
3350 };
3352 static bool
3353 log_open(struct view *view, enum open_flags flags)
3355         static const char *log_argv[] = {
3356                 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3357         };
3359         return begin_update(view, NULL, log_argv, flags);
3362 static enum request
3363 log_request(struct view *view, enum request request, struct line *line)
3365         switch (request) {
3366         case REQ_REFRESH:
3367                 load_refs();
3368                 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3369                 return REQ_NONE;
3370         default:
3371                 return pager_request(view, request, line);
3372         }
3375 static struct view_ops log_ops = {
3376         "line",
3377         log_open,
3378         pager_read,
3379         pager_draw,
3380         log_request,
3381         pager_grep,
3382         pager_select,
3383 };
3385 static bool
3386 diff_open(struct view *view, enum open_flags flags)
3388         static const char *diff_argv[] = {
3389                 "git", "show", "--pretty=fuller", "--no-color", "--root",
3390                         "--patch-with-stat", "--find-copies-harder", "-C",
3391                         "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3392         };
3394         return begin_update(view, NULL, diff_argv, flags);
3397 static bool
3398 diff_read(struct view *view, char *data)
3400         if (!data) {
3401                 /* Fall back to retry if no diff will be shown. */
3402                 if (view->lines == 0 && opt_file_argv) {
3403                         int pos = argv_size(view->argv)
3404                                 - argv_size(opt_file_argv) - 1;
3406                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3407                                 for (; view->argv[pos]; pos++) {
3408                                         free((void *) view->argv[pos]);
3409                                         view->argv[pos] = NULL;
3410                                 }
3412                                 if (view->pipe)
3413                                         io_done(view->pipe);
3414                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3415                                         return FALSE;
3416                         }
3417                 }
3418                 return TRUE;
3419         }
3421         return pager_read(view, data);
3424 static struct view_ops diff_ops = {
3425         "line",
3426         diff_open,
3427         diff_read,
3428         pager_draw,
3429         pager_request,
3430         pager_grep,
3431         pager_select,
3432 };
3434 /*
3435  * Help backend
3436  */
3438 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3440 static bool
3441 help_open_keymap_title(struct view *view, enum keymap keymap)
3443         struct line *line;
3445         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3446                                help_keymap_hidden[keymap] ? '+' : '-',
3447                                enum_name(keymap_table[keymap]));
3448         if (line)
3449                 line->other = keymap;
3451         return help_keymap_hidden[keymap];
3454 static void
3455 help_open_keymap(struct view *view, enum keymap keymap)
3457         const char *group = NULL;
3458         char buf[SIZEOF_STR];
3459         size_t bufpos;
3460         bool add_title = TRUE;
3461         int i;
3463         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3464                 const char *key = NULL;
3466                 if (req_info[i].request == REQ_NONE)
3467                         continue;
3469                 if (!req_info[i].request) {
3470                         group = req_info[i].help;
3471                         continue;
3472                 }
3474                 key = get_keys(keymap, req_info[i].request, TRUE);
3475                 if (!key || !*key)
3476                         continue;
3478                 if (add_title && help_open_keymap_title(view, keymap))
3479                         return;
3480                 add_title = FALSE;
3482                 if (group) {
3483                         add_line_text(view, group, LINE_HELP_GROUP);
3484                         group = NULL;
3485                 }
3487                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3488                                 enum_name(req_info[i]), req_info[i].help);
3489         }
3491         group = "External commands:";
3493         for (i = 0; i < run_requests; i++) {
3494                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3495                 const char *key;
3496                 int argc;
3498                 if (!req || req->keymap != keymap)
3499                         continue;
3501                 key = get_key_name(req->key);
3502                 if (!*key)
3503                         key = "(no key defined)";
3505                 if (add_title && help_open_keymap_title(view, keymap))
3506                         return;
3507                 if (group) {
3508                         add_line_text(view, group, LINE_HELP_GROUP);
3509                         group = NULL;
3510                 }
3512                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3513                         if (!string_format_from(buf, &bufpos, "%s%s",
3514                                                 argc ? " " : "", req->argv[argc]))
3515                                 return;
3517                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3518         }
3521 static bool
3522 help_open(struct view *view, enum open_flags flags)
3524         enum keymap keymap;
3526         reset_view(view);
3527         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3528         add_line_text(view, "", LINE_DEFAULT);
3530         for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3531                 help_open_keymap(view, keymap);
3533         return TRUE;
3536 static enum request
3537 help_request(struct view *view, enum request request, struct line *line)
3539         switch (request) {
3540         case REQ_ENTER:
3541                 if (line->type == LINE_HELP_KEYMAP) {
3542                         help_keymap_hidden[line->other] =
3543                                 !help_keymap_hidden[line->other];
3544                         view->p_restore = TRUE;
3545                         open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3546                 }
3548                 return REQ_NONE;
3549         default:
3550                 return pager_request(view, request, line);
3551         }
3554 static struct view_ops help_ops = {
3555         "line",
3556         help_open,
3557         NULL,
3558         pager_draw,
3559         help_request,
3560         pager_grep,
3561         pager_select,
3562 };
3565 /*
3566  * Tree backend
3567  */
3569 struct tree_stack_entry {
3570         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3571         unsigned long lineno;           /* Line number to restore */
3572         char *name;                     /* Position of name in opt_path */
3573 };
3575 /* The top of the path stack. */
3576 static struct tree_stack_entry *tree_stack = NULL;
3577 unsigned long tree_lineno = 0;
3579 static void
3580 pop_tree_stack_entry(void)
3582         struct tree_stack_entry *entry = tree_stack;
3584         tree_lineno = entry->lineno;
3585         entry->name[0] = 0;
3586         tree_stack = entry->prev;
3587         free(entry);
3590 static void
3591 push_tree_stack_entry(const char *name, unsigned long lineno)
3593         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3594         size_t pathlen = strlen(opt_path);
3596         if (!entry)
3597                 return;
3599         entry->prev = tree_stack;
3600         entry->name = opt_path + pathlen;
3601         tree_stack = entry;
3603         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3604                 pop_tree_stack_entry();
3605                 return;
3606         }
3608         /* Move the current line to the first tree entry. */
3609         tree_lineno = 1;
3610         entry->lineno = lineno;
3613 /* Parse output from git-ls-tree(1):
3614  *
3615  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3616  */
3618 #define SIZEOF_TREE_ATTR \
3619         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3621 #define SIZEOF_TREE_MODE \
3622         STRING_SIZE("100644 ")
3624 #define TREE_ID_OFFSET \
3625         STRING_SIZE("100644 blob ")
3627 struct tree_entry {
3628         char id[SIZEOF_REV];
3629         mode_t mode;
3630         struct time time;               /* Date from the author ident. */
3631         const char *author;             /* Author of the commit. */
3632         char name[1];
3633 };
3635 static const char *
3636 tree_path(const struct line *line)
3638         return ((struct tree_entry *) line->data)->name;
3641 static int
3642 tree_compare_entry(const struct line *line1, const struct line *line2)
3644         if (line1->type != line2->type)
3645                 return line1->type == LINE_TREE_DIR ? -1 : 1;
3646         return strcmp(tree_path(line1), tree_path(line2));
3649 static const enum sort_field tree_sort_fields[] = {
3650         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3651 };
3652 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3654 static int
3655 tree_compare(const void *l1, const void *l2)
3657         const struct line *line1 = (const struct line *) l1;
3658         const struct line *line2 = (const struct line *) l2;
3659         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3660         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3662         if (line1->type == LINE_TREE_HEAD)
3663                 return -1;
3664         if (line2->type == LINE_TREE_HEAD)
3665                 return 1;
3667         switch (get_sort_field(tree_sort_state)) {
3668         case ORDERBY_DATE:
3669                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3671         case ORDERBY_AUTHOR:
3672                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3674         case ORDERBY_NAME:
3675         default:
3676                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3677         }
3681 static struct line *
3682 tree_entry(struct view *view, enum line_type type, const char *path,
3683            const char *mode, const char *id)
3685         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3686         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3688         if (!entry || !line) {
3689                 free(entry);
3690                 return NULL;
3691         }
3693         strncpy(entry->name, path, strlen(path));
3694         if (mode)
3695                 entry->mode = strtoul(mode, NULL, 8);
3696         if (id)
3697                 string_copy_rev(entry->id, id);
3699         return line;
3702 static bool
3703 tree_read_date(struct view *view, char *text, bool *read_date)
3705         static const char *author_name;
3706         static struct time author_time;
3708         if (!text && *read_date) {
3709                 *read_date = FALSE;
3710                 return TRUE;
3712         } else if (!text) {
3713                 char *path = *opt_path ? opt_path : ".";
3714                 /* Find next entry to process */
3715                 const char *log_file[] = {
3716                         "git", "log", "--no-color", "--pretty=raw",
3717                                 "--cc", "--raw", view->id, "--", path, NULL
3718                 };
3720                 if (!view->lines) {
3721                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3722                         report("Tree is empty");
3723                         return TRUE;
3724                 }
3726                 if (!start_update(view, log_file, opt_cdup)) {
3727                         report("Failed to load tree data");
3728                         return TRUE;
3729                 }
3731                 *read_date = TRUE;
3732                 return FALSE;
3734         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3735                 parse_author_line(text + STRING_SIZE("author "),
3736                                   &author_name, &author_time);
3738         } else if (*text == ':') {
3739                 char *pos;
3740                 size_t annotated = 1;
3741                 size_t i;
3743                 pos = strchr(text, '\t');
3744                 if (!pos)
3745                         return TRUE;
3746                 text = pos + 1;
3747                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3748                         text += strlen(opt_path);
3749                 pos = strchr(text, '/');
3750                 if (pos)
3751                         *pos = 0;
3753                 for (i = 1; i < view->lines; i++) {
3754                         struct line *line = &view->line[i];
3755                         struct tree_entry *entry = line->data;
3757                         annotated += !!entry->author;
3758                         if (entry->author || strcmp(entry->name, text))
3759                                 continue;
3761                         entry->author = author_name;
3762                         entry->time = author_time;
3763                         line->dirty = 1;
3764                         break;
3765                 }
3767                 if (annotated == view->lines)
3768                         io_kill(view->pipe);
3769         }
3770         return TRUE;
3773 static bool
3774 tree_read(struct view *view, char *text)
3776         static bool read_date = FALSE;
3777         struct tree_entry *data;
3778         struct line *entry, *line;
3779         enum line_type type;
3780         size_t textlen = text ? strlen(text) : 0;
3781         char *path = text + SIZEOF_TREE_ATTR;
3783         if (read_date || !text)
3784                 return tree_read_date(view, text, &read_date);
3786         if (textlen <= SIZEOF_TREE_ATTR)
3787                 return FALSE;
3788         if (view->lines == 0 &&
3789             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3790                 return FALSE;
3792         /* Strip the path part ... */
3793         if (*opt_path) {
3794                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3795                 size_t striplen = strlen(opt_path);
3797                 if (pathlen > striplen)
3798                         memmove(path, path + striplen,
3799                                 pathlen - striplen + 1);
3801                 /* Insert "link" to parent directory. */
3802                 if (view->lines == 1 &&
3803                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3804                         return FALSE;
3805         }
3807         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3808         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3809         if (!entry)
3810                 return FALSE;
3811         data = entry->data;
3813         /* Skip "Directory ..." and ".." line. */
3814         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3815                 if (tree_compare_entry(line, entry) <= 0)
3816                         continue;
3818                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3820                 line->data = data;
3821                 line->type = type;
3822                 for (; line <= entry; line++)
3823                         line->dirty = line->cleareol = 1;
3824                 return TRUE;
3825         }
3827         if (tree_lineno > view->lineno) {
3828                 view->lineno = tree_lineno;
3829                 tree_lineno = 0;
3830         }
3832         return TRUE;
3835 static bool
3836 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3838         struct tree_entry *entry = line->data;
3840         if (line->type == LINE_TREE_HEAD) {
3841                 if (draw_text(view, line->type, "Directory path /"))
3842                         return TRUE;
3843         } else {
3844                 if (draw_mode(view, entry->mode))
3845                         return TRUE;
3847                 if (draw_author(view, entry->author))
3848                         return TRUE;
3850                 if (draw_date(view, &entry->time))
3851                         return TRUE;
3852         }
3854         draw_text(view, line->type, entry->name);
3855         return TRUE;
3858 static void
3859 open_blob_editor(const char *id)
3861         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3862         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3863         int fd = mkstemp(file);
3865         if (fd == -1)
3866                 report("Failed to create temporary file");
3867         else if (!io_run_append(blob_argv, fd))
3868                 report("Failed to save blob data to file");
3869         else
3870                 open_editor(file);
3871         if (fd != -1)
3872                 unlink(file);
3875 static enum request
3876 tree_request(struct view *view, enum request request, struct line *line)
3878         enum open_flags flags;
3879         struct tree_entry *entry = line->data;
3881         switch (request) {
3882         case REQ_VIEW_BLAME:
3883                 if (line->type != LINE_TREE_FILE) {
3884                         report("Blame only supported for files");
3885                         return REQ_NONE;
3886                 }
3888                 string_copy(opt_ref, view->vid);
3889                 return request;
3891         case REQ_EDIT:
3892                 if (line->type != LINE_TREE_FILE) {
3893                         report("Edit only supported for files");
3894                 } else if (!is_head_commit(view->vid)) {
3895                         open_blob_editor(entry->id);
3896                 } else {
3897                         open_editor(opt_file);
3898                 }
3899                 return REQ_NONE;
3901         case REQ_TOGGLE_SORT_FIELD:
3902         case REQ_TOGGLE_SORT_ORDER:
3903                 sort_view(view, request, &tree_sort_state, tree_compare);
3904                 return REQ_NONE;
3906         case REQ_PARENT:
3907                 if (!*opt_path) {
3908                         /* quit view if at top of tree */
3909                         return REQ_VIEW_CLOSE;
3910                 }
3911                 /* fake 'cd  ..' */
3912                 line = &view->line[1];
3913                 break;
3915         case REQ_ENTER:
3916                 break;
3918         default:
3919                 return request;
3920         }
3922         /* Cleanup the stack if the tree view is at a different tree. */
3923         while (!*opt_path && tree_stack)
3924                 pop_tree_stack_entry();
3926         switch (line->type) {
3927         case LINE_TREE_DIR:
3928                 /* Depending on whether it is a subdirectory or parent link
3929                  * mangle the path buffer. */
3930                 if (line == &view->line[1] && *opt_path) {
3931                         pop_tree_stack_entry();
3933                 } else {
3934                         const char *basename = tree_path(line);
3936                         push_tree_stack_entry(basename, view->lineno);
3937                 }
3939                 /* Trees and subtrees share the same ID, so they are not not
3940                  * unique like blobs. */
3941                 flags = OPEN_RELOAD;
3942                 request = REQ_VIEW_TREE;
3943                 break;
3945         case LINE_TREE_FILE:
3946                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3947                 request = REQ_VIEW_BLOB;
3948                 break;
3950         default:
3951                 return REQ_NONE;
3952         }
3954         open_view(view, request, flags);
3955         if (request == REQ_VIEW_TREE)
3956                 view->lineno = tree_lineno;
3958         return REQ_NONE;
3961 static bool
3962 tree_grep(struct view *view, struct line *line)
3964         struct tree_entry *entry = line->data;
3965         const char *text[] = {
3966                 entry->name,
3967                 opt_author ? entry->author : "",
3968                 mkdate(&entry->time, opt_date),
3969                 NULL
3970         };
3972         return grep_text(view, text);
3975 static void
3976 tree_select(struct view *view, struct line *line)
3978         struct tree_entry *entry = line->data;
3980         if (line->type == LINE_TREE_FILE) {
3981                 string_copy_rev(ref_blob, entry->id);
3982                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3984         } else if (line->type != LINE_TREE_DIR) {
3985                 return;
3986         }
3988         string_copy_rev(view->ref, entry->id);
3991 static bool
3992 tree_open(struct view *view, enum open_flags flags)
3994         static const char *tree_argv[] = {
3995                 "git", "ls-tree", "%(commit)", "%(directory)", NULL
3996         };
3998         if (view->lines == 0 && opt_prefix[0]) {
3999                 char *pos = opt_prefix;
4001                 while (pos && *pos) {
4002                         char *end = strchr(pos, '/');
4004                         if (end)
4005                                 *end = 0;
4006                         push_tree_stack_entry(pos, 0);
4007                         pos = end;
4008                         if (end) {
4009                                 *end = '/';
4010                                 pos++;
4011                         }
4012                 }
4014         } else if (strcmp(view->vid, view->id)) {
4015                 opt_path[0] = 0;
4016         }
4018         return begin_update(view, opt_cdup, tree_argv, flags);
4021 static struct view_ops tree_ops = {
4022         "file",
4023         tree_open,
4024         tree_read,
4025         tree_draw,
4026         tree_request,
4027         tree_grep,
4028         tree_select,
4029 };
4031 static bool
4032 blob_open(struct view *view, enum open_flags flags)
4034         static const char *blob_argv[] = {
4035                 "git", "cat-file", "blob", "%(blob)", NULL
4036         };
4038         return begin_update(view, NULL, blob_argv, flags);
4041 static bool
4042 blob_read(struct view *view, char *line)
4044         if (!line)
4045                 return TRUE;
4046         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4049 static enum request
4050 blob_request(struct view *view, enum request request, struct line *line)
4052         switch (request) {
4053         case REQ_EDIT:
4054                 open_blob_editor(view->vid);
4055                 return REQ_NONE;
4056         default:
4057                 return pager_request(view, request, line);
4058         }
4061 static struct view_ops blob_ops = {
4062         "line",
4063         blob_open,
4064         blob_read,
4065         pager_draw,
4066         blob_request,
4067         pager_grep,
4068         pager_select,
4069 };
4071 /*
4072  * Blame backend
4073  *
4074  * Loading the blame view is a two phase job:
4075  *
4076  *  1. File content is read either using opt_file from the
4077  *     filesystem or using git-cat-file.
4078  *  2. Then blame information is incrementally added by
4079  *     reading output from git-blame.
4080  */
4082 struct blame_commit {
4083         char id[SIZEOF_REV];            /* SHA1 ID. */
4084         char title[128];                /* First line of the commit message. */
4085         const char *author;             /* Author of the commit. */
4086         struct time time;               /* Date from the author ident. */
4087         char filename[128];             /* Name of file. */
4088         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4089         char parent_filename[128];      /* Parent/previous name of file. */
4090 };
4092 struct blame {
4093         struct blame_commit *commit;
4094         unsigned long lineno;
4095         char text[1];
4096 };
4098 static bool
4099 blame_open(struct view *view, enum open_flags flags)
4101         char path[SIZEOF_STR];
4102         size_t i;
4104         if (!view->prev && *opt_prefix) {
4105                 string_copy(path, opt_file);
4106                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4107                         return FALSE;
4108         }
4110         if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4111                 const char *blame_cat_file_argv[] = {
4112                         "git", "cat-file", "blob", path, NULL
4113                 };
4115                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4116                     !start_update(view, blame_cat_file_argv, opt_cdup))
4117                         return FALSE;
4118         }
4120         /* First pass: remove multiple references to the same commit. */
4121         for (i = 0; i < view->lines; i++) {
4122                 struct blame *blame = view->line[i].data;
4124                 if (blame->commit && blame->commit->id[0])
4125                         blame->commit->id[0] = 0;
4126                 else
4127                         blame->commit = NULL;
4128         }
4130         /* Second pass: free existing references. */
4131         for (i = 0; i < view->lines; i++) {
4132                 struct blame *blame = view->line[i].data;
4134                 if (blame->commit)
4135                         free(blame->commit);
4136         }
4138         setup_update(view, opt_file);
4139         string_format(view->ref, "%s ...", opt_file);
4141         return TRUE;
4144 static struct blame_commit *
4145 get_blame_commit(struct view *view, const char *id)
4147         size_t i;
4149         for (i = 0; i < view->lines; i++) {
4150                 struct blame *blame = view->line[i].data;
4152                 if (!blame->commit)
4153                         continue;
4155                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4156                         return blame->commit;
4157         }
4159         {
4160                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4162                 if (commit)
4163                         string_ncopy(commit->id, id, SIZEOF_REV);
4164                 return commit;
4165         }
4168 static bool
4169 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4171         const char *pos = *posref;
4173         *posref = NULL;
4174         pos = strchr(pos + 1, ' ');
4175         if (!pos || !isdigit(pos[1]))
4176                 return FALSE;
4177         *number = atoi(pos + 1);
4178         if (*number < min || *number > max)
4179                 return FALSE;
4181         *posref = pos;
4182         return TRUE;
4185 static struct blame_commit *
4186 parse_blame_commit(struct view *view, const char *text, int *blamed)
4188         struct blame_commit *commit;
4189         struct blame *blame;
4190         const char *pos = text + SIZEOF_REV - 2;
4191         size_t orig_lineno = 0;
4192         size_t lineno;
4193         size_t group;
4195         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4196                 return NULL;
4198         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4199             !parse_number(&pos, &lineno, 1, view->lines) ||
4200             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4201                 return NULL;
4203         commit = get_blame_commit(view, text);
4204         if (!commit)
4205                 return NULL;
4207         *blamed += group;
4208         while (group--) {
4209                 struct line *line = &view->line[lineno + group - 1];
4211                 blame = line->data;
4212                 blame->commit = commit;
4213                 blame->lineno = orig_lineno + group - 1;
4214                 line->dirty = 1;
4215         }
4217         return commit;
4220 static bool
4221 blame_read_file(struct view *view, const char *line, bool *read_file)
4223         if (!line) {
4224                 const char *blame_argv[] = {
4225                         "git", "blame", "%(blameargs)", "--incremental",
4226                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4227                 };
4229                 if (view->lines == 0 && !view->prev)
4230                         die("No blame exist for %s", view->vid);
4232                 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4233                         report("Failed to load blame data");
4234                         return TRUE;
4235                 }
4237                 *read_file = FALSE;
4238                 return FALSE;
4240         } else {
4241                 size_t linelen = strlen(line);
4242                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4244                 if (!blame)
4245                         return FALSE;
4247                 blame->commit = NULL;
4248                 strncpy(blame->text, line, linelen);
4249                 blame->text[linelen] = 0;
4250                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4251         }
4254 static bool
4255 match_blame_header(const char *name, char **line)
4257         size_t namelen = strlen(name);
4258         bool matched = !strncmp(name, *line, namelen);
4260         if (matched)
4261                 *line += namelen;
4263         return matched;
4266 static bool
4267 blame_read(struct view *view, char *line)
4269         static struct blame_commit *commit = NULL;
4270         static int blamed = 0;
4271         static bool read_file = TRUE;
4273         if (read_file)
4274                 return blame_read_file(view, line, &read_file);
4276         if (!line) {
4277                 /* Reset all! */
4278                 commit = NULL;
4279                 blamed = 0;
4280                 read_file = TRUE;
4281                 string_format(view->ref, "%s", view->vid);
4282                 if (view_is_displayed(view)) {
4283                         update_view_title(view);
4284                         redraw_view_from(view, 0);
4285                 }
4286                 return TRUE;
4287         }
4289         if (!commit) {
4290                 commit = parse_blame_commit(view, line, &blamed);
4291                 string_format(view->ref, "%s %2d%%", view->vid,
4292                               view->lines ? blamed * 100 / view->lines : 0);
4294         } else if (match_blame_header("author ", &line)) {
4295                 commit->author = get_author(line);
4297         } else if (match_blame_header("author-time ", &line)) {
4298                 parse_timesec(&commit->time, line);
4300         } else if (match_blame_header("author-tz ", &line)) {
4301                 parse_timezone(&commit->time, line);
4303         } else if (match_blame_header("summary ", &line)) {
4304                 string_ncopy(commit->title, line, strlen(line));
4306         } else if (match_blame_header("previous ", &line)) {
4307                 if (strlen(line) <= SIZEOF_REV)
4308                         return FALSE;
4309                 string_copy_rev(commit->parent_id, line);
4310                 line += SIZEOF_REV;
4311                 string_ncopy(commit->parent_filename, line, strlen(line));
4313         } else if (match_blame_header("filename ", &line)) {
4314                 string_ncopy(commit->filename, line, strlen(line));
4315                 commit = NULL;
4316         }
4318         return TRUE;
4321 static bool
4322 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4324         struct blame *blame = line->data;
4325         struct time *time = NULL;
4326         const char *id = NULL, *author = NULL;
4328         if (blame->commit && *blame->commit->filename) {
4329                 id = blame->commit->id;
4330                 author = blame->commit->author;
4331                 time = &blame->commit->time;
4332         }
4334         if (draw_date(view, time))
4335                 return TRUE;
4337         if (draw_author(view, author))
4338                 return TRUE;
4340         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4341                 return TRUE;
4343         if (draw_lineno(view, lineno))
4344                 return TRUE;
4346         draw_text(view, LINE_DEFAULT, blame->text);
4347         return TRUE;
4350 static bool
4351 check_blame_commit(struct blame *blame, bool check_null_id)
4353         if (!blame->commit)
4354                 report("Commit data not loaded yet");
4355         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4356                 report("No commit exist for the selected line");
4357         else
4358                 return TRUE;
4359         return FALSE;
4362 static void
4363 setup_blame_parent_line(struct view *view, struct blame *blame)
4365         char from[SIZEOF_REF + SIZEOF_STR];
4366         char to[SIZEOF_REF + SIZEOF_STR];
4367         const char *diff_tree_argv[] = {
4368                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4369                         "-U0", from, to, "--", NULL
4370         };
4371         struct io io;
4372         int parent_lineno = -1;
4373         int blamed_lineno = -1;
4374         char *line;
4376         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4377             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4378             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4379                 return;
4381         while ((line = io_get(&io, '\n', TRUE))) {
4382                 if (*line == '@') {
4383                         char *pos = strchr(line, '+');
4385                         parent_lineno = atoi(line + 4);
4386                         if (pos)
4387                                 blamed_lineno = atoi(pos + 1);
4389                 } else if (*line == '+' && parent_lineno != -1) {
4390                         if (blame->lineno == blamed_lineno - 1 &&
4391                             !strcmp(blame->text, line + 1)) {
4392                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4393                                 break;
4394                         }
4395                         blamed_lineno++;
4396                 }
4397         }
4399         io_done(&io);
4402 static enum request
4403 blame_request(struct view *view, enum request request, struct line *line)
4405         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4406         struct blame *blame = line->data;
4408         switch (request) {
4409         case REQ_VIEW_BLAME:
4410                 if (check_blame_commit(blame, TRUE)) {
4411                         string_copy(opt_ref, blame->commit->id);
4412                         string_copy(opt_file, blame->commit->filename);
4413                         if (blame->lineno)
4414                                 view->lineno = blame->lineno;
4415                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4416                 }
4417                 break;
4419         case REQ_PARENT:
4420                 if (!check_blame_commit(blame, TRUE))
4421                         break;
4422                 if (!*blame->commit->parent_id) {
4423                         report("The selected commit has no parents");
4424                 } else {
4425                         string_copy_rev(opt_ref, blame->commit->parent_id);
4426                         string_copy(opt_file, blame->commit->parent_filename);
4427                         setup_blame_parent_line(view, blame);
4428                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4429                 }
4430                 break;
4432         case REQ_ENTER:
4433                 if (!check_blame_commit(blame, FALSE))
4434                         break;
4436                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4437                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4438                         break;
4440                 if (!strcmp(blame->commit->id, NULL_ID)) {
4441                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4442                         const char *diff_index_argv[] = {
4443                                 "git", "diff-index", "--root", "--patch-with-stat",
4444                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4445                         };
4447                         if (!*blame->commit->parent_id) {
4448                                 diff_index_argv[1] = "diff";
4449                                 diff_index_argv[2] = "--no-color";
4450                                 diff_index_argv[6] = "--";
4451                                 diff_index_argv[7] = "/dev/null";
4452                         }
4454                         if (!prepare_update(diff, diff_index_argv, NULL)) {
4455                                 report("Failed to allocate diff command");
4456                                 break;
4457                         }
4458                         flags |= OPEN_PREPARED;
4459                 }
4461                 open_view(view, REQ_VIEW_DIFF, flags);
4462                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4463                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4464                 break;
4466         default:
4467                 return request;
4468         }
4470         return REQ_NONE;
4473 static bool
4474 blame_grep(struct view *view, struct line *line)
4476         struct blame *blame = line->data;
4477         struct blame_commit *commit = blame->commit;
4478         const char *text[] = {
4479                 blame->text,
4480                 commit ? commit->title : "",
4481                 commit ? commit->id : "",
4482                 commit && opt_author ? commit->author : "",
4483                 commit ? mkdate(&commit->time, opt_date) : "",
4484                 NULL
4485         };
4487         return grep_text(view, text);
4490 static void
4491 blame_select(struct view *view, struct line *line)
4493         struct blame *blame = line->data;
4494         struct blame_commit *commit = blame->commit;
4496         if (!commit)
4497                 return;
4499         if (!strcmp(commit->id, NULL_ID))
4500                 string_ncopy(ref_commit, "HEAD", 4);
4501         else
4502                 string_copy_rev(ref_commit, commit->id);
4505 static struct view_ops blame_ops = {
4506         "line",
4507         blame_open,
4508         blame_read,
4509         blame_draw,
4510         blame_request,
4511         blame_grep,
4512         blame_select,
4513 };
4515 /*
4516  * Branch backend
4517  */
4519 struct branch {
4520         const char *author;             /* Author of the last commit. */
4521         struct time time;               /* Date of the last activity. */
4522         const struct ref *ref;          /* Name and commit ID information. */
4523 };
4525 static const struct ref branch_all;
4527 static const enum sort_field branch_sort_fields[] = {
4528         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4529 };
4530 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4532 static int
4533 branch_compare(const void *l1, const void *l2)
4535         const struct branch *branch1 = ((const struct line *) l1)->data;
4536         const struct branch *branch2 = ((const struct line *) l2)->data;
4538         switch (get_sort_field(branch_sort_state)) {
4539         case ORDERBY_DATE:
4540                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4542         case ORDERBY_AUTHOR:
4543                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4545         case ORDERBY_NAME:
4546         default:
4547                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4548         }
4551 static bool
4552 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4554         struct branch *branch = line->data;
4555         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4557         if (draw_date(view, &branch->time))
4558                 return TRUE;
4560         if (draw_author(view, branch->author))
4561                 return TRUE;
4563         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4564         return TRUE;
4567 static enum request
4568 branch_request(struct view *view, enum request request, struct line *line)
4570         struct branch *branch = line->data;
4572         switch (request) {
4573         case REQ_REFRESH:
4574                 load_refs();
4575                 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4576                 return REQ_NONE;
4578         case REQ_TOGGLE_SORT_FIELD:
4579         case REQ_TOGGLE_SORT_ORDER:
4580                 sort_view(view, request, &branch_sort_state, branch_compare);
4581                 return REQ_NONE;
4583         case REQ_ENTER:
4584         {
4585                 const struct ref *ref = branch->ref;
4586                 const char *all_branches_argv[] = {
4587                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4588                               "--topo-order",
4589                               ref == &branch_all ? "--all" : ref->name, NULL
4590                 };
4591                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4593                 if (!prepare_update(main_view, all_branches_argv, NULL))
4594                         report("Failed to load view of all branches");
4595                 else
4596                         open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4597                 return REQ_NONE;
4598         }
4599         default:
4600                 return request;
4601         }
4604 static bool
4605 branch_read(struct view *view, char *line)
4607         static char id[SIZEOF_REV];
4608         struct branch *reference;
4609         size_t i;
4611         if (!line)
4612                 return TRUE;
4614         switch (get_line_type(line)) {
4615         case LINE_COMMIT:
4616                 string_copy_rev(id, line + STRING_SIZE("commit "));
4617                 return TRUE;
4619         case LINE_AUTHOR:
4620                 for (i = 0, reference = NULL; i < view->lines; i++) {
4621                         struct branch *branch = view->line[i].data;
4623                         if (strcmp(branch->ref->id, id))
4624                                 continue;
4626                         view->line[i].dirty = TRUE;
4627                         if (reference) {
4628                                 branch->author = reference->author;
4629                                 branch->time = reference->time;
4630                                 continue;
4631                         }
4633                         parse_author_line(line + STRING_SIZE("author "),
4634                                           &branch->author, &branch->time);
4635                         reference = branch;
4636                 }
4637                 return TRUE;
4639         default:
4640                 return TRUE;
4641         }
4645 static bool
4646 branch_open_visitor(void *data, const struct ref *ref)
4648         struct view *view = data;
4649         struct branch *branch;
4651         if (ref->tag || ref->ltag || ref->remote)
4652                 return TRUE;
4654         branch = calloc(1, sizeof(*branch));
4655         if (!branch)
4656                 return FALSE;
4658         branch->ref = ref;
4659         return !!add_line_data(view, branch, LINE_DEFAULT);
4662 static bool
4663 branch_open(struct view *view, enum open_flags flags)
4665         const char *branch_log[] = {
4666                 "git", "log", "--no-color", "--pretty=raw",
4667                         "--simplify-by-decoration", "--all", NULL
4668         };
4670         if (!start_update(view, branch_log, NULL)) {
4671                 report("Failed to load branch data");
4672                 return TRUE;
4673         }
4675         setup_update(view, view->id);
4676         branch_open_visitor(view, &branch_all);
4677         foreach_ref(branch_open_visitor, view);
4678         view->p_restore = TRUE;
4680         return TRUE;
4683 static bool
4684 branch_grep(struct view *view, struct line *line)
4686         struct branch *branch = line->data;
4687         const char *text[] = {
4688                 branch->ref->name,
4689                 branch->author,
4690                 NULL
4691         };
4693         return grep_text(view, text);
4696 static void
4697 branch_select(struct view *view, struct line *line)
4699         struct branch *branch = line->data;
4701         string_copy_rev(view->ref, branch->ref->id);
4702         string_copy_rev(ref_commit, branch->ref->id);
4703         string_copy_rev(ref_head, branch->ref->id);
4704         string_copy_rev(ref_branch, branch->ref->name);
4707 static struct view_ops branch_ops = {
4708         "branch",
4709         branch_open,
4710         branch_read,
4711         branch_draw,
4712         branch_request,
4713         branch_grep,
4714         branch_select,
4715 };
4717 /*
4718  * Status backend
4719  */
4721 struct status {
4722         char status;
4723         struct {
4724                 mode_t mode;
4725                 char rev[SIZEOF_REV];
4726                 char name[SIZEOF_STR];
4727         } old;
4728         struct {
4729                 mode_t mode;
4730                 char rev[SIZEOF_REV];
4731                 char name[SIZEOF_STR];
4732         } new;
4733 };
4735 static char status_onbranch[SIZEOF_STR];
4736 static struct status stage_status;
4737 static enum line_type stage_line_type;
4738 static size_t stage_chunks;
4739 static int *stage_chunk;
4741 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4743 /* This should work even for the "On branch" line. */
4744 static inline bool
4745 status_has_none(struct view *view, struct line *line)
4747         return line < view->line + view->lines && !line[1].data;
4750 /* Get fields from the diff line:
4751  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4752  */
4753 static inline bool
4754 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4756         const char *old_mode = buf +  1;
4757         const char *new_mode = buf +  8;
4758         const char *old_rev  = buf + 15;
4759         const char *new_rev  = buf + 56;
4760         const char *status   = buf + 97;
4762         if (bufsize < 98 ||
4763             old_mode[-1] != ':' ||
4764             new_mode[-1] != ' ' ||
4765             old_rev[-1]  != ' ' ||
4766             new_rev[-1]  != ' ' ||
4767             status[-1]   != ' ')
4768                 return FALSE;
4770         file->status = *status;
4772         string_copy_rev(file->old.rev, old_rev);
4773         string_copy_rev(file->new.rev, new_rev);
4775         file->old.mode = strtoul(old_mode, NULL, 8);
4776         file->new.mode = strtoul(new_mode, NULL, 8);
4778         file->old.name[0] = file->new.name[0] = 0;
4780         return TRUE;
4783 static bool
4784 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4786         struct status *unmerged = NULL;
4787         char *buf;
4788         struct io io;
4790         if (!io_run(&io, IO_RD, opt_cdup, argv))
4791                 return FALSE;
4793         add_line_data(view, NULL, type);
4795         while ((buf = io_get(&io, 0, TRUE))) {
4796                 struct status *file = unmerged;
4798                 if (!file) {
4799                         file = calloc(1, sizeof(*file));
4800                         if (!file || !add_line_data(view, file, type))
4801                                 goto error_out;
4802                 }
4804                 /* Parse diff info part. */
4805                 if (status) {
4806                         file->status = status;
4807                         if (status == 'A')
4808                                 string_copy(file->old.rev, NULL_ID);
4810                 } else if (!file->status || file == unmerged) {
4811                         if (!status_get_diff(file, buf, strlen(buf)))
4812                                 goto error_out;
4814                         buf = io_get(&io, 0, TRUE);
4815                         if (!buf)
4816                                 break;
4818                         /* Collapse all modified entries that follow an
4819                          * associated unmerged entry. */
4820                         if (unmerged == file) {
4821                                 unmerged->status = 'U';
4822                                 unmerged = NULL;
4823                         } else if (file->status == 'U') {
4824                                 unmerged = file;
4825                         }
4826                 }
4828                 /* Grab the old name for rename/copy. */
4829                 if (!*file->old.name &&
4830                     (file->status == 'R' || file->status == 'C')) {
4831                         string_ncopy(file->old.name, buf, strlen(buf));
4833                         buf = io_get(&io, 0, TRUE);
4834                         if (!buf)
4835                                 break;
4836                 }
4838                 /* git-ls-files just delivers a NUL separated list of
4839                  * file names similar to the second half of the
4840                  * git-diff-* output. */
4841                 string_ncopy(file->new.name, buf, strlen(buf));
4842                 if (!*file->old.name)
4843                         string_copy(file->old.name, file->new.name);
4844                 file = NULL;
4845         }
4847         if (io_error(&io)) {
4848 error_out:
4849                 io_done(&io);
4850                 return FALSE;
4851         }
4853         if (!view->line[view->lines - 1].data)
4854                 add_line_data(view, NULL, LINE_STAT_NONE);
4856         io_done(&io);
4857         return TRUE;
4860 /* Don't show unmerged entries in the staged section. */
4861 static const char *status_diff_index_argv[] = {
4862         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4863                              "--cached", "-M", "HEAD", NULL
4864 };
4866 static const char *status_diff_files_argv[] = {
4867         "git", "diff-files", "-z", NULL
4868 };
4870 static const char *status_list_other_argv[] = {
4871         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4872 };
4874 static const char *status_list_no_head_argv[] = {
4875         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4876 };
4878 static const char *update_index_argv[] = {
4879         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4880 };
4882 /* Restore the previous line number to stay in the context or select a
4883  * line with something that can be updated. */
4884 static void
4885 status_restore(struct view *view)
4887         if (view->p_lineno >= view->lines)
4888                 view->p_lineno = view->lines - 1;
4889         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4890                 view->p_lineno++;
4891         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4892                 view->p_lineno--;
4894         /* If the above fails, always skip the "On branch" line. */
4895         if (view->p_lineno < view->lines)
4896                 view->lineno = view->p_lineno;
4897         else
4898                 view->lineno = 1;
4900         if (view->lineno < view->offset)
4901                 view->offset = view->lineno;
4902         else if (view->offset + view->height <= view->lineno)
4903                 view->offset = view->lineno - view->height + 1;
4905         view->p_restore = FALSE;
4908 static void
4909 status_update_onbranch(void)
4911         static const char *paths[][2] = {
4912                 { "rebase-apply/rebasing",      "Rebasing" },
4913                 { "rebase-apply/applying",      "Applying mailbox" },
4914                 { "rebase-apply/",              "Rebasing mailbox" },
4915                 { "rebase-merge/interactive",   "Interactive rebase" },
4916                 { "rebase-merge/",              "Rebase merge" },
4917                 { "MERGE_HEAD",                 "Merging" },
4918                 { "BISECT_LOG",                 "Bisecting" },
4919                 { "HEAD",                       "On branch" },
4920         };
4921         char buf[SIZEOF_STR];
4922         struct stat stat;
4923         int i;
4925         if (is_initial_commit()) {
4926                 string_copy(status_onbranch, "Initial commit");
4927                 return;
4928         }
4930         for (i = 0; i < ARRAY_SIZE(paths); i++) {
4931                 char *head = opt_head;
4933                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4934                     lstat(buf, &stat) < 0)
4935                         continue;
4937                 if (!*opt_head) {
4938                         struct io io;
4940                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4941                             io_read_buf(&io, buf, sizeof(buf))) {
4942                                 head = buf;
4943                                 if (!prefixcmp(head, "refs/heads/"))
4944                                         head += STRING_SIZE("refs/heads/");
4945                         }
4946                 }
4948                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4949                         string_copy(status_onbranch, opt_head);
4950                 return;
4951         }
4953         string_copy(status_onbranch, "Not currently on any branch");
4956 /* First parse staged info using git-diff-index(1), then parse unstaged
4957  * info using git-diff-files(1), and finally untracked files using
4958  * git-ls-files(1). */
4959 static bool
4960 status_open(struct view *view, enum open_flags flags)
4962         reset_view(view);
4964         add_line_data(view, NULL, LINE_STAT_HEAD);
4965         status_update_onbranch();
4967         io_run_bg(update_index_argv);
4969         if (is_initial_commit()) {
4970                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4971                         return FALSE;
4972         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4973                 return FALSE;
4974         }
4976         if (!opt_untracked_dirs_content)
4977                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4979         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4980             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4981                 return FALSE;
4983         /* Restore the exact position or use the specialized restore
4984          * mode? */
4985         if (!view->p_restore)
4986                 status_restore(view);
4987         return TRUE;
4990 static bool
4991 status_draw(struct view *view, struct line *line, unsigned int lineno)
4993         struct status *status = line->data;
4994         enum line_type type;
4995         const char *text;
4997         if (!status) {
4998                 switch (line->type) {
4999                 case LINE_STAT_STAGED:
5000                         type = LINE_STAT_SECTION;
5001                         text = "Changes to be committed:";
5002                         break;
5004                 case LINE_STAT_UNSTAGED:
5005                         type = LINE_STAT_SECTION;
5006                         text = "Changed but not updated:";
5007                         break;
5009                 case LINE_STAT_UNTRACKED:
5010                         type = LINE_STAT_SECTION;
5011                         text = "Untracked files:";
5012                         break;
5014                 case LINE_STAT_NONE:
5015                         type = LINE_DEFAULT;
5016                         text = "  (no files)";
5017                         break;
5019                 case LINE_STAT_HEAD:
5020                         type = LINE_STAT_HEAD;
5021                         text = status_onbranch;
5022                         break;
5024                 default:
5025                         return FALSE;
5026                 }
5027         } else {
5028                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5030                 buf[0] = status->status;
5031                 if (draw_text(view, line->type, buf))
5032                         return TRUE;
5033                 type = LINE_DEFAULT;
5034                 text = status->new.name;
5035         }
5037         draw_text(view, type, text);
5038         return TRUE;
5041 static enum request
5042 status_load_error(struct view *view, struct view *stage, const char *path)
5044         if (displayed_views() == 2 || display[current_view] != view)
5045                 maximize_view(view);
5046         report("Failed to load '%s': %s", path, io_strerror(&stage->io));
5047         return REQ_NONE;
5050 static enum request
5051 status_enter(struct view *view, struct line *line)
5053         struct status *status = line->data;
5054         const char *oldpath = status ? status->old.name : NULL;
5055         /* Diffs for unmerged entries are empty when passing the new
5056          * path, so leave it empty. */
5057         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5058         const char *info;
5059         enum open_flags split;
5060         struct view *stage = VIEW(REQ_VIEW_STAGE);
5062         if (line->type == LINE_STAT_NONE ||
5063             (!status && line[1].type == LINE_STAT_NONE)) {
5064                 report("No file to diff");
5065                 return REQ_NONE;
5066         }
5068         switch (line->type) {
5069         case LINE_STAT_STAGED:
5070                 if (is_initial_commit()) {
5071                         const char *no_head_diff_argv[] = {
5072                                 "git", "diff", "--no-color", "--patch-with-stat",
5073                                         "--", "/dev/null", newpath, NULL
5074                         };
5076                         if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5077                                 return status_load_error(view, stage, newpath);
5078                 } else {
5079                         const char *index_show_argv[] = {
5080                                 "git", "diff-index", "--root", "--patch-with-stat",
5081                                         "-C", "-M", "--cached", "HEAD", "--",
5082                                         oldpath, newpath, NULL
5083                         };
5085                         if (!prepare_update(stage, index_show_argv, opt_cdup))
5086                                 return status_load_error(view, stage, newpath);
5087                 }
5089                 if (status)
5090                         info = "Staged changes to %s";
5091                 else
5092                         info = "Staged changes";
5093                 break;
5095         case LINE_STAT_UNSTAGED:
5096         {
5097                 const char *files_show_argv[] = {
5098                         "git", "diff-files", "--root", "--patch-with-stat",
5099                                 "-C", "-M", "--", oldpath, newpath, NULL
5100                 };
5102                 if (!prepare_update(stage, files_show_argv, opt_cdup))
5103                         return status_load_error(view, stage, newpath);
5104                 if (status)
5105                         info = "Unstaged changes to %s";
5106                 else
5107                         info = "Unstaged changes";
5108                 break;
5109         }
5110         case LINE_STAT_UNTRACKED:
5111                 if (!newpath) {
5112                         report("No file to show");
5113                         return REQ_NONE;
5114                 }
5116                 if (!suffixcmp(status->new.name, -1, "/")) {
5117                         report("Cannot display a directory");
5118                         return REQ_NONE;
5119                 }
5121                 if (!prepare_update_file(stage, newpath))
5122                         return status_load_error(view, stage, newpath);
5123                 info = "Untracked file %s";
5124                 break;
5126         case LINE_STAT_HEAD:
5127                 return REQ_NONE;
5129         default:
5130                 die("line type %d not handled in switch", line->type);
5131         }
5133         split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5134         open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5135         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5136                 if (status) {
5137                         stage_status = *status;
5138                 } else {
5139                         memset(&stage_status, 0, sizeof(stage_status));
5140                 }
5142                 stage_line_type = line->type;
5143                 stage_chunks = 0;
5144                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5145         }
5147         return REQ_NONE;
5150 static bool
5151 status_exists(struct status *status, enum line_type type)
5153         struct view *view = VIEW(REQ_VIEW_STATUS);
5154         unsigned long lineno;
5156         for (lineno = 0; lineno < view->lines; lineno++) {
5157                 struct line *line = &view->line[lineno];
5158                 struct status *pos = line->data;
5160                 if (line->type != type)
5161                         continue;
5162                 if (!pos && (!status || !status->status) && line[1].data) {
5163                         select_view_line(view, lineno);
5164                         return TRUE;
5165                 }
5166                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5167                         select_view_line(view, lineno);
5168                         return TRUE;
5169                 }
5170         }
5172         return FALSE;
5176 static bool
5177 status_update_prepare(struct io *io, enum line_type type)
5179         const char *staged_argv[] = {
5180                 "git", "update-index", "-z", "--index-info", NULL
5181         };
5182         const char *others_argv[] = {
5183                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5184         };
5186         switch (type) {
5187         case LINE_STAT_STAGED:
5188                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5190         case LINE_STAT_UNSTAGED:
5191         case LINE_STAT_UNTRACKED:
5192                 return io_run(io, IO_WR, opt_cdup, others_argv);
5194         default:
5195                 die("line type %d not handled in switch", type);
5196                 return FALSE;
5197         }
5200 static bool
5201 status_update_write(struct io *io, struct status *status, enum line_type type)
5203         char buf[SIZEOF_STR];
5204         size_t bufsize = 0;
5206         switch (type) {
5207         case LINE_STAT_STAGED:
5208                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5209                                         status->old.mode,
5210                                         status->old.rev,
5211                                         status->old.name, 0))
5212                         return FALSE;
5213                 break;
5215         case LINE_STAT_UNSTAGED:
5216         case LINE_STAT_UNTRACKED:
5217                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5218                         return FALSE;
5219                 break;
5221         default:
5222                 die("line type %d not handled in switch", type);
5223         }
5225         return io_write(io, buf, bufsize);
5228 static bool
5229 status_update_file(struct status *status, enum line_type type)
5231         struct io io;
5232         bool result;
5234         if (!status_update_prepare(&io, type))
5235                 return FALSE;
5237         result = status_update_write(&io, status, type);
5238         return io_done(&io) && result;
5241 static bool
5242 status_update_files(struct view *view, struct line *line)
5244         char buf[sizeof(view->ref)];
5245         struct io io;
5246         bool result = TRUE;
5247         struct line *pos = view->line + view->lines;
5248         int files = 0;
5249         int file, done;
5250         int cursor_y = -1, cursor_x = -1;
5252         if (!status_update_prepare(&io, line->type))
5253                 return FALSE;
5255         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5256                 files++;
5258         string_copy(buf, view->ref);
5259         getsyx(cursor_y, cursor_x);
5260         for (file = 0, done = 5; result && file < files; line++, file++) {
5261                 int almost_done = file * 100 / files;
5263                 if (almost_done > done) {
5264                         done = almost_done;
5265                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5266                                       file, files, done);
5267                         update_view_title(view);
5268                         setsyx(cursor_y, cursor_x);
5269                         doupdate();
5270                 }
5271                 result = status_update_write(&io, line->data, line->type);
5272         }
5273         string_copy(view->ref, buf);
5275         return io_done(&io) && result;
5278 static bool
5279 status_update(struct view *view)
5281         struct line *line = &view->line[view->lineno];
5283         assert(view->lines);
5285         if (!line->data) {
5286                 /* This should work even for the "On branch" line. */
5287                 if (line < view->line + view->lines && !line[1].data) {
5288                         report("Nothing to update");
5289                         return FALSE;
5290                 }
5292                 if (!status_update_files(view, line + 1)) {
5293                         report("Failed to update file status");
5294                         return FALSE;
5295                 }
5297         } else if (!status_update_file(line->data, line->type)) {
5298                 report("Failed to update file status");
5299                 return FALSE;
5300         }
5302         return TRUE;
5305 static bool
5306 status_revert(struct status *status, enum line_type type, bool has_none)
5308         if (!status || type != LINE_STAT_UNSTAGED) {
5309                 if (type == LINE_STAT_STAGED) {
5310                         report("Cannot revert changes to staged files");
5311                 } else if (type == LINE_STAT_UNTRACKED) {
5312                         report("Cannot revert changes to untracked files");
5313                 } else if (has_none) {
5314                         report("Nothing to revert");
5315                 } else {
5316                         report("Cannot revert changes to multiple files");
5317                 }
5319         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5320                 char mode[10] = "100644";
5321                 const char *reset_argv[] = {
5322                         "git", "update-index", "--cacheinfo", mode,
5323                                 status->old.rev, status->old.name, NULL
5324                 };
5325                 const char *checkout_argv[] = {
5326                         "git", "checkout", "--", status->old.name, NULL
5327                 };
5329                 if (status->status == 'U') {
5330                         string_format(mode, "%5o", status->old.mode);
5332                         if (status->old.mode == 0 && status->new.mode == 0) {
5333                                 reset_argv[2] = "--force-remove";
5334                                 reset_argv[3] = status->old.name;
5335                                 reset_argv[4] = NULL;
5336                         }
5338                         if (!io_run_fg(reset_argv, opt_cdup))
5339                                 return FALSE;
5340                         if (status->old.mode == 0 && status->new.mode == 0)
5341                                 return TRUE;
5342                 }
5344                 return io_run_fg(checkout_argv, opt_cdup);
5345         }
5347         return FALSE;
5350 static enum request
5351 status_request(struct view *view, enum request request, struct line *line)
5353         struct status *status = line->data;
5355         switch (request) {
5356         case REQ_STATUS_UPDATE:
5357                 if (!status_update(view))
5358                         return REQ_NONE;
5359                 break;
5361         case REQ_STATUS_REVERT:
5362                 if (!status_revert(status, line->type, status_has_none(view, line)))
5363                         return REQ_NONE;
5364                 break;
5366         case REQ_STATUS_MERGE:
5367                 if (!status || status->status != 'U') {
5368                         report("Merging only possible for files with unmerged status ('U').");
5369                         return REQ_NONE;
5370                 }
5371                 open_mergetool(status->new.name);
5372                 break;
5374         case REQ_EDIT:
5375                 if (!status)
5376                         return request;
5377                 if (status->status == 'D') {
5378                         report("File has been deleted.");
5379                         return REQ_NONE;
5380                 }
5382                 open_editor(status->new.name);
5383                 break;
5385         case REQ_VIEW_BLAME:
5386                 if (status)
5387                         opt_ref[0] = 0;
5388                 return request;
5390         case REQ_ENTER:
5391                 /* After returning the status view has been split to
5392                  * show the stage view. No further reloading is
5393                  * necessary. */
5394                 return status_enter(view, line);
5396         case REQ_REFRESH:
5397                 /* Simply reload the view. */
5398                 break;
5400         default:
5401                 return request;
5402         }
5404         open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5406         return REQ_NONE;
5409 static void
5410 status_select(struct view *view, struct line *line)
5412         struct status *status = line->data;
5413         char file[SIZEOF_STR] = "all files";
5414         const char *text;
5415         const char *key;
5417         if (status && !string_format(file, "'%s'", status->new.name))
5418                 return;
5420         if (!status && line[1].type == LINE_STAT_NONE)
5421                 line++;
5423         switch (line->type) {
5424         case LINE_STAT_STAGED:
5425                 text = "Press %s to unstage %s for commit";
5426                 break;
5428         case LINE_STAT_UNSTAGED:
5429                 text = "Press %s to stage %s for commit";
5430                 break;
5432         case LINE_STAT_UNTRACKED:
5433                 text = "Press %s to stage %s for addition";
5434                 break;
5436         case LINE_STAT_HEAD:
5437         case LINE_STAT_NONE:
5438                 text = "Nothing to update";
5439                 break;
5441         default:
5442                 die("line type %d not handled in switch", line->type);
5443         }
5445         if (status && status->status == 'U') {
5446                 text = "Press %s to resolve conflict in %s";
5447                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5449         } else {
5450                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5451         }
5453         string_format(view->ref, text, key, file);
5454         if (status)
5455                 string_copy(opt_file, status->new.name);
5458 static bool
5459 status_grep(struct view *view, struct line *line)
5461         struct status *status = line->data;
5463         if (status) {
5464                 const char buf[2] = { status->status, 0 };
5465                 const char *text[] = { status->new.name, buf, NULL };
5467                 return grep_text(view, text);
5468         }
5470         return FALSE;
5473 static struct view_ops status_ops = {
5474         "file",
5475         status_open,
5476         NULL,
5477         status_draw,
5478         status_request,
5479         status_grep,
5480         status_select,
5481 };
5484 static bool
5485 stage_diff_write(struct io *io, struct line *line, struct line *end)
5487         while (line < end) {
5488                 if (!io_write(io, line->data, strlen(line->data)) ||
5489                     !io_write(io, "\n", 1))
5490                         return FALSE;
5491                 line++;
5492                 if (line->type == LINE_DIFF_CHUNK ||
5493                     line->type == LINE_DIFF_HEADER)
5494                         break;
5495         }
5497         return TRUE;
5500 static struct line *
5501 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5503         for (; view->line < line; line--)
5504                 if (line->type == type)
5505                         return line;
5507         return NULL;
5510 static bool
5511 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5513         const char *apply_argv[SIZEOF_ARG] = {
5514                 "git", "apply", "--whitespace=nowarn", NULL
5515         };
5516         struct line *diff_hdr;
5517         struct io io;
5518         int argc = 3;
5520         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5521         if (!diff_hdr)
5522                 return FALSE;
5524         if (!revert)
5525                 apply_argv[argc++] = "--cached";
5526         if (revert || stage_line_type == LINE_STAT_STAGED)
5527                 apply_argv[argc++] = "-R";
5528         apply_argv[argc++] = "-";
5529         apply_argv[argc++] = NULL;
5530         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5531                 return FALSE;
5533         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5534             !stage_diff_write(&io, chunk, view->line + view->lines))
5535                 chunk = NULL;
5537         io_done(&io);
5538         io_run_bg(update_index_argv);
5540         return chunk ? TRUE : FALSE;
5543 static bool
5544 stage_update(struct view *view, struct line *line)
5546         struct line *chunk = NULL;
5548         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5549                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5551         if (chunk) {
5552                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5553                         report("Failed to apply chunk");
5554                         return FALSE;
5555                 }
5557         } else if (!stage_status.status) {
5558                 view = VIEW(REQ_VIEW_STATUS);
5560                 for (line = view->line; line < view->line + view->lines; line++)
5561                         if (line->type == stage_line_type)
5562                                 break;
5564                 if (!status_update_files(view, line + 1)) {
5565                         report("Failed to update files");
5566                         return FALSE;
5567                 }
5569         } else if (!status_update_file(&stage_status, stage_line_type)) {
5570                 report("Failed to update file");
5571                 return FALSE;
5572         }
5574         return TRUE;
5577 static bool
5578 stage_revert(struct view *view, struct line *line)
5580         struct line *chunk = NULL;
5582         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5583                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5585         if (chunk) {
5586                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5587                         return FALSE;
5589                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5590                         report("Failed to revert chunk");
5591                         return FALSE;
5592                 }
5593                 return TRUE;
5595         } else {
5596                 return status_revert(stage_status.status ? &stage_status : NULL,
5597                                      stage_line_type, FALSE);
5598         }
5602 static void
5603 stage_next(struct view *view, struct line *line)
5605         int i;
5607         if (!stage_chunks) {
5608                 for (line = view->line; line < view->line + view->lines; line++) {
5609                         if (line->type != LINE_DIFF_CHUNK)
5610                                 continue;
5612                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5613                                 report("Allocation failure");
5614                                 return;
5615                         }
5617                         stage_chunk[stage_chunks++] = line - view->line;
5618                 }
5619         }
5621         for (i = 0; i < stage_chunks; i++) {
5622                 if (stage_chunk[i] > view->lineno) {
5623                         do_scroll_view(view, stage_chunk[i] - view->lineno);
5624                         report("Chunk %d of %d", i + 1, stage_chunks);
5625                         return;
5626                 }
5627         }
5629         report("No next chunk found");
5632 static enum request
5633 stage_request(struct view *view, enum request request, struct line *line)
5635         switch (request) {
5636         case REQ_STATUS_UPDATE:
5637                 if (!stage_update(view, line))
5638                         return REQ_NONE;
5639                 break;
5641         case REQ_STATUS_REVERT:
5642                 if (!stage_revert(view, line))
5643                         return REQ_NONE;
5644                 break;
5646         case REQ_STAGE_NEXT:
5647                 if (stage_line_type == LINE_STAT_UNTRACKED) {
5648                         report("File is untracked; press %s to add",
5649                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5650                         return REQ_NONE;
5651                 }
5652                 stage_next(view, line);
5653                 return REQ_NONE;
5655         case REQ_EDIT:
5656                 if (!stage_status.new.name[0])
5657                         return request;
5658                 if (stage_status.status == 'D') {
5659                         report("File has been deleted.");
5660                         return REQ_NONE;
5661                 }
5663                 open_editor(stage_status.new.name);
5664                 break;
5666         case REQ_REFRESH:
5667                 /* Reload everything ... */
5668                 break;
5670         case REQ_VIEW_BLAME:
5671                 if (stage_status.new.name[0]) {
5672                         string_copy(opt_file, stage_status.new.name);
5673                         opt_ref[0] = 0;
5674                 }
5675                 return request;
5677         case REQ_ENTER:
5678                 return pager_request(view, request, line);
5680         default:
5681                 return request;
5682         }
5684         VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
5685         open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
5687         /* Check whether the staged entry still exists, and close the
5688          * stage view if it doesn't. */
5689         if (!status_exists(&stage_status, stage_line_type)) {
5690                 status_restore(VIEW(REQ_VIEW_STATUS));
5691                 return REQ_VIEW_CLOSE;
5692         }
5694         open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
5696         return REQ_NONE;
5699 static struct view_ops stage_ops = {
5700         "line",
5701         view_open,
5702         pager_read,
5703         pager_draw,
5704         stage_request,
5705         pager_grep,
5706         pager_select,
5707 };
5710 /*
5711  * Revision graph
5712  */
5714 static const enum line_type graph_colors[] = {
5715         LINE_GRAPH_LINE_0,
5716         LINE_GRAPH_LINE_1,
5717         LINE_GRAPH_LINE_2,
5718         LINE_GRAPH_LINE_3,
5719         LINE_GRAPH_LINE_4,
5720         LINE_GRAPH_LINE_5,
5721         LINE_GRAPH_LINE_6,
5722 };
5724 static enum line_type get_graph_color(struct graph_symbol *symbol)
5726         if (symbol->commit)
5727                 return LINE_GRAPH_COMMIT;
5728         assert(symbol->color < ARRAY_SIZE(graph_colors));
5729         return graph_colors[symbol->color];
5732 static bool
5733 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5735         const char *chars = graph_symbol_to_utf8(symbol);
5737         return draw_text(view, color, chars + !!first); 
5740 static bool
5741 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5743         const char *chars = graph_symbol_to_ascii(symbol);
5745         return draw_text(view, color, chars + !!first); 
5748 static bool
5749 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5751         const chtype *chars = graph_symbol_to_chtype(symbol);
5753         return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE); 
5756 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5758 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5760         static const draw_graph_fn fns[] = {
5761                 draw_graph_ascii,
5762                 draw_graph_chtype,
5763                 draw_graph_utf8
5764         };
5765         draw_graph_fn fn = fns[opt_line_graphics];
5766         int i;
5768         for (i = 0; i < canvas->size; i++) {
5769                 struct graph_symbol *symbol = &canvas->symbols[i];
5770                 enum line_type color = get_graph_color(symbol);
5772                 if (fn(view, symbol, color, i == 0))
5773                         return TRUE;
5774         }
5776         return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5779 /*
5780  * Main view backend
5781  */
5783 struct commit {
5784         char id[SIZEOF_REV];            /* SHA1 ID. */
5785         char title[128];                /* First line of the commit message. */
5786         const char *author;             /* Author of the commit. */
5787         struct time time;               /* Date from the author ident. */
5788         struct ref_list *refs;          /* Repository references. */
5789         struct graph_canvas graph;      /* Ancestry chain graphics. */
5790 };
5792 static bool
5793 main_open(struct view *view, enum open_flags flags)
5795         static const char *main_argv[] = {
5796                 "git", "log", "--no-color", "--pretty=raw", "--parents",
5797                         "--topo-order", "%(diffargs)", "%(revargs)",
5798                         "--", "%(fileargs)", NULL
5799         };
5801         return begin_update(view, NULL, main_argv, flags);
5804 static bool
5805 main_draw(struct view *view, struct line *line, unsigned int lineno)
5807         struct commit *commit = line->data;
5809         if (!commit->author)
5810                 return FALSE;
5812         if (draw_date(view, &commit->time))
5813                 return TRUE;
5815         if (draw_author(view, commit->author))
5816                 return TRUE;
5818         if (opt_rev_graph && draw_graph(view, &commit->graph))
5819                 return TRUE;
5821         if (opt_show_refs && commit->refs) {
5822                 size_t i;
5824                 for (i = 0; i < commit->refs->size; i++) {
5825                         struct ref *ref = commit->refs->refs[i];
5826                         enum line_type type;
5828                         if (ref->head)
5829                                 type = LINE_MAIN_HEAD;
5830                         else if (ref->ltag)
5831                                 type = LINE_MAIN_LOCAL_TAG;
5832                         else if (ref->tag)
5833                                 type = LINE_MAIN_TAG;
5834                         else if (ref->tracked)
5835                                 type = LINE_MAIN_TRACKED;
5836                         else if (ref->remote)
5837                                 type = LINE_MAIN_REMOTE;
5838                         else
5839                                 type = LINE_MAIN_REF;
5841                         if (draw_text(view, type, "[") ||
5842                             draw_text(view, type, ref->name) ||
5843                             draw_text(view, type, "]"))
5844                                 return TRUE;
5846                         if (draw_text(view, LINE_DEFAULT, " "))
5847                                 return TRUE;
5848                 }
5849         }
5851         draw_text(view, LINE_DEFAULT, commit->title);
5852         return TRUE;
5855 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5856 static bool
5857 main_read(struct view *view, char *line)
5859         static struct graph graph;
5860         enum line_type type;
5861         struct commit *commit;
5863         if (!line) {
5864                 if (!view->lines && !view->prev)
5865                         die("No revisions match the given arguments.");
5866                 if (view->lines > 0) {
5867                         commit = view->line[view->lines - 1].data;
5868                         view->line[view->lines - 1].dirty = 1;
5869                         if (!commit->author) {
5870                                 view->lines--;
5871                                 free(commit);
5872                         }
5873                 }
5875                 done_graph(&graph);
5876                 return TRUE;
5877         }
5879         type = get_line_type(line);
5880         if (type == LINE_COMMIT) {
5881                 bool is_boundary;
5883                 commit = calloc(1, sizeof(struct commit));
5884                 if (!commit)
5885                         return FALSE;
5887                 line += STRING_SIZE("commit ");
5888                 is_boundary = *line == '-';
5889                 if (is_boundary)
5890                         line++;
5892                 string_copy_rev(commit->id, line);
5893                 commit->refs = get_ref_list(commit->id);
5894                 add_line_data(view, commit, LINE_MAIN_COMMIT);
5895                 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5896                 return TRUE;
5897         }
5899         if (!view->lines)
5900                 return TRUE;
5901         commit = view->line[view->lines - 1].data;
5903         switch (type) {
5904         case LINE_PARENT:
5905                 if (!graph.has_parents)
5906                         graph_add_parent(&graph, line + STRING_SIZE("parent "));
5907                 break;
5909         case LINE_AUTHOR:
5910                 parse_author_line(line + STRING_SIZE("author "),
5911                                   &commit->author, &commit->time);
5912                 graph_render_parents(&graph);
5913                 break;
5915         default:
5916                 /* Fill in the commit title if it has not already been set. */
5917                 if (commit->title[0])
5918                         break;
5920                 /* Require titles to start with a non-space character at the
5921                  * offset used by git log. */
5922                 if (strncmp(line, "    ", 4))
5923                         break;
5924                 line += 4;
5925                 /* Well, if the title starts with a whitespace character,
5926                  * try to be forgiving.  Otherwise we end up with no title. */
5927                 while (isspace(*line))
5928                         line++;
5929                 if (*line == '\0')
5930                         break;
5931                 /* FIXME: More graceful handling of titles; append "..." to
5932                  * shortened titles, etc. */
5934                 string_expand(commit->title, sizeof(commit->title), line, 1);
5935                 view->line[view->lines - 1].dirty = 1;
5936         }
5938         return TRUE;
5941 static enum request
5942 main_request(struct view *view, enum request request, struct line *line)
5944         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5946         switch (request) {
5947         case REQ_ENTER:
5948                 if (view_is_displayed(view) && display[0] != view)
5949                         maximize_view(view);
5950                 open_view(view, REQ_VIEW_DIFF, flags);
5951                 break;
5952         case REQ_REFRESH:
5953                 load_refs();
5954                 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
5955                 break;
5956         default:
5957                 return request;
5958         }
5960         return REQ_NONE;
5963 static bool
5964 grep_refs(struct ref_list *list, regex_t *regex)
5966         regmatch_t pmatch;
5967         size_t i;
5969         if (!opt_show_refs || !list)
5970                 return FALSE;
5972         for (i = 0; i < list->size; i++) {
5973                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5974                         return TRUE;
5975         }
5977         return FALSE;
5980 static bool
5981 main_grep(struct view *view, struct line *line)
5983         struct commit *commit = line->data;
5984         const char *text[] = {
5985                 commit->title,
5986                 opt_author ? commit->author : "",
5987                 mkdate(&commit->time, opt_date),
5988                 NULL
5989         };
5991         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5994 static void
5995 main_select(struct view *view, struct line *line)
5997         struct commit *commit = line->data;
5999         string_copy_rev(view->ref, commit->id);
6000         string_copy_rev(ref_commit, view->ref);
6003 static struct view_ops main_ops = {
6004         "commit",
6005         main_open,
6006         main_read,
6007         main_draw,
6008         main_request,
6009         main_grep,
6010         main_select,
6011 };
6014 /*
6015  * Status management
6016  */
6018 /* Whether or not the curses interface has been initialized. */
6019 static bool cursed = FALSE;
6021 /* Terminal hacks and workarounds. */
6022 static bool use_scroll_redrawwin;
6023 static bool use_scroll_status_wclear;
6025 /* The status window is used for polling keystrokes. */
6026 static WINDOW *status_win;
6028 /* Reading from the prompt? */
6029 static bool input_mode = FALSE;
6031 static bool status_empty = FALSE;
6033 /* Update status and title window. */
6034 static void
6035 report(const char *msg, ...)
6037         struct view *view = display[current_view];
6039         if (input_mode)
6040                 return;
6042         if (!view) {
6043                 char buf[SIZEOF_STR];
6044                 va_list args;
6046                 va_start(args, msg);
6047                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6048                         buf[sizeof(buf) - 1] = 0;
6049                         buf[sizeof(buf) - 2] = '.';
6050                         buf[sizeof(buf) - 3] = '.';
6051                         buf[sizeof(buf) - 4] = '.';
6052                 }
6053                 va_end(args);
6054                 die("%s", buf);
6055         }
6057         if (!status_empty || *msg) {
6058                 va_list args;
6060                 va_start(args, msg);
6062                 wmove(status_win, 0, 0);
6063                 if (view->has_scrolled && use_scroll_status_wclear)
6064                         wclear(status_win);
6065                 if (*msg) {
6066                         vwprintw(status_win, msg, args);
6067                         status_empty = FALSE;
6068                 } else {
6069                         status_empty = TRUE;
6070                 }
6071                 wclrtoeol(status_win);
6072                 wnoutrefresh(status_win);
6074                 va_end(args);
6075         }
6077         update_view_title(view);
6080 static void
6081 init_display(void)
6083         const char *term;
6084         int x, y;
6086         /* Initialize the curses library */
6087         if (isatty(STDIN_FILENO)) {
6088                 cursed = !!initscr();
6089                 opt_tty = stdin;
6090         } else {
6091                 /* Leave stdin and stdout alone when acting as a pager. */
6092                 opt_tty = fopen("/dev/tty", "r+");
6093                 if (!opt_tty)
6094                         die("Failed to open /dev/tty");
6095                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6096         }
6098         if (!cursed)
6099                 die("Failed to initialize curses");
6101         nonl();         /* Disable conversion and detect newlines from input. */
6102         cbreak();       /* Take input chars one at a time, no wait for \n */
6103         noecho();       /* Don't echo input */
6104         leaveok(stdscr, FALSE);
6106         if (has_colors())
6107                 init_colors();
6109         getmaxyx(stdscr, y, x);
6110         status_win = newwin(1, x, y - 1, 0);
6111         if (!status_win)
6112                 die("Failed to create status window");
6114         /* Enable keyboard mapping */
6115         keypad(status_win, TRUE);
6116         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6118 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6119         set_tabsize(opt_tab_size);
6120 #else
6121         TABSIZE = opt_tab_size;
6122 #endif
6124         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6125         if (term && !strcmp(term, "gnome-terminal")) {
6126                 /* In the gnome-terminal-emulator, the message from
6127                  * scrolling up one line when impossible followed by
6128                  * scrolling down one line causes corruption of the
6129                  * status line. This is fixed by calling wclear. */
6130                 use_scroll_status_wclear = TRUE;
6131                 use_scroll_redrawwin = FALSE;
6133         } else if (term && !strcmp(term, "xrvt-xpm")) {
6134                 /* No problems with full optimizations in xrvt-(unicode)
6135                  * and aterm. */
6136                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6138         } else {
6139                 /* When scrolling in (u)xterm the last line in the
6140                  * scrolling direction will update slowly. */
6141                 use_scroll_redrawwin = TRUE;
6142                 use_scroll_status_wclear = FALSE;
6143         }
6146 static int
6147 get_input(int prompt_position)
6149         struct view *view;
6150         int i, key, cursor_y, cursor_x;
6152         if (prompt_position)
6153                 input_mode = TRUE;
6155         while (TRUE) {
6156                 bool loading = FALSE;
6158                 foreach_view (view, i) {
6159                         update_view(view);
6160                         if (view_is_displayed(view) && view->has_scrolled &&
6161                             use_scroll_redrawwin)
6162                                 redrawwin(view->win);
6163                         view->has_scrolled = FALSE;
6164                         if (view->pipe)
6165                                 loading = TRUE;
6166                 }
6168                 /* Update the cursor position. */
6169                 if (prompt_position) {
6170                         getbegyx(status_win, cursor_y, cursor_x);
6171                         cursor_x = prompt_position;
6172                 } else {
6173                         view = display[current_view];
6174                         getbegyx(view->win, cursor_y, cursor_x);
6175                         cursor_x = view->width - 1;
6176                         cursor_y += view->lineno - view->offset;
6177                 }
6178                 setsyx(cursor_y, cursor_x);
6180                 /* Refresh, accept single keystroke of input */
6181                 doupdate();
6182                 nodelay(status_win, loading);
6183                 key = wgetch(status_win);
6185                 /* wgetch() with nodelay() enabled returns ERR when
6186                  * there's no input. */
6187                 if (key == ERR) {
6189                 } else if (key == KEY_RESIZE) {
6190                         int height, width;
6192                         getmaxyx(stdscr, height, width);
6194                         wresize(status_win, 1, width);
6195                         mvwin(status_win, height - 1, 0);
6196                         wnoutrefresh(status_win);
6197                         resize_display();
6198                         redraw_display(TRUE);
6200                 } else {
6201                         input_mode = FALSE;
6202                         return key;
6203                 }
6204         }
6207 static char *
6208 prompt_input(const char *prompt, input_handler handler, void *data)
6210         enum input_status status = INPUT_OK;
6211         static char buf[SIZEOF_STR];
6212         size_t pos = 0;
6214         buf[pos] = 0;
6216         while (status == INPUT_OK || status == INPUT_SKIP) {
6217                 int key;
6219                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6220                 wclrtoeol(status_win);
6222                 key = get_input(pos + 1);
6223                 switch (key) {
6224                 case KEY_RETURN:
6225                 case KEY_ENTER:
6226                 case '\n':
6227                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6228                         break;
6230                 case KEY_BACKSPACE:
6231                         if (pos > 0)
6232                                 buf[--pos] = 0;
6233                         else
6234                                 status = INPUT_CANCEL;
6235                         break;
6237                 case KEY_ESC:
6238                         status = INPUT_CANCEL;
6239                         break;
6241                 default:
6242                         if (pos >= sizeof(buf)) {
6243                                 report("Input string too long");
6244                                 return NULL;
6245                         }
6247                         status = handler(data, buf, key);
6248                         if (status == INPUT_OK)
6249                                 buf[pos++] = (char) key;
6250                 }
6251         }
6253         /* Clear the status window */
6254         status_empty = FALSE;
6255         report("");
6257         if (status == INPUT_CANCEL)
6258                 return NULL;
6260         buf[pos++] = 0;
6262         return buf;
6265 static enum input_status
6266 prompt_yesno_handler(void *data, char *buf, int c)
6268         if (c == 'y' || c == 'Y')
6269                 return INPUT_STOP;
6270         if (c == 'n' || c == 'N')
6271                 return INPUT_CANCEL;
6272         return INPUT_SKIP;
6275 static bool
6276 prompt_yesno(const char *prompt)
6278         char prompt2[SIZEOF_STR];
6280         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6281                 return FALSE;
6283         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6286 static enum input_status
6287 read_prompt_handler(void *data, char *buf, int c)
6289         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6292 static char *
6293 read_prompt(const char *prompt)
6295         return prompt_input(prompt, read_prompt_handler, NULL);
6298 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6300         enum input_status status = INPUT_OK;
6301         int size = 0;
6303         while (items[size].text)
6304                 size++;
6306         while (status == INPUT_OK) {
6307                 const struct menu_item *item = &items[*selected];
6308                 int key;
6309                 int i;
6311                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6312                           prompt, *selected + 1, size);
6313                 if (item->hotkey)
6314                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6315                 wprintw(status_win, "%s", item->text);
6316                 wclrtoeol(status_win);
6318                 key = get_input(COLS - 1);
6319                 switch (key) {
6320                 case KEY_RETURN:
6321                 case KEY_ENTER:
6322                 case '\n':
6323                         status = INPUT_STOP;
6324                         break;
6326                 case KEY_LEFT:
6327                 case KEY_UP:
6328                         *selected = *selected - 1;
6329                         if (*selected < 0)
6330                                 *selected = size - 1;
6331                         break;
6333                 case KEY_RIGHT:
6334                 case KEY_DOWN:
6335                         *selected = (*selected + 1) % size;
6336                         break;
6338                 case KEY_ESC:
6339                         status = INPUT_CANCEL;
6340                         break;
6342                 default:
6343                         for (i = 0; items[i].text; i++)
6344                                 if (items[i].hotkey == key) {
6345                                         *selected = i;
6346                                         status = INPUT_STOP;
6347                                         break;
6348                                 }
6349                 }
6350         }
6352         /* Clear the status window */
6353         status_empty = FALSE;
6354         report("");
6356         return status != INPUT_CANCEL;
6359 /*
6360  * Repository properties
6361  */
6363 static struct ref **refs = NULL;
6364 static size_t refs_size = 0;
6365 static struct ref *refs_head = NULL;
6367 static struct ref_list **ref_lists = NULL;
6368 static size_t ref_lists_size = 0;
6370 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6371 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6372 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6374 static int
6375 compare_refs(const void *ref1_, const void *ref2_)
6377         const struct ref *ref1 = *(const struct ref **)ref1_;
6378         const struct ref *ref2 = *(const struct ref **)ref2_;
6380         if (ref1->tag != ref2->tag)
6381                 return ref2->tag - ref1->tag;
6382         if (ref1->ltag != ref2->ltag)
6383                 return ref2->ltag - ref2->ltag;
6384         if (ref1->head != ref2->head)
6385                 return ref2->head - ref1->head;
6386         if (ref1->tracked != ref2->tracked)
6387                 return ref2->tracked - ref1->tracked;
6388         if (ref1->remote != ref2->remote)
6389                 return ref2->remote - ref1->remote;
6390         return strcmp(ref1->name, ref2->name);
6393 static void
6394 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6396         size_t i;
6398         for (i = 0; i < refs_size; i++)
6399                 if (!visitor(data, refs[i]))
6400                         break;
6403 static struct ref *
6404 get_ref_head()
6406         return refs_head;
6409 static struct ref_list *
6410 get_ref_list(const char *id)
6412         struct ref_list *list;
6413         size_t i;
6415         for (i = 0; i < ref_lists_size; i++)
6416                 if (!strcmp(id, ref_lists[i]->id))
6417                         return ref_lists[i];
6419         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6420                 return NULL;
6421         list = calloc(1, sizeof(*list));
6422         if (!list)
6423                 return NULL;
6425         for (i = 0; i < refs_size; i++) {
6426                 if (!strcmp(id, refs[i]->id) &&
6427                     realloc_refs_list(&list->refs, list->size, 1))
6428                         list->refs[list->size++] = refs[i];
6429         }
6431         if (!list->refs) {
6432                 free(list);
6433                 return NULL;
6434         }
6436         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6437         ref_lists[ref_lists_size++] = list;
6438         return list;
6441 static int
6442 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6444         struct ref *ref = NULL;
6445         bool tag = FALSE;
6446         bool ltag = FALSE;
6447         bool remote = FALSE;
6448         bool tracked = FALSE;
6449         bool head = FALSE;
6450         int from = 0, to = refs_size - 1;
6452         if (!prefixcmp(name, "refs/tags/")) {
6453                 if (!suffixcmp(name, namelen, "^{}")) {
6454                         namelen -= 3;
6455                         name[namelen] = 0;
6456                 } else {
6457                         ltag = TRUE;
6458                 }
6460                 tag = TRUE;
6461                 namelen -= STRING_SIZE("refs/tags/");
6462                 name    += STRING_SIZE("refs/tags/");
6464         } else if (!prefixcmp(name, "refs/remotes/")) {
6465                 remote = TRUE;
6466                 namelen -= STRING_SIZE("refs/remotes/");
6467                 name    += STRING_SIZE("refs/remotes/");
6468                 tracked  = !strcmp(opt_remote, name);
6470         } else if (!prefixcmp(name, "refs/heads/")) {
6471                 namelen -= STRING_SIZE("refs/heads/");
6472                 name    += STRING_SIZE("refs/heads/");
6473                 if (!strncmp(opt_head, name, namelen))
6474                         return OK;
6476         } else if (!strcmp(name, "HEAD")) {
6477                 head     = TRUE;
6478                 if (*opt_head) {
6479                         namelen  = strlen(opt_head);
6480                         name     = opt_head;
6481                 }
6482         }
6484         /* If we are reloading or it's an annotated tag, replace the
6485          * previous SHA1 with the resolved commit id; relies on the fact
6486          * git-ls-remote lists the commit id of an annotated tag right
6487          * before the commit id it points to. */
6488         while (from <= to) {
6489                 size_t pos = (to + from) / 2;
6490                 int cmp = strcmp(name, refs[pos]->name);
6492                 if (!cmp) {
6493                         ref = refs[pos];
6494                         break;
6495                 }
6497                 if (cmp < 0)
6498                         to = pos - 1;
6499                 else
6500                         from = pos + 1;
6501         }
6503         if (!ref) {
6504                 if (!realloc_refs(&refs, refs_size, 1))
6505                         return ERR;
6506                 ref = calloc(1, sizeof(*ref) + namelen);
6507                 if (!ref)
6508                         return ERR;
6509                 memmove(refs + from + 1, refs + from,
6510                         (refs_size - from) * sizeof(*refs));
6511                 refs[from] = ref;
6512                 strncpy(ref->name, name, namelen);
6513                 refs_size++;
6514         }
6516         ref->head = head;
6517         ref->tag = tag;
6518         ref->ltag = ltag;
6519         ref->remote = remote;
6520         ref->tracked = tracked;
6521         string_copy_rev(ref->id, id);
6523         if (head)
6524                 refs_head = ref;
6525         return OK;
6528 static int
6529 load_refs(void)
6531         const char *head_argv[] = {
6532                 "git", "symbolic-ref", "HEAD", NULL
6533         };
6534         static const char *ls_remote_argv[SIZEOF_ARG] = {
6535                 "git", "ls-remote", opt_git_dir, NULL
6536         };
6537         static bool init = FALSE;
6538         size_t i;
6540         if (!init) {
6541                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6542                         die("TIG_LS_REMOTE contains too many arguments");
6543                 init = TRUE;
6544         }
6546         if (!*opt_git_dir)
6547                 return OK;
6549         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6550             !prefixcmp(opt_head, "refs/heads/")) {
6551                 char *offset = opt_head + STRING_SIZE("refs/heads/");
6553                 memmove(opt_head, offset, strlen(offset) + 1);
6554         }
6556         refs_head = NULL;
6557         for (i = 0; i < refs_size; i++)
6558                 refs[i]->id[0] = 0;
6560         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6561                 return ERR;
6563         /* Update the ref lists to reflect changes. */
6564         for (i = 0; i < ref_lists_size; i++) {
6565                 struct ref_list *list = ref_lists[i];
6566                 size_t old, new;
6568                 for (old = new = 0; old < list->size; old++)
6569                         if (!strcmp(list->id, list->refs[old]->id))
6570                                 list->refs[new++] = list->refs[old];
6571                 list->size = new;
6572         }
6574         return OK;
6577 static void
6578 set_remote_branch(const char *name, const char *value, size_t valuelen)
6580         if (!strcmp(name, ".remote")) {
6581                 string_ncopy(opt_remote, value, valuelen);
6583         } else if (*opt_remote && !strcmp(name, ".merge")) {
6584                 size_t from = strlen(opt_remote);
6586                 if (!prefixcmp(value, "refs/heads/"))
6587                         value += STRING_SIZE("refs/heads/");
6589                 if (!string_format_from(opt_remote, &from, "/%s", value))
6590                         opt_remote[0] = 0;
6591         }
6594 static void
6595 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6597         const char *argv[SIZEOF_ARG] = { name, "=" };
6598         int argc = 1 + (cmd == option_set_command);
6599         enum option_code error;
6601         if (!argv_from_string(argv, &argc, value))
6602                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6603         else
6604                 error = cmd(argc, argv);
6606         if (error != OPT_OK)
6607                 warn("Option 'tig.%s': %s", name, option_errors[error]);
6610 static bool
6611 set_environment_variable(const char *name, const char *value)
6613         size_t len = strlen(name) + 1 + strlen(value) + 1;
6614         char *env = malloc(len);
6616         if (env &&
6617             string_nformat(env, len, NULL, "%s=%s", name, value) &&
6618             putenv(env) == 0)
6619                 return TRUE;
6620         free(env);
6621         return FALSE;
6624 static void
6625 set_work_tree(const char *value)
6627         char cwd[SIZEOF_STR];
6629         if (!getcwd(cwd, sizeof(cwd)))
6630                 die("Failed to get cwd path: %s", strerror(errno));
6631         if (chdir(opt_git_dir) < 0)
6632                 die("Failed to chdir(%s): %s", strerror(errno));
6633         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6634                 die("Failed to get git path: %s", strerror(errno));
6635         if (chdir(cwd) < 0)
6636                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6637         if (chdir(value) < 0)
6638                 die("Failed to chdir(%s): %s", value, strerror(errno));
6639         if (!getcwd(cwd, sizeof(cwd)))
6640                 die("Failed to get cwd path: %s", strerror(errno));
6641         if (!set_environment_variable("GIT_WORK_TREE", cwd))
6642                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6643         if (!set_environment_variable("GIT_DIR", opt_git_dir))
6644                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6645         opt_is_inside_work_tree = TRUE;
6648 static int
6649 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6651         if (!strcmp(name, "i18n.commitencoding"))
6652                 string_ncopy(opt_encoding, value, valuelen);
6654         else if (!strcmp(name, "core.editor"))
6655                 string_ncopy(opt_editor, value, valuelen);
6657         else if (!strcmp(name, "core.worktree"))
6658                 set_work_tree(value);
6660         else if (!prefixcmp(name, "tig.color."))
6661                 set_repo_config_option(name + 10, value, option_color_command);
6663         else if (!prefixcmp(name, "tig.bind."))
6664                 set_repo_config_option(name + 9, value, option_bind_command);
6666         else if (!prefixcmp(name, "tig."))
6667                 set_repo_config_option(name + 4, value, option_set_command);
6669         else if (*opt_head && !prefixcmp(name, "branch.") &&
6670                  !strncmp(name + 7, opt_head, strlen(opt_head)))
6671                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6673         return OK;
6676 static int
6677 load_git_config(void)
6679         const char *config_list_argv[] = { "git", "config", "--list", NULL };
6681         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6684 static int
6685 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6687         if (!opt_git_dir[0]) {
6688                 string_ncopy(opt_git_dir, name, namelen);
6690         } else if (opt_is_inside_work_tree == -1) {
6691                 /* This can be 3 different values depending on the
6692                  * version of git being used. If git-rev-parse does not
6693                  * understand --is-inside-work-tree it will simply echo
6694                  * the option else either "true" or "false" is printed.
6695                  * Default to true for the unknown case. */
6696                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6698         } else if (*name == '.') {
6699                 string_ncopy(opt_cdup, name, namelen);
6701         } else {
6702                 string_ncopy(opt_prefix, name, namelen);
6703         }
6705         return OK;
6708 static int
6709 load_repo_info(void)
6711         const char *rev_parse_argv[] = {
6712                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6713                         "--show-cdup", "--show-prefix", NULL
6714         };
6716         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6720 /*
6721  * Main
6722  */
6724 static const char usage[] =
6725 "tig " TIG_VERSION " (" __DATE__ ")\n"
6726 "\n"
6727 "Usage: tig        [options] [revs] [--] [paths]\n"
6728 "   or: tig show   [options] [revs] [--] [paths]\n"
6729 "   or: tig blame  [options] [rev] [--] path\n"
6730 "   or: tig status\n"
6731 "   or: tig <      [git command output]\n"
6732 "\n"
6733 "Options:\n"
6734 "  -v, --version   Show version and exit\n"
6735 "  -h, --help      Show help message and exit";
6737 static void __NORETURN
6738 quit(int sig)
6740         /* XXX: Restore tty modes and let the OS cleanup the rest! */
6741         if (cursed)
6742                 endwin();
6743         exit(0);
6746 static void __NORETURN
6747 die(const char *err, ...)
6749         va_list args;
6751         endwin();
6753         va_start(args, err);
6754         fputs("tig: ", stderr);
6755         vfprintf(stderr, err, args);
6756         fputs("\n", stderr);
6757         va_end(args);
6759         exit(1);
6762 static void
6763 warn(const char *msg, ...)
6765         va_list args;
6767         va_start(args, msg);
6768         fputs("tig warning: ", stderr);
6769         vfprintf(stderr, msg, args);
6770         fputs("\n", stderr);
6771         va_end(args);
6774 static int
6775 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6777         const char ***filter_args = data;
6779         return argv_append(filter_args, name) ? OK : ERR;
6782 static void
6783 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6785         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6786         const char **all_argv = NULL;
6788         if (!argv_append_array(&all_argv, rev_parse_argv) ||
6789             !argv_append_array(&all_argv, argv) ||
6790             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6791                 die("Failed to split arguments");
6792         argv_free(all_argv);
6793         free(all_argv);
6796 static void
6797 filter_options(const char *argv[])
6799         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6800         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6801         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6804 static enum request
6805 parse_options(int argc, const char *argv[])
6807         enum request request = REQ_VIEW_MAIN;
6808         const char *subcommand;
6809         bool seen_dashdash = FALSE;
6810         const char **filter_argv = NULL;
6811         int i;
6813         if (!isatty(STDIN_FILENO))
6814                 return REQ_VIEW_PAGER;
6816         if (argc <= 1)
6817                 return REQ_VIEW_MAIN;
6819         subcommand = argv[1];
6820         if (!strcmp(subcommand, "status")) {
6821                 if (argc > 2)
6822                         warn("ignoring arguments after `%s'", subcommand);
6823                 return REQ_VIEW_STATUS;
6825         } else if (!strcmp(subcommand, "blame")) {
6826                 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6827                 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6828                 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6830                 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6831                         die("invalid number of options to blame\n\n%s", usage);
6833                 if (opt_rev_argv) {
6834                         string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6835                 }
6837                 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6838                 return REQ_VIEW_BLAME;
6840         } else if (!strcmp(subcommand, "show")) {
6841                 request = REQ_VIEW_DIFF;
6843         } else {
6844                 subcommand = NULL;
6845         }
6847         for (i = 1 + !!subcommand; i < argc; i++) {
6848                 const char *opt = argv[i];
6850                 if (seen_dashdash) {
6851                         argv_append(&opt_file_argv, opt);
6852                         continue;
6854                 } else if (!strcmp(opt, "--")) {
6855                         seen_dashdash = TRUE;
6856                         continue;
6858                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6859                         printf("tig version %s\n", TIG_VERSION);
6860                         quit(0);
6862                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6863                         printf("%s\n", usage);
6864                         quit(0);
6866                 } else if (!strcmp(opt, "--all")) {
6867                         argv_append(&opt_rev_argv, opt);
6868                         continue;
6869                 }
6871                 if (!argv_append(&filter_argv, opt))
6872                         die("command too long");
6873         }
6875         if (filter_argv)
6876                 filter_options(filter_argv);
6878         return request;
6881 int
6882 main(int argc, const char *argv[])
6884         const char *codeset = "UTF-8";
6885         enum request request = parse_options(argc, argv);
6886         struct view *view;
6888         signal(SIGINT, quit);
6889         signal(SIGPIPE, SIG_IGN);
6891         if (setlocale(LC_ALL, "")) {
6892                 codeset = nl_langinfo(CODESET);
6893         }
6895         if (load_repo_info() == ERR)
6896                 die("Failed to load repo info.");
6898         if (load_options() == ERR)
6899                 die("Failed to load user config.");
6901         if (load_git_config() == ERR)
6902                 die("Failed to load repo config.");
6904         /* Require a git repository unless when running in pager mode. */
6905         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6906                 die("Not a git repository");
6908         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6909                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6910                 if (opt_iconv_in == ICONV_NONE)
6911                         die("Failed to initialize character set conversion");
6912         }
6914         if (codeset && strcmp(codeset, "UTF-8")) {
6915                 opt_iconv_out = iconv_open(codeset, "UTF-8");
6916                 if (opt_iconv_out == ICONV_NONE)
6917                         die("Failed to initialize character set conversion");
6918         }
6920         if (load_refs() == ERR)
6921                 die("Failed to load refs.");
6923         init_display();
6925         while (view_driver(display[current_view], request)) {
6926                 int key = get_input(0);
6928                 view = display[current_view];
6929                 request = get_keybinding(view->keymap, key);
6931                 /* Some low-level request handling. This keeps access to
6932                  * status_win restricted. */
6933                 switch (request) {
6934                 case REQ_NONE:
6935                         report("Unknown key, press %s for help",
6936                                get_key(view->keymap, REQ_VIEW_HELP));
6937                         break;
6938                 case REQ_PROMPT:
6939                 {
6940                         char *cmd = read_prompt(":");
6942                         if (cmd && isdigit(*cmd)) {
6943                                 int lineno = view->lineno + 1;
6945                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6946                                         select_view_line(view, lineno - 1);
6947                                         report("");
6948                                 } else {
6949                                         report("Unable to parse '%s' as a line number", cmd);
6950                                 }
6952                         } else if (cmd) {
6953                                 struct view *next = VIEW(REQ_VIEW_PAGER);
6954                                 const char *argv[SIZEOF_ARG] = { "git" };
6955                                 int argc = 1;
6957                                 /* When running random commands, initially show the
6958                                  * command in the title. However, it maybe later be
6959                                  * overwritten if a commit line is selected. */
6960                                 string_ncopy(next->ref, cmd, strlen(cmd));
6962                                 if (!argv_from_string(argv, &argc, cmd)) {
6963                                         report("Too many arguments");
6964                                 } else if (!prepare_update(next, argv, NULL)) {
6965                                         report("Failed to format command");
6966                                 } else {
6967                                         open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
6968                                 }
6969                         }
6971                         request = REQ_NONE;
6972                         break;
6973                 }
6974                 case REQ_SEARCH:
6975                 case REQ_SEARCH_BACK:
6976                 {
6977                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
6978                         char *search = read_prompt(prompt);
6980                         if (search)
6981                                 string_ncopy(opt_search, search, strlen(search));
6982                         else if (*opt_search)
6983                                 request = request == REQ_SEARCH ?
6984                                         REQ_FIND_NEXT :
6985                                         REQ_FIND_PREV;
6986                         else
6987                                 request = REQ_NONE;
6988                         break;
6989                 }
6990                 default:
6991                         break;
6992                 }
6993         }
6995         quit(0);
6997         return 0;