Code

Move includes, macros and core utilities to tig.h
[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"
16 static void __NORETURN die(const char *err, ...);
17 static void warn(const char *msg, ...);
18 static void report(const char *msg, ...);
21 struct ref {
22         char id[SIZEOF_REV];    /* Commit SHA1 ID */
23         unsigned int head:1;    /* Is it the current HEAD? */
24         unsigned int tag:1;     /* Is it a tag? */
25         unsigned int ltag:1;    /* If so, is the tag local? */
26         unsigned int remote:1;  /* Is it a remote ref? */
27         unsigned int tracked:1; /* Is it the remote for the current HEAD? */
28         char name[1];           /* Ref name; tag or head names are shortened. */
29 };
31 struct ref_list {
32         char id[SIZEOF_REV];    /* Commit SHA1 ID */
33         size_t size;            /* Number of refs. */
34         struct ref **refs;      /* References for this ID. */
35 };
37 static struct ref *get_ref_head();
38 static struct ref_list *get_ref_list(const char *id);
39 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
40 static int load_refs(void);
42 enum input_status {
43         INPUT_OK,
44         INPUT_SKIP,
45         INPUT_STOP,
46         INPUT_CANCEL
47 };
49 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
51 static char *prompt_input(const char *prompt, input_handler handler, void *data);
52 static bool prompt_yesno(const char *prompt);
54 struct menu_item {
55         int hotkey;
56         const char *text;
57         void *data;
58 };
60 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
62 #define DATE_INFO \
63         DATE_(NO), \
64         DATE_(DEFAULT), \
65         DATE_(LOCAL), \
66         DATE_(RELATIVE), \
67         DATE_(SHORT)
69 enum date {
70 #define DATE_(name) DATE_##name
71         DATE_INFO
72 #undef  DATE_
73 };
75 static const struct enum_map date_map[] = {
76 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
77         DATE_INFO
78 #undef  DATE_
79 };
81 struct time {
82         time_t sec;
83         int tz;
84 };
86 static inline int timecmp(const struct time *t1, const struct time *t2)
87 {
88         return t1->sec - t2->sec;
89 }
91 static const char *
92 mkdate(const struct time *time, enum date date)
93 {
94         static char buf[DATE_COLS + 1];
95         static const struct enum_map reldate[] = {
96                 { "second", 1,                  60 * 2 },
97                 { "minute", 60,                 60 * 60 * 2 },
98                 { "hour",   60 * 60,            60 * 60 * 24 * 2 },
99                 { "day",    60 * 60 * 24,       60 * 60 * 24 * 7 * 2 },
100                 { "week",   60 * 60 * 24 * 7,   60 * 60 * 24 * 7 * 5 },
101                 { "month",  60 * 60 * 24 * 30,  60 * 60 * 24 * 30 * 12 },
102         };
103         struct tm tm;
105         if (!date || !time || !time->sec)
106                 return "";
108         if (date == DATE_RELATIVE) {
109                 struct timeval now;
110                 time_t date = time->sec + time->tz;
111                 time_t seconds;
112                 int i;
114                 gettimeofday(&now, NULL);
115                 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
116                 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
117                         if (seconds >= reldate[i].value)
118                                 continue;
120                         seconds /= reldate[i].namelen;
121                         if (!string_format(buf, "%ld %s%s %s",
122                                            seconds, reldate[i].name,
123                                            seconds > 1 ? "s" : "",
124                                            now.tv_sec >= date ? "ago" : "ahead"))
125                                 break;
126                         return buf;
127                 }
128         }
130         if (date == DATE_LOCAL) {
131                 time_t date = time->sec + time->tz;
132                 localtime_r(&date, &tm);
133         }
134         else {
135                 gmtime_r(&time->sec, &tm);
136         }
137         return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
141 #define AUTHOR_VALUES \
142         AUTHOR_(NO), \
143         AUTHOR_(FULL), \
144         AUTHOR_(ABBREVIATED)
146 enum author {
147 #define AUTHOR_(name) AUTHOR_##name
148         AUTHOR_VALUES,
149 #undef  AUTHOR_
150         AUTHOR_DEFAULT = AUTHOR_FULL
151 };
153 static const struct enum_map author_map[] = {
154 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
155         AUTHOR_VALUES
156 #undef  AUTHOR_
157 };
159 static const char *
160 get_author_initials(const char *author)
162         static char initials[AUTHOR_COLS * 6 + 1];
163         size_t pos = 0;
164         const char *end = strchr(author, '\0');
166 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
168         memset(initials, 0, sizeof(initials));
169         while (author < end) {
170                 unsigned char bytes;
171                 size_t i;
173                 while (is_initial_sep(*author))
174                         author++;
176                 bytes = utf8_char_length(author, end);
177                 if (bytes < sizeof(initials) - 1 - pos) {
178                         while (bytes--) {
179                                 initials[pos++] = *author++;
180                         }
181                 }
183                 for (i = pos; author < end && !is_initial_sep(*author); author++) {
184                         if (i < sizeof(initials) - 1)
185                                 initials[i++] = *author;
186                 }
188                 initials[i++] = 0;
189         }
191         return initials;
195 static bool
196 argv_from_string(const char *argv[SIZEOF_ARG], int *argc, char *cmd)
198         int valuelen;
200         while (*cmd && *argc < SIZEOF_ARG && (valuelen = strcspn(cmd, " \t"))) {
201                 bool advance = cmd[valuelen] != 0;
203                 cmd[valuelen] = 0;
204                 argv[(*argc)++] = chomp_string(cmd);
205                 cmd = chomp_string(cmd + valuelen + advance);
206         }
208         if (*argc < SIZEOF_ARG)
209                 argv[*argc] = NULL;
210         return *argc < SIZEOF_ARG;
213 static bool
214 argv_from_env(const char **argv, const char *name)
216         char *env = argv ? getenv(name) : NULL;
217         int argc = 0;
219         if (env && *env)
220                 env = strdup(env);
221         return !env || argv_from_string(argv, &argc, env);
224 static void
225 argv_free(const char *argv[])
227         int argc;
229         if (!argv)
230                 return;
231         for (argc = 0; argv[argc]; argc++)
232                 free((void *) argv[argc]);
233         argv[0] = NULL;
236 static size_t
237 argv_size(const char **argv)
239         int argc = 0;
241         while (argv && argv[argc])
242                 argc++;
244         return argc;
247 DEFINE_ALLOCATOR(argv_realloc, const char *, SIZEOF_ARG)
249 static bool
250 argv_append(const char ***argv, const char *arg)
252         size_t argc = argv_size(*argv);
254         if (!argv_realloc(argv, argc, 2))
255                 return FALSE;
257         (*argv)[argc++] = strdup(arg);
258         (*argv)[argc] = NULL;
259         return TRUE;
262 static bool
263 argv_append_array(const char ***dst_argv, const char *src_argv[])
265         int i;
267         for (i = 0; src_argv && src_argv[i]; i++)
268                 if (!argv_append(dst_argv, src_argv[i]))
269                         return FALSE;
270         return TRUE;
273 static bool
274 argv_copy(const char ***dst, const char *src[])
276         int argc;
278         for (argc = 0; src[argc]; argc++)
279                 if (!argv_append(dst, src[argc]))
280                         return FALSE;
281         return TRUE;
285 /*
286  * Executing external commands.
287  */
289 enum io_type {
290         IO_FD,                  /* File descriptor based IO. */
291         IO_BG,                  /* Execute command in the background. */
292         IO_FG,                  /* Execute command with same std{in,out,err}. */
293         IO_RD,                  /* Read only fork+exec IO. */
294         IO_WR,                  /* Write only fork+exec IO. */
295         IO_AP,                  /* Append fork+exec output to file. */
296 };
298 struct io {
299         int pipe;               /* Pipe end for reading or writing. */
300         pid_t pid;              /* PID of spawned process. */
301         int error;              /* Error status. */
302         char *buf;              /* Read buffer. */
303         size_t bufalloc;        /* Allocated buffer size. */
304         size_t bufsize;         /* Buffer content size. */
305         char *bufpos;           /* Current buffer position. */
306         unsigned int eof:1;     /* Has end of file been reached. */
307 };
309 static void
310 io_init(struct io *io)
312         memset(io, 0, sizeof(*io));
313         io->pipe = -1;
316 static bool
317 io_open(struct io *io, const char *fmt, ...)
319         char name[SIZEOF_STR] = "";
320         bool fits;
321         va_list args;
323         io_init(io);
325         va_start(args, fmt);
326         fits = vsnprintf(name, sizeof(name), fmt, args) < sizeof(name);
327         va_end(args);
329         if (!fits) {
330                 io->error = ENAMETOOLONG;
331                 return FALSE;
332         }
333         io->pipe = *name ? open(name, O_RDONLY) : STDIN_FILENO;
334         if (io->pipe == -1)
335                 io->error = errno;
336         return io->pipe != -1;
339 static bool
340 io_kill(struct io *io)
342         return io->pid == 0 || kill(io->pid, SIGKILL) != -1;
345 static bool
346 io_done(struct io *io)
348         pid_t pid = io->pid;
350         if (io->pipe != -1)
351                 close(io->pipe);
352         free(io->buf);
353         io_init(io);
355         while (pid > 0) {
356                 int status;
357                 pid_t waiting = waitpid(pid, &status, 0);
359                 if (waiting < 0) {
360                         if (errno == EINTR)
361                                 continue;
362                         io->error = errno;
363                         return FALSE;
364                 }
366                 return waiting == pid &&
367                        !WIFSIGNALED(status) &&
368                        WIFEXITED(status) &&
369                        !WEXITSTATUS(status);
370         }
372         return TRUE;
375 static bool
376 io_run(struct io *io, enum io_type type, const char *dir, const char *argv[], ...)
378         int pipefds[2] = { -1, -1 };
379         va_list args;
381         io_init(io);
383         if ((type == IO_RD || type == IO_WR) && pipe(pipefds) < 0) {
384                 io->error = errno;
385                 return FALSE;
386         } else if (type == IO_AP) {
387                 va_start(args, argv);
388                 pipefds[1] = va_arg(args, int);
389                 va_end(args);
390         }
392         if ((io->pid = fork())) {
393                 if (io->pid == -1)
394                         io->error = errno;
395                 if (pipefds[!(type == IO_WR)] != -1)
396                         close(pipefds[!(type == IO_WR)]);
397                 if (io->pid != -1) {
398                         io->pipe = pipefds[!!(type == IO_WR)];
399                         return TRUE;
400                 }
402         } else {
403                 if (type != IO_FG) {
404                         int devnull = open("/dev/null", O_RDWR);
405                         int readfd  = type == IO_WR ? pipefds[0] : devnull;
406                         int writefd = (type == IO_RD || type == IO_AP)
407                                                         ? pipefds[1] : devnull;
409                         dup2(readfd,  STDIN_FILENO);
410                         dup2(writefd, STDOUT_FILENO);
411                         dup2(devnull, STDERR_FILENO);
413                         close(devnull);
414                         if (pipefds[0] != -1)
415                                 close(pipefds[0]);
416                         if (pipefds[1] != -1)
417                                 close(pipefds[1]);
418                 }
420                 if (dir && *dir && chdir(dir) == -1)
421                         exit(errno);
423                 execvp(argv[0], (char *const*) argv);
424                 exit(errno);
425         }
427         if (pipefds[!!(type == IO_WR)] != -1)
428                 close(pipefds[!!(type == IO_WR)]);
429         return FALSE;
432 static bool
433 io_complete(enum io_type type, const char **argv, const char *dir, int fd)
435         struct io io;
437         return io_run(&io, type, dir, argv, fd) && io_done(&io);
440 static bool
441 io_run_bg(const char **argv)
443         return io_complete(IO_BG, argv, NULL, -1);
446 static bool
447 io_run_fg(const char **argv, const char *dir)
449         return io_complete(IO_FG, argv, dir, -1);
452 static bool
453 io_run_append(const char **argv, int fd)
455         return io_complete(IO_AP, argv, NULL, fd);
458 static bool
459 io_eof(struct io *io)
461         return io->eof;
464 static int
465 io_error(struct io *io)
467         return io->error;
470 static char *
471 io_strerror(struct io *io)
473         return strerror(io->error);
476 static bool
477 io_can_read(struct io *io)
479         struct timeval tv = { 0, 500 };
480         fd_set fds;
482         FD_ZERO(&fds);
483         FD_SET(io->pipe, &fds);
485         return select(io->pipe + 1, &fds, NULL, NULL, &tv) > 0;
488 static ssize_t
489 io_read(struct io *io, void *buf, size_t bufsize)
491         do {
492                 ssize_t readsize = read(io->pipe, buf, bufsize);
494                 if (readsize < 0 && (errno == EAGAIN || errno == EINTR))
495                         continue;
496                 else if (readsize == -1)
497                         io->error = errno;
498                 else if (readsize == 0)
499                         io->eof = 1;
500                 return readsize;
501         } while (1);
504 DEFINE_ALLOCATOR(io_realloc_buf, char, BUFSIZ)
506 static char *
507 io_get(struct io *io, int c, bool can_read)
509         char *eol;
510         ssize_t readsize;
512         while (TRUE) {
513                 if (io->bufsize > 0) {
514                         eol = memchr(io->bufpos, c, io->bufsize);
515                         if (eol) {
516                                 char *line = io->bufpos;
518                                 *eol = 0;
519                                 io->bufpos = eol + 1;
520                                 io->bufsize -= io->bufpos - line;
521                                 return line;
522                         }
523                 }
525                 if (io_eof(io)) {
526                         if (io->bufsize) {
527                                 io->bufpos[io->bufsize] = 0;
528                                 io->bufsize = 0;
529                                 return io->bufpos;
530                         }
531                         return NULL;
532                 }
534                 if (!can_read)
535                         return NULL;
537                 if (io->bufsize > 0 && io->bufpos > io->buf)
538                         memmove(io->buf, io->bufpos, io->bufsize);
540                 if (io->bufalloc == io->bufsize) {
541                         if (!io_realloc_buf(&io->buf, io->bufalloc, BUFSIZ))
542                                 return NULL;
543                         io->bufalloc += BUFSIZ;
544                 }
546                 io->bufpos = io->buf;
547                 readsize = io_read(io, io->buf + io->bufsize, io->bufalloc - io->bufsize);
548                 if (io_error(io))
549                         return NULL;
550                 io->bufsize += readsize;
551         }
554 static bool
555 io_write(struct io *io, const void *buf, size_t bufsize)
557         size_t written = 0;
559         while (!io_error(io) && written < bufsize) {
560                 ssize_t size;
562                 size = write(io->pipe, buf + written, bufsize - written);
563                 if (size < 0 && (errno == EAGAIN || errno == EINTR))
564                         continue;
565                 else if (size == -1)
566                         io->error = errno;
567                 else
568                         written += size;
569         }
571         return written == bufsize;
574 static bool
575 io_read_buf(struct io *io, char buf[], size_t bufsize)
577         char *result = io_get(io, '\n', TRUE);
579         if (result) {
580                 result = chomp_string(result);
581                 string_ncopy_do(buf, bufsize, result, strlen(result));
582         }
584         return io_done(io) && result;
587 static bool
588 io_run_buf(const char **argv, char buf[], size_t bufsize)
590         struct io io;
592         return io_run(&io, IO_RD, NULL, argv) && io_read_buf(&io, buf, bufsize);
595 typedef int (*io_read_fn)(char *, size_t, char *, size_t, void *data);
597 static int
598 io_load(struct io *io, const char *separators,
599         io_read_fn read_property, void *data)
601         char *name;
602         int state = OK;
604         while (state == OK && (name = io_get(io, '\n', TRUE))) {
605                 char *value;
606                 size_t namelen;
607                 size_t valuelen;
609                 name = chomp_string(name);
610                 namelen = strcspn(name, separators);
612                 if (name[namelen]) {
613                         name[namelen] = 0;
614                         value = chomp_string(name + namelen + 1);
615                         valuelen = strlen(value);
617                 } else {
618                         value = "";
619                         valuelen = 0;
620                 }
622                 state = read_property(name, namelen, value, valuelen, data);
623         }
625         if (state != ERR && io_error(io))
626                 state = ERR;
627         io_done(io);
629         return state;
632 static int
633 io_run_load(const char **argv, const char *separators,
634             io_read_fn read_property, void *data)
636         struct io io;
638         if (!io_run(&io, IO_RD, NULL, argv))
639                 return ERR;
640         return io_load(&io, separators, read_property, data);
644 /*
645  * User requests
646  */
648 #define REQ_INFO \
649         /* XXX: Keep the view request first and in sync with views[]. */ \
650         REQ_GROUP("View switching") \
651         REQ_(VIEW_MAIN,         "Show main view"), \
652         REQ_(VIEW_DIFF,         "Show diff view"), \
653         REQ_(VIEW_LOG,          "Show log view"), \
654         REQ_(VIEW_TREE,         "Show tree view"), \
655         REQ_(VIEW_BLOB,         "Show blob view"), \
656         REQ_(VIEW_BLAME,        "Show blame view"), \
657         REQ_(VIEW_BRANCH,       "Show branch view"), \
658         REQ_(VIEW_HELP,         "Show help page"), \
659         REQ_(VIEW_PAGER,        "Show pager view"), \
660         REQ_(VIEW_STATUS,       "Show status view"), \
661         REQ_(VIEW_STAGE,        "Show stage view"), \
662         \
663         REQ_GROUP("View manipulation") \
664         REQ_(ENTER,             "Enter current line and scroll"), \
665         REQ_(NEXT,              "Move to next"), \
666         REQ_(PREVIOUS,          "Move to previous"), \
667         REQ_(PARENT,            "Move to parent"), \
668         REQ_(VIEW_NEXT,         "Move focus to next view"), \
669         REQ_(REFRESH,           "Reload and refresh"), \
670         REQ_(MAXIMIZE,          "Maximize the current view"), \
671         REQ_(VIEW_CLOSE,        "Close the current view"), \
672         REQ_(QUIT,              "Close all views and quit"), \
673         \
674         REQ_GROUP("View specific requests") \
675         REQ_(STATUS_UPDATE,     "Update file status"), \
676         REQ_(STATUS_REVERT,     "Revert file changes"), \
677         REQ_(STATUS_MERGE,      "Merge file using external tool"), \
678         REQ_(STAGE_NEXT,        "Find next chunk to stage"), \
679         \
680         REQ_GROUP("Cursor navigation") \
681         REQ_(MOVE_UP,           "Move cursor one line up"), \
682         REQ_(MOVE_DOWN,         "Move cursor one line down"), \
683         REQ_(MOVE_PAGE_DOWN,    "Move cursor one page down"), \
684         REQ_(MOVE_PAGE_UP,      "Move cursor one page up"), \
685         REQ_(MOVE_FIRST_LINE,   "Move cursor to first line"), \
686         REQ_(MOVE_LAST_LINE,    "Move cursor to last line"), \
687         \
688         REQ_GROUP("Scrolling") \
689         REQ_(SCROLL_FIRST_COL,  "Scroll to the first line columns"), \
690         REQ_(SCROLL_LEFT,       "Scroll two columns left"), \
691         REQ_(SCROLL_RIGHT,      "Scroll two columns right"), \
692         REQ_(SCROLL_LINE_UP,    "Scroll one line up"), \
693         REQ_(SCROLL_LINE_DOWN,  "Scroll one line down"), \
694         REQ_(SCROLL_PAGE_UP,    "Scroll one page up"), \
695         REQ_(SCROLL_PAGE_DOWN,  "Scroll one page down"), \
696         \
697         REQ_GROUP("Searching") \
698         REQ_(SEARCH,            "Search the view"), \
699         REQ_(SEARCH_BACK,       "Search backwards in the view"), \
700         REQ_(FIND_NEXT,         "Find next search match"), \
701         REQ_(FIND_PREV,         "Find previous search match"), \
702         \
703         REQ_GROUP("Option manipulation") \
704         REQ_(OPTIONS,           "Open option menu"), \
705         REQ_(TOGGLE_LINENO,     "Toggle line numbers"), \
706         REQ_(TOGGLE_DATE,       "Toggle date display"), \
707         REQ_(TOGGLE_AUTHOR,     "Toggle author display"), \
708         REQ_(TOGGLE_REV_GRAPH,  "Toggle revision graph visualization"), \
709         REQ_(TOGGLE_REFS,       "Toggle reference display (tags/branches)"), \
710         REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
711         REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
712         \
713         REQ_GROUP("Misc") \
714         REQ_(PROMPT,            "Bring up the prompt"), \
715         REQ_(SCREEN_REDRAW,     "Redraw the screen"), \
716         REQ_(SHOW_VERSION,      "Show version information"), \
717         REQ_(STOP_LOADING,      "Stop all loading views"), \
718         REQ_(EDIT,              "Open in editor"), \
719         REQ_(NONE,              "Do nothing")
722 /* User action requests. */
723 enum request {
724 #define REQ_GROUP(help)
725 #define REQ_(req, help) REQ_##req
727         /* Offset all requests to avoid conflicts with ncurses getch values. */
728         REQ_UNKNOWN = KEY_MAX + 1,
729         REQ_OFFSET,
730         REQ_INFO
732 #undef  REQ_GROUP
733 #undef  REQ_
734 };
736 struct request_info {
737         enum request request;
738         const char *name;
739         int namelen;
740         const char *help;
741 };
743 static const struct request_info req_info[] = {
744 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
745 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
746         REQ_INFO
747 #undef  REQ_GROUP
748 #undef  REQ_
749 };
751 static enum request
752 get_request(const char *name)
754         int namelen = strlen(name);
755         int i;
757         for (i = 0; i < ARRAY_SIZE(req_info); i++)
758                 if (enum_equals(req_info[i], name, namelen))
759                         return req_info[i].request;
761         return REQ_UNKNOWN;
765 /*
766  * Options
767  */
769 /* Option and state variables. */
770 static enum date opt_date               = DATE_DEFAULT;
771 static enum author opt_author           = AUTHOR_DEFAULT;
772 static bool opt_line_number             = FALSE;
773 static bool opt_line_graphics           = TRUE;
774 static bool opt_rev_graph               = FALSE;
775 static bool opt_show_refs               = TRUE;
776 static bool opt_untracked_dirs_content  = TRUE;
777 static int opt_num_interval             = 5;
778 static double opt_hscroll               = 0.50;
779 static double opt_scale_split_view      = 2.0 / 3.0;
780 static int opt_tab_size                 = 8;
781 static int opt_author_cols              = AUTHOR_COLS;
782 static char opt_path[SIZEOF_STR]        = "";
783 static char opt_file[SIZEOF_STR]        = "";
784 static char opt_ref[SIZEOF_REF]         = "";
785 static char opt_head[SIZEOF_REF]        = "";
786 static char opt_remote[SIZEOF_REF]      = "";
787 static char opt_encoding[20]            = "UTF-8";
788 static iconv_t opt_iconv_in             = ICONV_NONE;
789 static iconv_t opt_iconv_out            = ICONV_NONE;
790 static char opt_search[SIZEOF_STR]      = "";
791 static char opt_cdup[SIZEOF_STR]        = "";
792 static char opt_prefix[SIZEOF_STR]      = "";
793 static char opt_git_dir[SIZEOF_STR]     = "";
794 static signed char opt_is_inside_work_tree      = -1; /* set to TRUE or FALSE */
795 static char opt_editor[SIZEOF_STR]      = "";
796 static FILE *opt_tty                    = NULL;
797 static const char **opt_diff_argv       = NULL;
798 static const char **opt_rev_argv        = NULL;
799 static const char **opt_file_argv       = NULL;
801 #define is_initial_commit()     (!get_ref_head())
802 #define is_head_commit(rev)     (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
805 /*
806  * Line-oriented content detection.
807  */
809 #define LINE_INFO \
810 LINE(DIFF_HEADER,  "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
811 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
812 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
813 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
814 LINE(DIFF_INDEX,        "index ",         COLOR_BLUE,   COLOR_DEFAULT,  0), \
815 LINE(DIFF_OLDMODE,      "old file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
816 LINE(DIFF_NEWMODE,      "new file mode ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
817 LINE(DIFF_COPY_FROM,    "copy from",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
818 LINE(DIFF_COPY_TO,      "copy to",        COLOR_YELLOW, COLOR_DEFAULT,  0), \
819 LINE(DIFF_RENAME_FROM,  "rename from",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
820 LINE(DIFF_RENAME_TO,    "rename to",      COLOR_YELLOW, COLOR_DEFAULT,  0), \
821 LINE(DIFF_SIMILARITY,   "similarity ",    COLOR_YELLOW, COLOR_DEFAULT,  0), \
822 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT,  0), \
823 LINE(DIFF_TREE,         "diff-tree ",     COLOR_BLUE,   COLOR_DEFAULT,  0), \
824 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
825 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
826 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
827 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
828 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
829 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
830 LINE(PP_REFS,      "Refs: ",            COLOR_RED,      COLOR_DEFAULT,  0), \
831 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
832 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
833 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
834 LINE(AUTHOR,       "author ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
835 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
836 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
837 LINE(ACKED,        "    Acked-by",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
838 LINE(TESTED,       "    Tested-by",     COLOR_YELLOW,   COLOR_DEFAULT,  0), \
839 LINE(REVIEWED,     "    Reviewed-by",   COLOR_YELLOW,   COLOR_DEFAULT,  0), \
840 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
841 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
842 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
843 LINE(DELIMITER,    "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
844 LINE(DATE,         "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
845 LINE(MODE,         "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
846 LINE(LINE_NUMBER,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
847 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
848 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
849 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
850 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
851 LINE(MAIN_LOCAL_TAG,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
852 LINE(MAIN_REMOTE,  "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
853 LINE(MAIN_TRACKED, "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_BOLD), \
854 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
855 LINE(MAIN_HEAD,    "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD), \
856 LINE(MAIN_REVGRAPH,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
857 LINE(TREE_HEAD,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_BOLD), \
858 LINE(TREE_DIR,     "",                  COLOR_YELLOW,   COLOR_DEFAULT,  A_NORMAL), \
859 LINE(TREE_FILE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
860 LINE(STAT_HEAD,    "",                  COLOR_YELLOW,   COLOR_DEFAULT,  0), \
861 LINE(STAT_SECTION, "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
862 LINE(STAT_NONE,    "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
863 LINE(STAT_STAGED,  "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
864 LINE(STAT_UNSTAGED,"",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
865 LINE(STAT_UNTRACKED,"",                 COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
866 LINE(HELP_KEYMAP,  "",                  COLOR_CYAN,     COLOR_DEFAULT,  0), \
867 LINE(HELP_GROUP,   "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
868 LINE(BLAME_ID,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0)
870 enum line_type {
871 #define LINE(type, line, fg, bg, attr) \
872         LINE_##type
873         LINE_INFO,
874         LINE_NONE
875 #undef  LINE
876 };
878 struct line_info {
879         const char *name;       /* Option name. */
880         int namelen;            /* Size of option name. */
881         const char *line;       /* The start of line to match. */
882         int linelen;            /* Size of string to match. */
883         int fg, bg, attr;       /* Color and text attributes for the lines. */
884 };
886 static struct line_info line_info[] = {
887 #define LINE(type, line, fg, bg, attr) \
888         { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
889         LINE_INFO
890 #undef  LINE
891 };
893 static enum line_type
894 get_line_type(const char *line)
896         int linelen = strlen(line);
897         enum line_type type;
899         for (type = 0; type < ARRAY_SIZE(line_info); type++)
900                 /* Case insensitive search matches Signed-off-by lines better. */
901                 if (linelen >= line_info[type].linelen &&
902                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
903                         return type;
905         return LINE_DEFAULT;
908 static inline int
909 get_line_attr(enum line_type type)
911         assert(type < ARRAY_SIZE(line_info));
912         return COLOR_PAIR(type) | line_info[type].attr;
915 static struct line_info *
916 get_line_info(const char *name)
918         size_t namelen = strlen(name);
919         enum line_type type;
921         for (type = 0; type < ARRAY_SIZE(line_info); type++)
922                 if (enum_equals(line_info[type], name, namelen))
923                         return &line_info[type];
925         return NULL;
928 static void
929 init_colors(void)
931         int default_bg = line_info[LINE_DEFAULT].bg;
932         int default_fg = line_info[LINE_DEFAULT].fg;
933         enum line_type type;
935         start_color();
937         if (assume_default_colors(default_fg, default_bg) == ERR) {
938                 default_bg = COLOR_BLACK;
939                 default_fg = COLOR_WHITE;
940         }
942         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
943                 struct line_info *info = &line_info[type];
944                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
945                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
947                 init_pair(type, fg, bg);
948         }
951 struct line {
952         enum line_type type;
954         /* State flags */
955         unsigned int selected:1;
956         unsigned int dirty:1;
957         unsigned int cleareol:1;
958         unsigned int other:16;
960         void *data;             /* User data */
961 };
964 /*
965  * Keys
966  */
968 struct keybinding {
969         int alias;
970         enum request request;
971 };
973 static struct keybinding default_keybindings[] = {
974         /* View switching */
975         { 'm',          REQ_VIEW_MAIN },
976         { 'd',          REQ_VIEW_DIFF },
977         { 'l',          REQ_VIEW_LOG },
978         { 't',          REQ_VIEW_TREE },
979         { 'f',          REQ_VIEW_BLOB },
980         { 'B',          REQ_VIEW_BLAME },
981         { 'H',          REQ_VIEW_BRANCH },
982         { 'p',          REQ_VIEW_PAGER },
983         { 'h',          REQ_VIEW_HELP },
984         { 'S',          REQ_VIEW_STATUS },
985         { 'c',          REQ_VIEW_STAGE },
987         /* View manipulation */
988         { 'q',          REQ_VIEW_CLOSE },
989         { KEY_TAB,      REQ_VIEW_NEXT },
990         { KEY_RETURN,   REQ_ENTER },
991         { KEY_UP,       REQ_PREVIOUS },
992         { KEY_CTL('P'), REQ_PREVIOUS },
993         { KEY_DOWN,     REQ_NEXT },
994         { KEY_CTL('N'), REQ_NEXT },
995         { 'R',          REQ_REFRESH },
996         { KEY_F(5),     REQ_REFRESH },
997         { 'O',          REQ_MAXIMIZE },
999         /* Cursor navigation */
1000         { 'k',          REQ_MOVE_UP },
1001         { 'j',          REQ_MOVE_DOWN },
1002         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
1003         { KEY_END,      REQ_MOVE_LAST_LINE },
1004         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
1005         { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
1006         { ' ',          REQ_MOVE_PAGE_DOWN },
1007         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
1008         { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
1009         { 'b',          REQ_MOVE_PAGE_UP },
1010         { '-',          REQ_MOVE_PAGE_UP },
1012         /* Scrolling */
1013         { '|',          REQ_SCROLL_FIRST_COL },
1014         { KEY_LEFT,     REQ_SCROLL_LEFT },
1015         { KEY_RIGHT,    REQ_SCROLL_RIGHT },
1016         { KEY_IC,       REQ_SCROLL_LINE_UP },
1017         { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
1018         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
1019         { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
1020         { 'w',          REQ_SCROLL_PAGE_UP },
1021         { 's',          REQ_SCROLL_PAGE_DOWN },
1023         /* Searching */
1024         { '/',          REQ_SEARCH },
1025         { '?',          REQ_SEARCH_BACK },
1026         { 'n',          REQ_FIND_NEXT },
1027         { 'N',          REQ_FIND_PREV },
1029         /* Misc */
1030         { 'Q',          REQ_QUIT },
1031         { 'z',          REQ_STOP_LOADING },
1032         { 'v',          REQ_SHOW_VERSION },
1033         { 'r',          REQ_SCREEN_REDRAW },
1034         { KEY_CTL('L'), REQ_SCREEN_REDRAW },
1035         { 'o',          REQ_OPTIONS },
1036         { '.',          REQ_TOGGLE_LINENO },
1037         { 'D',          REQ_TOGGLE_DATE },
1038         { 'A',          REQ_TOGGLE_AUTHOR },
1039         { 'g',          REQ_TOGGLE_REV_GRAPH },
1040         { 'F',          REQ_TOGGLE_REFS },
1041         { 'I',          REQ_TOGGLE_SORT_ORDER },
1042         { 'i',          REQ_TOGGLE_SORT_FIELD },
1043         { ':',          REQ_PROMPT },
1044         { 'u',          REQ_STATUS_UPDATE },
1045         { '!',          REQ_STATUS_REVERT },
1046         { 'M',          REQ_STATUS_MERGE },
1047         { '@',          REQ_STAGE_NEXT },
1048         { ',',          REQ_PARENT },
1049         { 'e',          REQ_EDIT },
1050 };
1052 #define KEYMAP_INFO \
1053         KEYMAP_(GENERIC), \
1054         KEYMAP_(MAIN), \
1055         KEYMAP_(DIFF), \
1056         KEYMAP_(LOG), \
1057         KEYMAP_(TREE), \
1058         KEYMAP_(BLOB), \
1059         KEYMAP_(BLAME), \
1060         KEYMAP_(BRANCH), \
1061         KEYMAP_(PAGER), \
1062         KEYMAP_(HELP), \
1063         KEYMAP_(STATUS), \
1064         KEYMAP_(STAGE)
1066 enum keymap {
1067 #define KEYMAP_(name) KEYMAP_##name
1068         KEYMAP_INFO
1069 #undef  KEYMAP_
1070 };
1072 static const struct enum_map keymap_table[] = {
1073 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
1074         KEYMAP_INFO
1075 #undef  KEYMAP_
1076 };
1078 #define set_keymap(map, name) map_enum(map, keymap_table, name)
1080 struct keybinding_table {
1081         struct keybinding *data;
1082         size_t size;
1083 };
1085 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
1087 static void
1088 add_keybinding(enum keymap keymap, enum request request, int key)
1090         struct keybinding_table *table = &keybindings[keymap];
1091         size_t i;
1093         for (i = 0; i < keybindings[keymap].size; i++) {
1094                 if (keybindings[keymap].data[i].alias == key) {
1095                         keybindings[keymap].data[i].request = request;
1096                         return;
1097                 }
1098         }
1100         table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1101         if (!table->data)
1102                 die("Failed to allocate keybinding");
1103         table->data[table->size].alias = key;
1104         table->data[table->size++].request = request;
1106         if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
1107                 int i;
1109                 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1110                         if (default_keybindings[i].alias == key)
1111                                 default_keybindings[i].request = REQ_NONE;
1112         }
1115 /* Looks for a key binding first in the given map, then in the generic map, and
1116  * lastly in the default keybindings. */
1117 static enum request
1118 get_keybinding(enum keymap keymap, int key)
1120         size_t i;
1122         for (i = 0; i < keybindings[keymap].size; i++)
1123                 if (keybindings[keymap].data[i].alias == key)
1124                         return keybindings[keymap].data[i].request;
1126         for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
1127                 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
1128                         return keybindings[KEYMAP_GENERIC].data[i].request;
1130         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1131                 if (default_keybindings[i].alias == key)
1132                         return default_keybindings[i].request;
1134         return (enum request) key;
1138 struct key {
1139         const char *name;
1140         int value;
1141 };
1143 static const struct key key_table[] = {
1144         { "Enter",      KEY_RETURN },
1145         { "Space",      ' ' },
1146         { "Backspace",  KEY_BACKSPACE },
1147         { "Tab",        KEY_TAB },
1148         { "Escape",     KEY_ESC },
1149         { "Left",       KEY_LEFT },
1150         { "Right",      KEY_RIGHT },
1151         { "Up",         KEY_UP },
1152         { "Down",       KEY_DOWN },
1153         { "Insert",     KEY_IC },
1154         { "Delete",     KEY_DC },
1155         { "Hash",       '#' },
1156         { "Home",       KEY_HOME },
1157         { "End",        KEY_END },
1158         { "PageUp",     KEY_PPAGE },
1159         { "PageDown",   KEY_NPAGE },
1160         { "F1",         KEY_F(1) },
1161         { "F2",         KEY_F(2) },
1162         { "F3",         KEY_F(3) },
1163         { "F4",         KEY_F(4) },
1164         { "F5",         KEY_F(5) },
1165         { "F6",         KEY_F(6) },
1166         { "F7",         KEY_F(7) },
1167         { "F8",         KEY_F(8) },
1168         { "F9",         KEY_F(9) },
1169         { "F10",        KEY_F(10) },
1170         { "F11",        KEY_F(11) },
1171         { "F12",        KEY_F(12) },
1172 };
1174 static int
1175 get_key_value(const char *name)
1177         int i;
1179         for (i = 0; i < ARRAY_SIZE(key_table); i++)
1180                 if (!strcasecmp(key_table[i].name, name))
1181                         return key_table[i].value;
1183         if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1184                 return (int)name[1] & 0x1f;
1185         if (strlen(name) == 1 && isprint(*name))
1186                 return (int) *name;
1187         return ERR;
1190 static const char *
1191 get_key_name(int key_value)
1193         static char key_char[] = "'X'\0";
1194         const char *seq = NULL;
1195         int key;
1197         for (key = 0; key < ARRAY_SIZE(key_table); key++)
1198                 if (key_table[key].value == key_value)
1199                         seq = key_table[key].name;
1201         if (seq == NULL && key_value < 0x7f) {
1202                 char *s = key_char + 1;
1204                 if (key_value >= 0x20) {
1205                         *s++ = key_value;
1206                 } else {
1207                         *s++ = '^';
1208                         *s++ = 0x40 | (key_value & 0x1f);
1209                 }
1210                 *s++ = '\'';
1211                 *s++ = '\0';
1212                 seq = key_char;
1213         }
1215         return seq ? seq : "(no key)";
1218 static bool
1219 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1221         const char *sep = *pos > 0 ? ", " : "";
1222         const char *keyname = get_key_name(keybinding->alias);
1224         return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1227 static bool
1228 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1229                            enum keymap keymap, bool all)
1231         int i;
1233         for (i = 0; i < keybindings[keymap].size; i++) {
1234                 if (keybindings[keymap].data[i].request == request) {
1235                         if (!append_key(buf, pos, &keybindings[keymap].data[i]))
1236                                 return FALSE;
1237                         if (!all)
1238                                 break;
1239                 }
1240         }
1242         return TRUE;
1245 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
1247 static const char *
1248 get_keys(enum keymap keymap, enum request request, bool all)
1250         static char buf[BUFSIZ];
1251         size_t pos = 0;
1252         int i;
1254         buf[pos] = 0;
1256         if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1257                 return "Too many keybindings!";
1258         if (pos > 0 && !all)
1259                 return buf;
1261         if (keymap != KEYMAP_GENERIC) {
1262                 /* Only the generic keymap includes the default keybindings when
1263                  * listing all keys. */
1264                 if (all)
1265                         return buf;
1267                 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
1268                         return "Too many keybindings!";
1269                 if (pos)
1270                         return buf;
1271         }
1273         for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1274                 if (default_keybindings[i].request == request) {
1275                         if (!append_key(buf, &pos, &default_keybindings[i]))
1276                                 return "Too many keybindings!";
1277                         if (!all)
1278                                 return buf;
1279                 }
1280         }
1282         return buf;
1285 struct run_request {
1286         enum keymap keymap;
1287         int key;
1288         const char **argv;
1289 };
1291 static struct run_request *run_request;
1292 static size_t run_requests;
1294 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1296 static enum request
1297 add_run_request(enum keymap keymap, int key, const char **argv)
1299         struct run_request *req;
1301         if (!realloc_run_requests(&run_request, run_requests, 1))
1302                 return REQ_NONE;
1304         req = &run_request[run_requests];
1305         req->keymap = keymap;
1306         req->key = key;
1307         req->argv = NULL;
1309         if (!argv_copy(&req->argv, argv))
1310                 return REQ_NONE;
1312         return REQ_NONE + ++run_requests;
1315 static struct run_request *
1316 get_run_request(enum request request)
1318         if (request <= REQ_NONE)
1319                 return NULL;
1320         return &run_request[request - REQ_NONE - 1];
1323 static void
1324 add_builtin_run_requests(void)
1326         const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1327         const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1328         const char *commit[] = { "git", "commit", NULL };
1329         const char *gc[] = { "git", "gc", NULL };
1330         struct run_request reqs[] = {
1331                 { KEYMAP_MAIN,    'C', cherry_pick },
1332                 { KEYMAP_STATUS,  'C', commit },
1333                 { KEYMAP_BRANCH,  'C', checkout },
1334                 { KEYMAP_GENERIC, 'G', gc },
1335         };
1336         int i;
1338         for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1339                 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1341                 if (req != reqs[i].key)
1342                         continue;
1343                 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1344                 if (req != REQ_NONE)
1345                         add_keybinding(reqs[i].keymap, req, reqs[i].key);
1346         }
1349 /*
1350  * User config file handling.
1351  */
1353 #define OPT_ERR_INFO \
1354         OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1355         OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1356         OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1357         OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1358         OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1359         OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1360         OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1361         OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1362         OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1363         OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1364         OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1365         OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1366         OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1367         OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1368         OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1369         OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1371 enum option_code {
1372 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1373         OPT_ERR_INFO
1374 #undef  OPT_ERR_
1375         OPT_OK
1376 };
1378 static const char *option_errors[] = {
1379 #define OPT_ERR_(name, msg) msg
1380         OPT_ERR_INFO
1381 #undef  OPT_ERR_
1382 };
1384 static const struct enum_map color_map[] = {
1385 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1386         COLOR_MAP(DEFAULT),
1387         COLOR_MAP(BLACK),
1388         COLOR_MAP(BLUE),
1389         COLOR_MAP(CYAN),
1390         COLOR_MAP(GREEN),
1391         COLOR_MAP(MAGENTA),
1392         COLOR_MAP(RED),
1393         COLOR_MAP(WHITE),
1394         COLOR_MAP(YELLOW),
1395 };
1397 static const struct enum_map attr_map[] = {
1398 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1399         ATTR_MAP(NORMAL),
1400         ATTR_MAP(BLINK),
1401         ATTR_MAP(BOLD),
1402         ATTR_MAP(DIM),
1403         ATTR_MAP(REVERSE),
1404         ATTR_MAP(STANDOUT),
1405         ATTR_MAP(UNDERLINE),
1406 };
1408 #define set_attribute(attr, name)       map_enum(attr, attr_map, name)
1410 static enum option_code
1411 parse_step(double *opt, const char *arg)
1413         *opt = atoi(arg);
1414         if (!strchr(arg, '%'))
1415                 return OPT_OK;
1417         /* "Shift down" so 100% and 1 does not conflict. */
1418         *opt = (*opt - 1) / 100;
1419         if (*opt >= 1.0) {
1420                 *opt = 0.99;
1421                 return OPT_ERR_INVALID_STEP_VALUE;
1422         }
1423         if (*opt < 0.0) {
1424                 *opt = 1;
1425                 return OPT_ERR_INVALID_STEP_VALUE;
1426         }
1427         return OPT_OK;
1430 static enum option_code
1431 parse_int(int *opt, const char *arg, int min, int max)
1433         int value = atoi(arg);
1435         if (min <= value && value <= max) {
1436                 *opt = value;
1437                 return OPT_OK;
1438         }
1440         return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1443 static bool
1444 set_color(int *color, const char *name)
1446         if (map_enum(color, color_map, name))
1447                 return TRUE;
1448         if (!prefixcmp(name, "color"))
1449                 return parse_int(color, name + 5, 0, 255) == OK;
1450         return FALSE;
1453 /* Wants: object fgcolor bgcolor [attribute] */
1454 static enum option_code
1455 option_color_command(int argc, const char *argv[])
1457         struct line_info *info;
1459         if (argc < 3)
1460                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1462         info = get_line_info(argv[0]);
1463         if (!info) {
1464                 static const struct enum_map obsolete[] = {
1465                         ENUM_MAP("main-delim",  LINE_DELIMITER),
1466                         ENUM_MAP("main-date",   LINE_DATE),
1467                         ENUM_MAP("main-author", LINE_AUTHOR),
1468                 };
1469                 int index;
1471                 if (!map_enum(&index, obsolete, argv[0]))
1472                         return OPT_ERR_UNKNOWN_COLOR_NAME;
1473                 info = &line_info[index];
1474         }
1476         if (!set_color(&info->fg, argv[1]) ||
1477             !set_color(&info->bg, argv[2]))
1478                 return OPT_ERR_UNKNOWN_COLOR;
1480         info->attr = 0;
1481         while (argc-- > 3) {
1482                 int attr;
1484                 if (!set_attribute(&attr, argv[argc]))
1485                         return OPT_ERR_UNKNOWN_ATTRIBUTE;
1486                 info->attr |= attr;
1487         }
1489         return OPT_OK;
1492 static enum option_code
1493 parse_bool(bool *opt, const char *arg)
1495         *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1496                 ? TRUE : FALSE;
1497         return OPT_OK;
1500 static enum option_code
1501 parse_enum_do(unsigned int *opt, const char *arg,
1502               const struct enum_map *map, size_t map_size)
1504         bool is_true;
1506         assert(map_size > 1);
1508         if (map_enum_do(map, map_size, (int *) opt, arg))
1509                 return OPT_OK;
1511         parse_bool(&is_true, arg);
1512         *opt = is_true ? map[1].value : map[0].value;
1513         return OPT_OK;
1516 #define parse_enum(opt, arg, map) \
1517         parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1519 static enum option_code
1520 parse_string(char *opt, const char *arg, size_t optsize)
1522         int arglen = strlen(arg);
1524         switch (arg[0]) {
1525         case '\"':
1526         case '\'':
1527                 if (arglen == 1 || arg[arglen - 1] != arg[0])
1528                         return OPT_ERR_UNMATCHED_QUOTATION;
1529                 arg += 1; arglen -= 2;
1530         default:
1531                 string_ncopy_do(opt, optsize, arg, arglen);
1532                 return OPT_OK;
1533         }
1536 /* Wants: name = value */
1537 static enum option_code
1538 option_set_command(int argc, const char *argv[])
1540         if (argc != 3)
1541                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1543         if (strcmp(argv[1], "="))
1544                 return OPT_ERR_NO_VALUE_ASSIGNED;
1546         if (!strcmp(argv[0], "show-author"))
1547                 return parse_enum(&opt_author, argv[2], author_map);
1549         if (!strcmp(argv[0], "show-date"))
1550                 return parse_enum(&opt_date, argv[2], date_map);
1552         if (!strcmp(argv[0], "show-rev-graph"))
1553                 return parse_bool(&opt_rev_graph, argv[2]);
1555         if (!strcmp(argv[0], "show-refs"))
1556                 return parse_bool(&opt_show_refs, argv[2]);
1558         if (!strcmp(argv[0], "show-line-numbers"))
1559                 return parse_bool(&opt_line_number, argv[2]);
1561         if (!strcmp(argv[0], "line-graphics"))
1562                 return parse_bool(&opt_line_graphics, argv[2]);
1564         if (!strcmp(argv[0], "line-number-interval"))
1565                 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1567         if (!strcmp(argv[0], "author-width"))
1568                 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1570         if (!strcmp(argv[0], "horizontal-scroll"))
1571                 return parse_step(&opt_hscroll, argv[2]);
1573         if (!strcmp(argv[0], "split-view-height"))
1574                 return parse_step(&opt_scale_split_view, argv[2]);
1576         if (!strcmp(argv[0], "tab-size"))
1577                 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1579         if (!strcmp(argv[0], "commit-encoding"))
1580                 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1582         if (!strcmp(argv[0], "status-untracked-dirs"))
1583                 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1585         return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1588 /* Wants: mode request key */
1589 static enum option_code
1590 option_bind_command(int argc, const char *argv[])
1592         enum request request;
1593         int keymap = -1;
1594         int key;
1596         if (argc < 3)
1597                 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1599         if (!set_keymap(&keymap, argv[0]))
1600                 return OPT_ERR_UNKNOWN_KEY_MAP;
1602         key = get_key_value(argv[1]);
1603         if (key == ERR)
1604                 return OPT_ERR_UNKNOWN_KEY;
1606         request = get_request(argv[2]);
1607         if (request == REQ_UNKNOWN) {
1608                 static const struct enum_map obsolete[] = {
1609                         ENUM_MAP("cherry-pick",         REQ_NONE),
1610                         ENUM_MAP("screen-resize",       REQ_NONE),
1611                         ENUM_MAP("tree-parent",         REQ_PARENT),
1612                 };
1613                 int alias;
1615                 if (map_enum(&alias, obsolete, argv[2])) {
1616                         if (alias != REQ_NONE)
1617                                 add_keybinding(keymap, alias, key);
1618                         return OPT_ERR_OBSOLETE_REQUEST_NAME;
1619                 }
1620         }
1621         if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1622                 request = add_run_request(keymap, key, argv + 2);
1623         if (request == REQ_UNKNOWN)
1624                 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1626         add_keybinding(keymap, request, key);
1628         return OPT_OK;
1631 static enum option_code
1632 set_option(const char *opt, char *value)
1634         const char *argv[SIZEOF_ARG];
1635         int argc = 0;
1637         if (!argv_from_string(argv, &argc, value))
1638                 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1640         if (!strcmp(opt, "color"))
1641                 return option_color_command(argc, argv);
1643         if (!strcmp(opt, "set"))
1644                 return option_set_command(argc, argv);
1646         if (!strcmp(opt, "bind"))
1647                 return option_bind_command(argc, argv);
1649         return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1652 struct config_state {
1653         int lineno;
1654         bool errors;
1655 };
1657 static int
1658 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1660         struct config_state *config = data;
1661         enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1663         config->lineno++;
1665         /* Check for comment markers, since read_properties() will
1666          * only ensure opt and value are split at first " \t". */
1667         optlen = strcspn(opt, "#");
1668         if (optlen == 0)
1669                 return OK;
1671         if (opt[optlen] == 0) {
1672                 /* Look for comment endings in the value. */
1673                 size_t len = strcspn(value, "#");
1675                 if (len < valuelen) {
1676                         valuelen = len;
1677                         value[valuelen] = 0;
1678                 }
1680                 status = set_option(opt, value);
1681         }
1683         if (status != OPT_OK) {
1684                 warn("Error on line %d, near '%.*s': %s",
1685                      config->lineno, (int) optlen, opt, option_errors[status]);
1686                 config->errors = TRUE;
1687         }
1689         /* Always keep going if errors are encountered. */
1690         return OK;
1693 static void
1694 load_option_file(const char *path)
1696         struct config_state config = { 0, FALSE };
1697         struct io io;
1699         /* It's OK that the file doesn't exist. */
1700         if (!io_open(&io, "%s", path))
1701                 return;
1703         if (io_load(&io, " \t", read_option, &config) == ERR ||
1704             config.errors == TRUE)
1705                 warn("Errors while loading %s.", path);
1708 static int
1709 load_options(void)
1711         const char *home = getenv("HOME");
1712         const char *tigrc_user = getenv("TIGRC_USER");
1713         const char *tigrc_system = getenv("TIGRC_SYSTEM");
1714         const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1715         char buf[SIZEOF_STR];
1717         if (!tigrc_system)
1718                 tigrc_system = SYSCONFDIR "/tigrc";
1719         load_option_file(tigrc_system);
1721         if (!tigrc_user) {
1722                 if (!home || !string_format(buf, "%s/.tigrc", home))
1723                         return ERR;
1724                 tigrc_user = buf;
1725         }
1726         load_option_file(tigrc_user);
1728         /* Add _after_ loading config files to avoid adding run requests
1729          * that conflict with keybindings. */
1730         add_builtin_run_requests();
1732         if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1733                 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1734                 int argc = 0;
1736                 if (!string_format(buf, "%s", tig_diff_opts) ||
1737                     !argv_from_string(diff_opts, &argc, buf))
1738                         die("TIG_DIFF_OPTS contains too many arguments");
1739                 else if (!argv_copy(&opt_diff_argv, diff_opts))
1740                         die("Failed to format TIG_DIFF_OPTS arguments");
1741         }
1743         return OK;
1747 /*
1748  * The viewer
1749  */
1751 struct view;
1752 struct view_ops;
1754 /* The display array of active views and the index of the current view. */
1755 static struct view *display[2];
1756 static WINDOW *display_win[2];
1757 static WINDOW *display_title[2];
1758 static unsigned int current_view;
1760 #define foreach_displayed_view(view, i) \
1761         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1763 #define displayed_views()       (display[1] != NULL ? 2 : 1)
1765 /* Current head and commit ID */
1766 static char ref_blob[SIZEOF_REF]        = "";
1767 static char ref_commit[SIZEOF_REF]      = "HEAD";
1768 static char ref_head[SIZEOF_REF]        = "HEAD";
1769 static char ref_branch[SIZEOF_REF]      = "";
1771 enum view_type {
1772         VIEW_MAIN,
1773         VIEW_DIFF,
1774         VIEW_LOG,
1775         VIEW_TREE,
1776         VIEW_BLOB,
1777         VIEW_BLAME,
1778         VIEW_BRANCH,
1779         VIEW_HELP,
1780         VIEW_PAGER,
1781         VIEW_STATUS,
1782         VIEW_STAGE,
1783 };
1785 struct view {
1786         enum view_type type;    /* View type */
1787         const char *name;       /* View name */
1788         const char *cmd_env;    /* Command line set via environment */
1789         const char *id;         /* Points to either of ref_{head,commit,blob} */
1791         struct view_ops *ops;   /* View operations */
1793         enum keymap keymap;     /* What keymap does this view have */
1794         bool git_dir;           /* Whether the view requires a git directory. */
1796         char ref[SIZEOF_REF];   /* Hovered commit reference */
1797         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
1799         int height, width;      /* The width and height of the main window */
1800         WINDOW *win;            /* The main window */
1802         /* Navigation */
1803         unsigned long offset;   /* Offset of the window top */
1804         unsigned long yoffset;  /* Offset from the window side. */
1805         unsigned long lineno;   /* Current line number */
1806         unsigned long p_offset; /* Previous offset of the window top */
1807         unsigned long p_yoffset;/* Previous offset from the window side */
1808         unsigned long p_lineno; /* Previous current line number */
1809         bool p_restore;         /* Should the previous position be restored. */
1811         /* Searching */
1812         char grep[SIZEOF_STR];  /* Search string */
1813         regex_t *regex;         /* Pre-compiled regexp */
1815         /* If non-NULL, points to the view that opened this view. If this view
1816          * is closed tig will switch back to the parent view. */
1817         struct view *parent;
1818         struct view *prev;
1820         /* Buffering */
1821         size_t lines;           /* Total number of lines */
1822         struct line *line;      /* Line index */
1823         unsigned int digits;    /* Number of digits in the lines member. */
1825         /* Drawing */
1826         struct line *curline;   /* Line currently being drawn. */
1827         enum line_type curtype; /* Attribute currently used for drawing. */
1828         unsigned long col;      /* Column when drawing. */
1829         bool has_scrolled;      /* View was scrolled. */
1831         /* Loading */
1832         const char **argv;      /* Shell command arguments. */
1833         const char *dir;        /* Directory from which to execute. */
1834         struct io io;
1835         struct io *pipe;
1836         time_t start_time;
1837         time_t update_secs;
1838 };
1840 struct view_ops {
1841         /* What type of content being displayed. Used in the title bar. */
1842         const char *type;
1843         /* Default command arguments. */
1844         const char **argv;
1845         /* Open and reads in all view content. */
1846         bool (*open)(struct view *view);
1847         /* Read one line; updates view->line. */
1848         bool (*read)(struct view *view, char *data);
1849         /* Draw one line; @lineno must be < view->height. */
1850         bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1851         /* Depending on view handle a special requests. */
1852         enum request (*request)(struct view *view, enum request request, struct line *line);
1853         /* Search for regexp in a line. */
1854         bool (*grep)(struct view *view, struct line *line);
1855         /* Select line */
1856         void (*select)(struct view *view, struct line *line);
1857         /* Prepare view for loading */
1858         bool (*prepare)(struct view *view);
1859 };
1861 static struct view_ops blame_ops;
1862 static struct view_ops blob_ops;
1863 static struct view_ops diff_ops;
1864 static struct view_ops help_ops;
1865 static struct view_ops log_ops;
1866 static struct view_ops main_ops;
1867 static struct view_ops pager_ops;
1868 static struct view_ops stage_ops;
1869 static struct view_ops status_ops;
1870 static struct view_ops tree_ops;
1871 static struct view_ops branch_ops;
1873 #define VIEW_STR(type, name, env, ref, ops, map, git) \
1874         { type, name, #env, ref, ops, map, git }
1876 #define VIEW_(id, name, ops, git, ref) \
1877         VIEW_STR(VIEW_##id, name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
1879 static struct view views[] = {
1880         VIEW_(MAIN,   "main",   &main_ops,   TRUE,  ref_head),
1881         VIEW_(DIFF,   "diff",   &diff_ops,   TRUE,  ref_commit),
1882         VIEW_(LOG,    "log",    &log_ops,    TRUE,  ref_head),
1883         VIEW_(TREE,   "tree",   &tree_ops,   TRUE,  ref_commit),
1884         VIEW_(BLOB,   "blob",   &blob_ops,   TRUE,  ref_blob),
1885         VIEW_(BLAME,  "blame",  &blame_ops,  TRUE,  ref_commit),
1886         VIEW_(BRANCH, "branch", &branch_ops, TRUE,  ref_head),
1887         VIEW_(HELP,   "help",   &help_ops,   FALSE, ""),
1888         VIEW_(PAGER,  "pager",  &pager_ops,  FALSE, ""),
1889         VIEW_(STATUS, "status", &status_ops, TRUE,  ""),
1890         VIEW_(STAGE,  "stage",  &stage_ops,  TRUE,  ""),
1891 };
1893 #define VIEW(req)       (&views[(req) - REQ_OFFSET - 1])
1895 #define foreach_view(view, i) \
1896         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1898 #define view_is_displayed(view) \
1899         (view == display[0] || view == display[1])
1901 static enum request
1902 view_request(struct view *view, enum request request)
1904         if (!view || !view->lines)
1905                 return request;
1906         return view->ops->request(view, request, &view->line[view->lineno]);
1910 /*
1911  * View drawing.
1912  */
1914 static inline void
1915 set_view_attr(struct view *view, enum line_type type)
1917         if (!view->curline->selected && view->curtype != type) {
1918                 (void) wattrset(view->win, get_line_attr(type));
1919                 wchgat(view->win, -1, 0, type, NULL);
1920                 view->curtype = type;
1921         }
1924 static int
1925 draw_chars(struct view *view, enum line_type type, const char *string,
1926            int max_len, bool use_tilde)
1928         static char out_buffer[BUFSIZ * 2];
1929         int len = 0;
1930         int col = 0;
1931         int trimmed = FALSE;
1932         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1934         if (max_len <= 0)
1935                 return 0;
1937         len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1939         set_view_attr(view, type);
1940         if (len > 0) {
1941                 if (opt_iconv_out != ICONV_NONE) {
1942                         ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1943                         size_t inlen = len + 1;
1945                         char *outbuf = out_buffer;
1946                         size_t outlen = sizeof(out_buffer);
1948                         size_t ret;
1950                         ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1951                         if (ret != (size_t) -1) {
1952                                 string = out_buffer;
1953                                 len = sizeof(out_buffer) - outlen;
1954                         }
1955                 }
1957                 waddnstr(view->win, string, len);
1959                 if (trimmed && use_tilde) {
1960                         set_view_attr(view, LINE_DELIMITER);
1961                         waddch(view->win, '~');
1962                         col++;
1963                 }
1964         }
1966         return col;
1969 static int
1970 draw_space(struct view *view, enum line_type type, int max, int spaces)
1972         static char space[] = "                    ";
1973         int col = 0;
1975         spaces = MIN(max, spaces);
1977         while (spaces > 0) {
1978                 int len = MIN(spaces, sizeof(space) - 1);
1980                 col += draw_chars(view, type, space, len, FALSE);
1981                 spaces -= len;
1982         }
1984         return col;
1987 static bool
1988 draw_text(struct view *view, enum line_type type, const char *string)
1990         char text[SIZEOF_STR];
1992         do {
1993                 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1995                 view->col += draw_chars(view, type, text, view->width + view->yoffset - view->col, TRUE);
1996                 string += pos;
1997         } while (*string && view->width + view->yoffset > view->col);
1999         return view->width + view->yoffset <= view->col;
2002 static bool
2003 draw_graphic(struct view *view, enum line_type type, chtype graphic[], size_t size)
2005         size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
2006         int max = view->width + view->yoffset - view->col;
2007         int i;
2009         if (max < size)
2010                 size = max;
2012         set_view_attr(view, type);
2013         /* Using waddch() instead of waddnstr() ensures that
2014          * they'll be rendered correctly for the cursor line. */
2015         for (i = skip; i < size; i++)
2016                 waddch(view->win, graphic[i]);
2018         view->col += size;
2019         if (size < max && skip <= size)
2020                 waddch(view->win, ' ');
2021         view->col++;
2023         return view->width + view->yoffset <= view->col;
2026 static bool
2027 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
2029         int max = MIN(view->width + view->yoffset - view->col, len);
2030         int col;
2032         if (text)
2033                 col = draw_chars(view, type, text, max - 1, trim);
2034         else
2035                 col = draw_space(view, type, max - 1, max - 1);
2037         view->col += col;
2038         view->col += draw_space(view, LINE_DEFAULT, max - col, max - col);
2039         return view->width + view->yoffset <= view->col;
2042 static bool
2043 draw_date(struct view *view, struct time *time)
2045         const char *date = mkdate(time, opt_date);
2046         int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
2048         return draw_field(view, LINE_DATE, date, cols, FALSE);
2051 static bool
2052 draw_author(struct view *view, const char *author)
2054         bool trim = opt_author_cols == 0 || opt_author_cols > 5;
2055         bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
2057         if (abbreviate && author)
2058                 author = get_author_initials(author);
2060         return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
2063 static bool
2064 draw_mode(struct view *view, mode_t mode)
2066         const char *str;
2068         if (S_ISDIR(mode))
2069                 str = "drwxr-xr-x";
2070         else if (S_ISLNK(mode))
2071                 str = "lrwxrwxrwx";
2072         else if (S_ISGITLINK(mode))
2073                 str = "m---------";
2074         else if (S_ISREG(mode) && mode & S_IXUSR)
2075                 str = "-rwxr-xr-x";
2076         else if (S_ISREG(mode))
2077                 str = "-rw-r--r--";
2078         else
2079                 str = "----------";
2081         return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2084 static bool
2085 draw_lineno(struct view *view, unsigned int lineno)
2087         char number[10];
2088         int digits3 = view->digits < 3 ? 3 : view->digits;
2089         int max = MIN(view->width + view->yoffset - view->col, digits3);
2090         char *text = NULL;
2091         chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2093         lineno += view->offset + 1;
2094         if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2095                 static char fmt[] = "%1ld";
2097                 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2098                 if (string_format(number, fmt, lineno))
2099                         text = number;
2100         }
2101         if (text)
2102                 view->col += draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2103         else
2104                 view->col += draw_space(view, LINE_LINE_NUMBER, max, digits3);
2105         return draw_graphic(view, LINE_DEFAULT, &separator, 1);
2108 static bool
2109 draw_view_line(struct view *view, unsigned int lineno)
2111         struct line *line;
2112         bool selected = (view->offset + lineno == view->lineno);
2114         assert(view_is_displayed(view));
2116         if (view->offset + lineno >= view->lines)
2117                 return FALSE;
2119         line = &view->line[view->offset + lineno];
2121         wmove(view->win, lineno, 0);
2122         if (line->cleareol)
2123                 wclrtoeol(view->win);
2124         view->col = 0;
2125         view->curline = line;
2126         view->curtype = LINE_NONE;
2127         line->selected = FALSE;
2128         line->dirty = line->cleareol = 0;
2130         if (selected) {
2131                 set_view_attr(view, LINE_CURSOR);
2132                 line->selected = TRUE;
2133                 view->ops->select(view, line);
2134         }
2136         return view->ops->draw(view, line, lineno);
2139 static void
2140 redraw_view_dirty(struct view *view)
2142         bool dirty = FALSE;
2143         int lineno;
2145         for (lineno = 0; lineno < view->height; lineno++) {
2146                 if (view->offset + lineno >= view->lines)
2147                         break;
2148                 if (!view->line[view->offset + lineno].dirty)
2149                         continue;
2150                 dirty = TRUE;
2151                 if (!draw_view_line(view, lineno))
2152                         break;
2153         }
2155         if (!dirty)
2156                 return;
2157         wnoutrefresh(view->win);
2160 static void
2161 redraw_view_from(struct view *view, int lineno)
2163         assert(0 <= lineno && lineno < view->height);
2165         for (; lineno < view->height; lineno++) {
2166                 if (!draw_view_line(view, lineno))
2167                         break;
2168         }
2170         wnoutrefresh(view->win);
2173 static void
2174 redraw_view(struct view *view)
2176         werase(view->win);
2177         redraw_view_from(view, 0);
2181 static void
2182 update_view_title(struct view *view)
2184         char buf[SIZEOF_STR];
2185         char state[SIZEOF_STR];
2186         size_t bufpos = 0, statelen = 0;
2187         WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2189         assert(view_is_displayed(view));
2191         if (view->type != VIEW_STATUS && view->lines) {
2192                 unsigned int view_lines = view->offset + view->height;
2193                 unsigned int lines = view->lines
2194                                    ? MIN(view_lines, view->lines) * 100 / view->lines
2195                                    : 0;
2197                 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2198                                    view->ops->type,
2199                                    view->lineno + 1,
2200                                    view->lines,
2201                                    lines);
2203         }
2205         if (view->pipe) {
2206                 time_t secs = time(NULL) - view->start_time;
2208                 /* Three git seconds are a long time ... */
2209                 if (secs > 2)
2210                         string_format_from(state, &statelen, " loading %lds", secs);
2211         }
2213         string_format_from(buf, &bufpos, "[%s]", view->name);
2214         if (*view->ref && bufpos < view->width) {
2215                 size_t refsize = strlen(view->ref);
2216                 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2218                 if (minsize < view->width)
2219                         refsize = view->width - minsize + 7;
2220                 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2221         }
2223         if (statelen && bufpos < view->width) {
2224                 string_format_from(buf, &bufpos, "%s", state);
2225         }
2227         if (view == display[current_view])
2228                 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2229         else
2230                 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2232         mvwaddnstr(window, 0, 0, buf, bufpos);
2233         wclrtoeol(window);
2234         wnoutrefresh(window);
2237 static int
2238 apply_step(double step, int value)
2240         if (step >= 1)
2241                 return (int) step;
2242         value *= step + 0.01;
2243         return value ? value : 1;
2246 static void
2247 resize_display(void)
2249         int offset, i;
2250         struct view *base = display[0];
2251         struct view *view = display[1] ? display[1] : display[0];
2253         /* Setup window dimensions */
2255         getmaxyx(stdscr, base->height, base->width);
2257         /* Make room for the status window. */
2258         base->height -= 1;
2260         if (view != base) {
2261                 /* Horizontal split. */
2262                 view->width   = base->width;
2263                 view->height  = apply_step(opt_scale_split_view, base->height);
2264                 view->height  = MAX(view->height, MIN_VIEW_HEIGHT);
2265                 view->height  = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2266                 base->height -= view->height;
2268                 /* Make room for the title bar. */
2269                 view->height -= 1;
2270         }
2272         /* Make room for the title bar. */
2273         base->height -= 1;
2275         offset = 0;
2277         foreach_displayed_view (view, i) {
2278                 if (!display_win[i]) {
2279                         display_win[i] = newwin(view->height, view->width, offset, 0);
2280                         if (!display_win[i])
2281                                 die("Failed to create %s view", view->name);
2283                         scrollok(display_win[i], FALSE);
2285                         display_title[i] = newwin(1, view->width, offset + view->height, 0);
2286                         if (!display_title[i])
2287                                 die("Failed to create title window");
2289                 } else {
2290                         wresize(display_win[i], view->height, view->width);
2291                         mvwin(display_win[i],   offset, 0);
2292                         mvwin(display_title[i], offset + view->height, 0);
2293                 }
2295                 view->win = display_win[i];
2297                 offset += view->height + 1;
2298         }
2301 static void
2302 redraw_display(bool clear)
2304         struct view *view;
2305         int i;
2307         foreach_displayed_view (view, i) {
2308                 if (clear)
2309                         wclear(view->win);
2310                 redraw_view(view);
2311                 update_view_title(view);
2312         }
2316 /*
2317  * Option management
2318  */
2320 #define TOGGLE_MENU \
2321         TOGGLE_(LINENO,    '.', "line numbers",      &opt_line_number, NULL) \
2322         TOGGLE_(DATE,      'D', "dates",             &opt_date,   date_map) \
2323         TOGGLE_(AUTHOR,    'A', "author names",      &opt_author, author_map) \
2324         TOGGLE_(REV_GRAPH, 'g', "revision graph",    &opt_rev_graph, NULL) \
2325         TOGGLE_(REFS,      'F', "reference display", &opt_show_refs, NULL)
2327 static void
2328 toggle_option(enum request request)
2330         const struct {
2331                 enum request request;
2332                 const struct enum_map *map;
2333                 size_t map_size;
2334         } data[] = {            
2335 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2336                 TOGGLE_MENU
2337 #undef  TOGGLE_
2338         };
2339         const struct menu_item menu[] = {
2340 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2341                 TOGGLE_MENU
2342 #undef  TOGGLE_
2343                 { 0 }
2344         };
2345         int i = 0;
2347         if (request == REQ_OPTIONS) {
2348                 if (!prompt_menu("Toggle option", menu, &i))
2349                         return;
2350         } else {
2351                 while (i < ARRAY_SIZE(data) && data[i].request != request)
2352                         i++;
2353                 if (i >= ARRAY_SIZE(data))
2354                         die("Invalid request (%d)", request);
2355         }
2357         if (data[i].map != NULL) {
2358                 unsigned int *opt = menu[i].data;
2360                 *opt = (*opt + 1) % data[i].map_size;
2361                 redraw_display(FALSE);
2362                 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2364         } else {
2365                 bool *option = menu[i].data;
2367                 *option = !*option;
2368                 redraw_display(FALSE);
2369                 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2370         }
2373 static void
2374 maximize_view(struct view *view)
2376         memset(display, 0, sizeof(display));
2377         current_view = 0;
2378         display[current_view] = view;
2379         resize_display();
2380         redraw_display(FALSE);
2381         report("");
2385 /*
2386  * Navigation
2387  */
2389 static bool
2390 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2392         if (lineno >= view->lines)
2393                 lineno = view->lines > 0 ? view->lines - 1 : 0;
2395         if (offset > lineno || offset + view->height <= lineno) {
2396                 unsigned long half = view->height / 2;
2398                 if (lineno > half)
2399                         offset = lineno - half;
2400                 else
2401                         offset = 0;
2402         }
2404         if (offset != view->offset || lineno != view->lineno) {
2405                 view->offset = offset;
2406                 view->lineno = lineno;
2407                 return TRUE;
2408         }
2410         return FALSE;
2413 /* Scrolling backend */
2414 static void
2415 do_scroll_view(struct view *view, int lines)
2417         bool redraw_current_line = FALSE;
2419         /* The rendering expects the new offset. */
2420         view->offset += lines;
2422         assert(0 <= view->offset && view->offset < view->lines);
2423         assert(lines);
2425         /* Move current line into the view. */
2426         if (view->lineno < view->offset) {
2427                 view->lineno = view->offset;
2428                 redraw_current_line = TRUE;
2429         } else if (view->lineno >= view->offset + view->height) {
2430                 view->lineno = view->offset + view->height - 1;
2431                 redraw_current_line = TRUE;
2432         }
2434         assert(view->offset <= view->lineno && view->lineno < view->lines);
2436         /* Redraw the whole screen if scrolling is pointless. */
2437         if (view->height < ABS(lines)) {
2438                 redraw_view(view);
2440         } else {
2441                 int line = lines > 0 ? view->height - lines : 0;
2442                 int end = line + ABS(lines);
2444                 scrollok(view->win, TRUE);
2445                 wscrl(view->win, lines);
2446                 scrollok(view->win, FALSE);
2448                 while (line < end && draw_view_line(view, line))
2449                         line++;
2451                 if (redraw_current_line)
2452                         draw_view_line(view, view->lineno - view->offset);
2453                 wnoutrefresh(view->win);
2454         }
2456         view->has_scrolled = TRUE;
2457         report("");
2460 /* Scroll frontend */
2461 static void
2462 scroll_view(struct view *view, enum request request)
2464         int lines = 1;
2466         assert(view_is_displayed(view));
2468         switch (request) {
2469         case REQ_SCROLL_FIRST_COL:
2470                 view->yoffset = 0;
2471                 redraw_view_from(view, 0);
2472                 report("");
2473                 return;
2474         case REQ_SCROLL_LEFT:
2475                 if (view->yoffset == 0) {
2476                         report("Cannot scroll beyond the first column");
2477                         return;
2478                 }
2479                 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2480                         view->yoffset = 0;
2481                 else
2482                         view->yoffset -= apply_step(opt_hscroll, view->width);
2483                 redraw_view_from(view, 0);
2484                 report("");
2485                 return;
2486         case REQ_SCROLL_RIGHT:
2487                 view->yoffset += apply_step(opt_hscroll, view->width);
2488                 redraw_view(view);
2489                 report("");
2490                 return;
2491         case REQ_SCROLL_PAGE_DOWN:
2492                 lines = view->height;
2493         case REQ_SCROLL_LINE_DOWN:
2494                 if (view->offset + lines > view->lines)
2495                         lines = view->lines - view->offset;
2497                 if (lines == 0 || view->offset + view->height >= view->lines) {
2498                         report("Cannot scroll beyond the last line");
2499                         return;
2500                 }
2501                 break;
2503         case REQ_SCROLL_PAGE_UP:
2504                 lines = view->height;
2505         case REQ_SCROLL_LINE_UP:
2506                 if (lines > view->offset)
2507                         lines = view->offset;
2509                 if (lines == 0) {
2510                         report("Cannot scroll beyond the first line");
2511                         return;
2512                 }
2514                 lines = -lines;
2515                 break;
2517         default:
2518                 die("request %d not handled in switch", request);
2519         }
2521         do_scroll_view(view, lines);
2524 /* Cursor moving */
2525 static void
2526 move_view(struct view *view, enum request request)
2528         int scroll_steps = 0;
2529         int steps;
2531         switch (request) {
2532         case REQ_MOVE_FIRST_LINE:
2533                 steps = -view->lineno;
2534                 break;
2536         case REQ_MOVE_LAST_LINE:
2537                 steps = view->lines - view->lineno - 1;
2538                 break;
2540         case REQ_MOVE_PAGE_UP:
2541                 steps = view->height > view->lineno
2542                       ? -view->lineno : -view->height;
2543                 break;
2545         case REQ_MOVE_PAGE_DOWN:
2546                 steps = view->lineno + view->height >= view->lines
2547                       ? view->lines - view->lineno - 1 : view->height;
2548                 break;
2550         case REQ_MOVE_UP:
2551                 steps = -1;
2552                 break;
2554         case REQ_MOVE_DOWN:
2555                 steps = 1;
2556                 break;
2558         default:
2559                 die("request %d not handled in switch", request);
2560         }
2562         if (steps <= 0 && view->lineno == 0) {
2563                 report("Cannot move beyond the first line");
2564                 return;
2566         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2567                 report("Cannot move beyond the last line");
2568                 return;
2569         }
2571         /* Move the current line */
2572         view->lineno += steps;
2573         assert(0 <= view->lineno && view->lineno < view->lines);
2575         /* Check whether the view needs to be scrolled */
2576         if (view->lineno < view->offset ||
2577             view->lineno >= view->offset + view->height) {
2578                 scroll_steps = steps;
2579                 if (steps < 0 && -steps > view->offset) {
2580                         scroll_steps = -view->offset;
2582                 } else if (steps > 0) {
2583                         if (view->lineno == view->lines - 1 &&
2584                             view->lines > view->height) {
2585                                 scroll_steps = view->lines - view->offset - 1;
2586                                 if (scroll_steps >= view->height)
2587                                         scroll_steps -= view->height - 1;
2588                         }
2589                 }
2590         }
2592         if (!view_is_displayed(view)) {
2593                 view->offset += scroll_steps;
2594                 assert(0 <= view->offset && view->offset < view->lines);
2595                 view->ops->select(view, &view->line[view->lineno]);
2596                 return;
2597         }
2599         /* Repaint the old "current" line if we be scrolling */
2600         if (ABS(steps) < view->height)
2601                 draw_view_line(view, view->lineno - steps - view->offset);
2603         if (scroll_steps) {
2604                 do_scroll_view(view, scroll_steps);
2605                 return;
2606         }
2608         /* Draw the current line */
2609         draw_view_line(view, view->lineno - view->offset);
2611         wnoutrefresh(view->win);
2612         report("");
2616 /*
2617  * Searching
2618  */
2620 static void search_view(struct view *view, enum request request);
2622 static bool
2623 grep_text(struct view *view, const char *text[])
2625         regmatch_t pmatch;
2626         size_t i;
2628         for (i = 0; text[i]; i++)
2629                 if (*text[i] &&
2630                     regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2631                         return TRUE;
2632         return FALSE;
2635 static void
2636 select_view_line(struct view *view, unsigned long lineno)
2638         unsigned long old_lineno = view->lineno;
2639         unsigned long old_offset = view->offset;
2641         if (goto_view_line(view, view->offset, lineno)) {
2642                 if (view_is_displayed(view)) {
2643                         if (old_offset != view->offset) {
2644                                 redraw_view(view);
2645                         } else {
2646                                 draw_view_line(view, old_lineno - view->offset);
2647                                 draw_view_line(view, view->lineno - view->offset);
2648                                 wnoutrefresh(view->win);
2649                         }
2650                 } else {
2651                         view->ops->select(view, &view->line[view->lineno]);
2652                 }
2653         }
2656 static void
2657 find_next(struct view *view, enum request request)
2659         unsigned long lineno = view->lineno;
2660         int direction;
2662         if (!*view->grep) {
2663                 if (!*opt_search)
2664                         report("No previous search");
2665                 else
2666                         search_view(view, request);
2667                 return;
2668         }
2670         switch (request) {
2671         case REQ_SEARCH:
2672         case REQ_FIND_NEXT:
2673                 direction = 1;
2674                 break;
2676         case REQ_SEARCH_BACK:
2677         case REQ_FIND_PREV:
2678                 direction = -1;
2679                 break;
2681         default:
2682                 return;
2683         }
2685         if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2686                 lineno += direction;
2688         /* Note, lineno is unsigned long so will wrap around in which case it
2689          * will become bigger than view->lines. */
2690         for (; lineno < view->lines; lineno += direction) {
2691                 if (view->ops->grep(view, &view->line[lineno])) {
2692                         select_view_line(view, lineno);
2693                         report("Line %ld matches '%s'", lineno + 1, view->grep);
2694                         return;
2695                 }
2696         }
2698         report("No match found for '%s'", view->grep);
2701 static void
2702 search_view(struct view *view, enum request request)
2704         int regex_err;
2706         if (view->regex) {
2707                 regfree(view->regex);
2708                 *view->grep = 0;
2709         } else {
2710                 view->regex = calloc(1, sizeof(*view->regex));
2711                 if (!view->regex)
2712                         return;
2713         }
2715         regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2716         if (regex_err != 0) {
2717                 char buf[SIZEOF_STR] = "unknown error";
2719                 regerror(regex_err, view->regex, buf, sizeof(buf));
2720                 report("Search failed: %s", buf);
2721                 return;
2722         }
2724         string_copy(view->grep, opt_search);
2726         find_next(view, request);
2729 /*
2730  * Incremental updating
2731  */
2733 static void
2734 reset_view(struct view *view)
2736         int i;
2738         for (i = 0; i < view->lines; i++)
2739                 free(view->line[i].data);
2740         free(view->line);
2742         view->p_offset = view->offset;
2743         view->p_yoffset = view->yoffset;
2744         view->p_lineno = view->lineno;
2746         view->line = NULL;
2747         view->offset = 0;
2748         view->yoffset = 0;
2749         view->lines  = 0;
2750         view->lineno = 0;
2751         view->vid[0] = 0;
2752         view->update_secs = 0;
2755 static const char *
2756 format_arg(const char *name)
2758         static struct {
2759                 const char *name;
2760                 size_t namelen;
2761                 const char *value;
2762                 const char *value_if_empty;
2763         } vars[] = {
2764 #define FORMAT_VAR(name, value, value_if_empty) \
2765         { name, STRING_SIZE(name), value, value_if_empty }
2766                 FORMAT_VAR("%(directory)",      opt_path,       ""),
2767                 FORMAT_VAR("%(file)",           opt_file,       ""),
2768                 FORMAT_VAR("%(ref)",            opt_ref,        "HEAD"),
2769                 FORMAT_VAR("%(head)",           ref_head,       ""),
2770                 FORMAT_VAR("%(commit)",         ref_commit,     ""),
2771                 FORMAT_VAR("%(blob)",           ref_blob,       ""),
2772                 FORMAT_VAR("%(branch)",         ref_branch,     ""),
2773         };
2774         int i;
2776         for (i = 0; i < ARRAY_SIZE(vars); i++)
2777                 if (!strncmp(name, vars[i].name, vars[i].namelen))
2778                         return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2780         report("Unknown replacement: `%s`", name);
2781         return NULL;
2784 static bool
2785 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2787         char buf[SIZEOF_STR];
2788         int argc;
2790         argv_free(*dst_argv);
2792         for (argc = 0; src_argv[argc]; argc++) {
2793                 const char *arg = src_argv[argc];
2794                 size_t bufpos = 0;
2796                 if (!strcmp(arg, "%(fileargs)")) {
2797                         if (!argv_append_array(dst_argv, opt_file_argv))
2798                                 break;
2799                         continue;
2801                 } else if (!strcmp(arg, "%(diffargs)")) {
2802                         if (!argv_append_array(dst_argv, opt_diff_argv))
2803                                 break;
2804                         continue;
2806                 } else if (!strcmp(arg, "%(revargs)") ||
2807                            (first && !strcmp(arg, "%(commit)"))) {
2808                         if (!argv_append_array(dst_argv, opt_rev_argv))
2809                                 break;
2810                         continue;
2811                 }
2813                 while (arg) {
2814                         char *next = strstr(arg, "%(");
2815                         int len = next - arg;
2816                         const char *value;
2818                         if (!next || !replace) {
2819                                 len = strlen(arg);
2820                                 value = "";
2822                         } else {
2823                                 value = format_arg(next);
2825                                 if (!value) {
2826                                         return FALSE;
2827                                 }
2828                         }
2830                         if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2831                                 return FALSE;
2833                         arg = next && replace ? strchr(next, ')') + 1 : NULL;
2834                 }
2836                 if (!argv_append(dst_argv, buf))
2837                         break;
2838         }
2840         return src_argv[argc] == NULL;
2843 static bool
2844 restore_view_position(struct view *view)
2846         if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2847                 return FALSE;
2849         /* Changing the view position cancels the restoring. */
2850         /* FIXME: Changing back to the first line is not detected. */
2851         if (view->offset != 0 || view->lineno != 0) {
2852                 view->p_restore = FALSE;
2853                 return FALSE;
2854         }
2856         if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2857             view_is_displayed(view))
2858                 werase(view->win);
2860         view->yoffset = view->p_yoffset;
2861         view->p_restore = FALSE;
2863         return TRUE;
2866 static void
2867 end_update(struct view *view, bool force)
2869         if (!view->pipe)
2870                 return;
2871         while (!view->ops->read(view, NULL))
2872                 if (!force)
2873                         return;
2874         if (force)
2875                 io_kill(view->pipe);
2876         io_done(view->pipe);
2877         view->pipe = NULL;
2880 static void
2881 setup_update(struct view *view, const char *vid)
2883         reset_view(view);
2884         string_copy_rev(view->vid, vid);
2885         view->pipe = &view->io;
2886         view->start_time = time(NULL);
2889 static bool
2890 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2892         view->dir = dir;
2893         return format_argv(&view->argv, argv, replace, !view->prev);
2896 static bool
2897 prepare_update(struct view *view, const char *argv[], const char *dir)
2899         if (view->pipe)
2900                 end_update(view, TRUE);
2901         return prepare_io(view, dir, argv, FALSE);
2904 static bool
2905 start_update(struct view *view, const char **argv, const char *dir)
2907         if (view->pipe)
2908                 io_done(view->pipe);
2909         return prepare_io(view, dir, argv, FALSE) &&
2910                io_run(&view->io, IO_RD, dir, view->argv);
2913 static bool
2914 prepare_update_file(struct view *view, const char *name)
2916         if (view->pipe)
2917                 end_update(view, TRUE);
2918         argv_free(view->argv);
2919         return io_open(&view->io, "%s/%s", opt_cdup[0] ? opt_cdup : ".", name);
2922 static bool
2923 begin_update(struct view *view, bool refresh)
2925         if (view->pipe)
2926                 end_update(view, TRUE);
2928         if (!refresh) {
2929                 if (view->ops->prepare) {
2930                         if (!view->ops->prepare(view))
2931                                 return FALSE;
2932                 } else if (!prepare_io(view, NULL, view->ops->argv, TRUE)) {
2933                         return FALSE;
2934                 }
2936                 /* Put the current ref_* value to the view title ref
2937                  * member. This is needed by the blob view. Most other
2938                  * views sets it automatically after loading because the
2939                  * first line is a commit line. */
2940                 string_copy_rev(view->ref, view->id);
2941         }
2943         if (view->argv && view->argv[0] &&
2944             !io_run(&view->io, IO_RD, view->dir, view->argv))
2945                 return FALSE;
2947         setup_update(view, view->id);
2949         return TRUE;
2952 static bool
2953 update_view(struct view *view)
2955         char out_buffer[BUFSIZ * 2];
2956         char *line;
2957         /* Clear the view and redraw everything since the tree sorting
2958          * might have rearranged things. */
2959         bool redraw = view->lines == 0;
2960         bool can_read = TRUE;
2962         if (!view->pipe)
2963                 return TRUE;
2965         if (!io_can_read(view->pipe)) {
2966                 if (view->lines == 0 && view_is_displayed(view)) {
2967                         time_t secs = time(NULL) - view->start_time;
2969                         if (secs > 1 && secs > view->update_secs) {
2970                                 if (view->update_secs == 0)
2971                                         redraw_view(view);
2972                                 update_view_title(view);
2973                                 view->update_secs = secs;
2974                         }
2975                 }
2976                 return TRUE;
2977         }
2979         for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2980                 if (opt_iconv_in != ICONV_NONE) {
2981                         ICONV_CONST char *inbuf = line;
2982                         size_t inlen = strlen(line) + 1;
2984                         char *outbuf = out_buffer;
2985                         size_t outlen = sizeof(out_buffer);
2987                         size_t ret;
2989                         ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2990                         if (ret != (size_t) -1)
2991                                 line = out_buffer;
2992                 }
2994                 if (!view->ops->read(view, line)) {
2995                         report("Allocation failure");
2996                         end_update(view, TRUE);
2997                         return FALSE;
2998                 }
2999         }
3001         {
3002                 unsigned long lines = view->lines;
3003                 int digits;
3005                 for (digits = 0; lines; digits++)
3006                         lines /= 10;
3008                 /* Keep the displayed view in sync with line number scaling. */
3009                 if (digits != view->digits) {
3010                         view->digits = digits;
3011                         if (opt_line_number || view->type == VIEW_BLAME)
3012                                 redraw = TRUE;
3013                 }
3014         }
3016         if (io_error(view->pipe)) {
3017                 report("Failed to read: %s", io_strerror(view->pipe));
3018                 end_update(view, TRUE);
3020         } else if (io_eof(view->pipe)) {
3021                 if (view_is_displayed(view))
3022                         report("");
3023                 end_update(view, FALSE);
3024         }
3026         if (restore_view_position(view))
3027                 redraw = TRUE;
3029         if (!view_is_displayed(view))
3030                 return TRUE;
3032         if (redraw)
3033                 redraw_view_from(view, 0);
3034         else
3035                 redraw_view_dirty(view);
3037         /* Update the title _after_ the redraw so that if the redraw picks up a
3038          * commit reference in view->ref it'll be available here. */
3039         update_view_title(view);
3040         return TRUE;
3043 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3045 static struct line *
3046 add_line_data(struct view *view, void *data, enum line_type type)
3048         struct line *line;
3050         if (!realloc_lines(&view->line, view->lines, 1))
3051                 return NULL;
3053         line = &view->line[view->lines++];
3054         memset(line, 0, sizeof(*line));
3055         line->type = type;
3056         line->data = data;
3057         line->dirty = 1;
3059         return line;
3062 static struct line *
3063 add_line_text(struct view *view, const char *text, enum line_type type)
3065         char *data = text ? strdup(text) : NULL;
3067         return data ? add_line_data(view, data, type) : NULL;
3070 static struct line *
3071 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3073         char buf[SIZEOF_STR];
3074         va_list args;
3076         va_start(args, fmt);
3077         if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
3078                 buf[0] = 0;
3079         va_end(args);
3081         return buf[0] ? add_line_text(view, buf, type) : NULL;
3084 /*
3085  * View opening
3086  */
3088 enum open_flags {
3089         OPEN_DEFAULT = 0,       /* Use default view switching. */
3090         OPEN_SPLIT = 1,         /* Split current view. */
3091         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
3092         OPEN_REFRESH = 16,      /* Refresh view using previous command. */
3093         OPEN_PREPARED = 32,     /* Open already prepared command. */
3094 };
3096 static void
3097 open_view(struct view *prev, enum request request, enum open_flags flags)
3099         bool split = !!(flags & OPEN_SPLIT);
3100         bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
3101         bool nomaximize = !!(flags & OPEN_REFRESH);
3102         struct view *view = VIEW(request);
3103         int nviews = displayed_views();
3104         struct view *base_view = display[0];
3106         if (view == prev && nviews == 1 && !reload) {
3107                 report("Already in %s view", view->name);
3108                 return;
3109         }
3111         if (view->git_dir && !opt_git_dir[0]) {
3112                 report("The %s view is disabled in pager view", view->name);
3113                 return;
3114         }
3116         if (split) {
3117                 display[1] = view;
3118                 current_view = 1;
3119                 view->parent = prev;
3120         } else if (!nomaximize) {
3121                 /* Maximize the current view. */
3122                 memset(display, 0, sizeof(display));
3123                 current_view = 0;
3124                 display[current_view] = view;
3125         }
3127         /* No prev signals that this is the first loaded view. */
3128         if (prev && view != prev) {
3129                 view->prev = prev;
3130         }
3132         /* Resize the view when switching between split- and full-screen,
3133          * or when switching between two different full-screen views. */
3134         if (nviews != displayed_views() ||
3135             (nviews == 1 && base_view != display[0]))
3136                 resize_display();
3138         if (view->ops->open) {
3139                 if (view->pipe)
3140                         end_update(view, TRUE);
3141                 if (!view->ops->open(view)) {
3142                         report("Failed to load %s view", view->name);
3143                         return;
3144                 }
3145                 restore_view_position(view);
3147         } else if ((reload || strcmp(view->vid, view->id)) &&
3148                    !begin_update(view, flags & (OPEN_REFRESH | OPEN_PREPARED))) {
3149                 report("Failed to load %s view", view->name);
3150                 return;
3151         }
3153         if (split && prev->lineno - prev->offset >= prev->height) {
3154                 /* Take the title line into account. */
3155                 int lines = prev->lineno - prev->offset - prev->height + 1;
3157                 /* Scroll the view that was split if the current line is
3158                  * outside the new limited view. */
3159                 do_scroll_view(prev, lines);
3160         }
3162         if (prev && view != prev && split && view_is_displayed(prev)) {
3163                 /* "Blur" the previous view. */
3164                 update_view_title(prev);
3165         }
3167         if (view->pipe && view->lines == 0) {
3168                 /* Clear the old view and let the incremental updating refill
3169                  * the screen. */
3170                 werase(view->win);
3171                 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
3172                 report("");
3173         } else if (view_is_displayed(view)) {
3174                 redraw_view(view);
3175                 report("");
3176         }
3179 static void
3180 open_external_viewer(const char *argv[], const char *dir)
3182         def_prog_mode();           /* save current tty modes */
3183         endwin();                  /* restore original tty modes */
3184         io_run_fg(argv, dir);
3185         fprintf(stderr, "Press Enter to continue");
3186         getc(opt_tty);
3187         reset_prog_mode();
3188         redraw_display(TRUE);
3191 static void
3192 open_mergetool(const char *file)
3194         const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3196         open_external_viewer(mergetool_argv, opt_cdup);
3199 static void
3200 open_editor(const char *file)
3202         const char *editor_argv[] = { "vi", file, NULL };
3203         const char *editor;
3205         editor = getenv("GIT_EDITOR");
3206         if (!editor && *opt_editor)
3207                 editor = opt_editor;
3208         if (!editor)
3209                 editor = getenv("VISUAL");
3210         if (!editor)
3211                 editor = getenv("EDITOR");
3212         if (!editor)
3213                 editor = "vi";
3215         editor_argv[0] = editor;
3216         open_external_viewer(editor_argv, opt_cdup);
3219 static void
3220 open_run_request(enum request request)
3222         struct run_request *req = get_run_request(request);
3223         const char **argv = NULL;
3225         if (!req) {
3226                 report("Unknown run request");
3227                 return;
3228         }
3230         if (format_argv(&argv, req->argv, TRUE, FALSE))
3231                 open_external_viewer(argv, NULL);
3232         if (argv)
3233                 argv_free(argv);
3234         free(argv);
3237 /*
3238  * User request switch noodle
3239  */
3241 static int
3242 view_driver(struct view *view, enum request request)
3244         int i;
3246         if (request == REQ_NONE)
3247                 return TRUE;
3249         if (request > REQ_NONE) {
3250                 open_run_request(request);
3251                 view_request(view, REQ_REFRESH);
3252                 return TRUE;
3253         }
3255         request = view_request(view, request);
3256         if (request == REQ_NONE)
3257                 return TRUE;
3259         switch (request) {
3260         case REQ_MOVE_UP:
3261         case REQ_MOVE_DOWN:
3262         case REQ_MOVE_PAGE_UP:
3263         case REQ_MOVE_PAGE_DOWN:
3264         case REQ_MOVE_FIRST_LINE:
3265         case REQ_MOVE_LAST_LINE:
3266                 move_view(view, request);
3267                 break;
3269         case REQ_SCROLL_FIRST_COL:
3270         case REQ_SCROLL_LEFT:
3271         case REQ_SCROLL_RIGHT:
3272         case REQ_SCROLL_LINE_DOWN:
3273         case REQ_SCROLL_LINE_UP:
3274         case REQ_SCROLL_PAGE_DOWN:
3275         case REQ_SCROLL_PAGE_UP:
3276                 scroll_view(view, request);
3277                 break;
3279         case REQ_VIEW_BLAME:
3280                 if (!opt_file[0]) {
3281                         report("No file chosen, press %s to open tree view",
3282                                get_key(view->keymap, REQ_VIEW_TREE));
3283                         break;
3284                 }
3285                 open_view(view, request, OPEN_DEFAULT);
3286                 break;
3288         case REQ_VIEW_BLOB:
3289                 if (!ref_blob[0]) {
3290                         report("No file chosen, press %s to open tree view",
3291                                get_key(view->keymap, REQ_VIEW_TREE));
3292                         break;
3293                 }
3294                 open_view(view, request, OPEN_DEFAULT);
3295                 break;
3297         case REQ_VIEW_PAGER:
3298                 if (view == NULL) {
3299                         if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3300                                 die("Failed to open stdin");
3301                         open_view(view, request, OPEN_PREPARED);
3302                         break;
3303                 }
3305                 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3306                         report("No pager content, press %s to run command from prompt",
3307                                get_key(view->keymap, REQ_PROMPT));
3308                         break;
3309                 }
3310                 open_view(view, request, OPEN_DEFAULT);
3311                 break;
3313         case REQ_VIEW_STAGE:
3314                 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3315                         report("No stage content, press %s to open the status view and choose file",
3316                                get_key(view->keymap, REQ_VIEW_STATUS));
3317                         break;
3318                 }
3319                 open_view(view, request, OPEN_DEFAULT);
3320                 break;
3322         case REQ_VIEW_STATUS:
3323                 if (opt_is_inside_work_tree == FALSE) {
3324                         report("The status view requires a working tree");
3325                         break;
3326                 }
3327                 open_view(view, request, OPEN_DEFAULT);
3328                 break;
3330         case REQ_VIEW_MAIN:
3331         case REQ_VIEW_DIFF:
3332         case REQ_VIEW_LOG:
3333         case REQ_VIEW_TREE:
3334         case REQ_VIEW_HELP:
3335         case REQ_VIEW_BRANCH:
3336                 open_view(view, request, OPEN_DEFAULT);
3337                 break;
3339         case REQ_NEXT:
3340         case REQ_PREVIOUS:
3341                 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3343                 if (view->parent) {
3344                         int line;
3346                         view = view->parent;
3347                         line = view->lineno;
3348                         move_view(view, request);
3349                         if (view_is_displayed(view))
3350                                 update_view_title(view);
3351                         if (line != view->lineno)
3352                                 view_request(view, REQ_ENTER);
3353                 } else {
3354                         move_view(view, request);
3355                 }
3356                 break;
3358         case REQ_VIEW_NEXT:
3359         {
3360                 int nviews = displayed_views();
3361                 int next_view = (current_view + 1) % nviews;
3363                 if (next_view == current_view) {
3364                         report("Only one view is displayed");
3365                         break;
3366                 }
3368                 current_view = next_view;
3369                 /* Blur out the title of the previous view. */
3370                 update_view_title(view);
3371                 report("");
3372                 break;
3373         }
3374         case REQ_REFRESH:
3375                 report("Refreshing is not yet supported for the %s view", view->name);
3376                 break;
3378         case REQ_MAXIMIZE:
3379                 if (displayed_views() == 2)
3380                         maximize_view(view);
3381                 break;
3383         case REQ_OPTIONS:
3384         case REQ_TOGGLE_LINENO:
3385         case REQ_TOGGLE_DATE:
3386         case REQ_TOGGLE_AUTHOR:
3387         case REQ_TOGGLE_REV_GRAPH:
3388         case REQ_TOGGLE_REFS:
3389                 toggle_option(request);
3390                 break;
3392         case REQ_TOGGLE_SORT_FIELD:
3393         case REQ_TOGGLE_SORT_ORDER:
3394                 report("Sorting is not yet supported for the %s view", view->name);
3395                 break;
3397         case REQ_SEARCH:
3398         case REQ_SEARCH_BACK:
3399                 search_view(view, request);
3400                 break;
3402         case REQ_FIND_NEXT:
3403         case REQ_FIND_PREV:
3404                 find_next(view, request);
3405                 break;
3407         case REQ_STOP_LOADING:
3408                 foreach_view(view, i) {
3409                         if (view->pipe)
3410                                 report("Stopped loading the %s view", view->name),
3411                         end_update(view, TRUE);
3412                 }
3413                 break;
3415         case REQ_SHOW_VERSION:
3416                 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3417                 return TRUE;
3419         case REQ_SCREEN_REDRAW:
3420                 redraw_display(TRUE);
3421                 break;
3423         case REQ_EDIT:
3424                 report("Nothing to edit");
3425                 break;
3427         case REQ_ENTER:
3428                 report("Nothing to enter");
3429                 break;
3431         case REQ_VIEW_CLOSE:
3432                 /* XXX: Mark closed views by letting view->prev point to the
3433                  * view itself. Parents to closed view should never be
3434                  * followed. */
3435                 if (view->prev && view->prev != view) {
3436                         maximize_view(view->prev);
3437                         view->prev = view;
3438                         break;
3439                 }
3440                 /* Fall-through */
3441         case REQ_QUIT:
3442                 return FALSE;
3444         default:
3445                 report("Unknown key, press %s for help",
3446                        get_key(view->keymap, REQ_VIEW_HELP));
3447                 return TRUE;
3448         }
3450         return TRUE;
3454 /*
3455  * View backend utilities
3456  */
3458 enum sort_field {
3459         ORDERBY_NAME,
3460         ORDERBY_DATE,
3461         ORDERBY_AUTHOR,
3462 };
3464 struct sort_state {
3465         const enum sort_field *fields;
3466         size_t size, current;
3467         bool reverse;
3468 };
3470 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3471 #define get_sort_field(state) ((state).fields[(state).current])
3472 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3474 static void
3475 sort_view(struct view *view, enum request request, struct sort_state *state,
3476           int (*compare)(const void *, const void *))
3478         switch (request) {
3479         case REQ_TOGGLE_SORT_FIELD:
3480                 state->current = (state->current + 1) % state->size;
3481                 break;
3483         case REQ_TOGGLE_SORT_ORDER:
3484                 state->reverse = !state->reverse;
3485                 break;
3486         default:
3487                 die("Not a sort request");
3488         }
3490         qsort(view->line, view->lines, sizeof(*view->line), compare);
3491         redraw_view(view);
3494 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3496 /* Small author cache to reduce memory consumption. It uses binary
3497  * search to lookup or find place to position new entries. No entries
3498  * are ever freed. */
3499 static const char *
3500 get_author(const char *name)
3502         static const char **authors;
3503         static size_t authors_size;
3504         int from = 0, to = authors_size - 1;
3506         while (from <= to) {
3507                 size_t pos = (to + from) / 2;
3508                 int cmp = strcmp(name, authors[pos]);
3510                 if (!cmp)
3511                         return authors[pos];
3513                 if (cmp < 0)
3514                         to = pos - 1;
3515                 else
3516                         from = pos + 1;
3517         }
3519         if (!realloc_authors(&authors, authors_size, 1))
3520                 return NULL;
3521         name = strdup(name);
3522         if (!name)
3523                 return NULL;
3525         memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3526         authors[from] = name;
3527         authors_size++;
3529         return name;
3532 static void
3533 parse_timesec(struct time *time, const char *sec)
3535         time->sec = (time_t) atol(sec);
3538 static void
3539 parse_timezone(struct time *time, const char *zone)
3541         long tz;
3543         tz  = ('0' - zone[1]) * 60 * 60 * 10;
3544         tz += ('0' - zone[2]) * 60 * 60;
3545         tz += ('0' - zone[3]) * 60 * 10;
3546         tz += ('0' - zone[4]) * 60;
3548         if (zone[0] == '-')
3549                 tz = -tz;
3551         time->tz = tz;
3552         time->sec -= tz;
3555 /* Parse author lines where the name may be empty:
3556  *      author  <email@address.tld> 1138474660 +0100
3557  */
3558 static void
3559 parse_author_line(char *ident, const char **author, struct time *time)
3561         char *nameend = strchr(ident, '<');
3562         char *emailend = strchr(ident, '>');
3564         if (nameend && emailend)
3565                 *nameend = *emailend = 0;
3566         ident = chomp_string(ident);
3567         if (!*ident) {
3568                 if (nameend)
3569                         ident = chomp_string(nameend + 1);
3570                 if (!*ident)
3571                         ident = "Unknown";
3572         }
3574         *author = get_author(ident);
3576         /* Parse epoch and timezone */
3577         if (emailend && emailend[1] == ' ') {
3578                 char *secs = emailend + 2;
3579                 char *zone = strchr(secs, ' ');
3581                 parse_timesec(time, secs);
3583                 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3584                         parse_timezone(time, zone + 1);
3585         }
3588 /*
3589  * Pager backend
3590  */
3592 static bool
3593 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3595         if (opt_line_number && draw_lineno(view, lineno))
3596                 return TRUE;
3598         draw_text(view, line->type, line->data);
3599         return TRUE;
3602 static bool
3603 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3605         const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3606         char ref[SIZEOF_STR];
3608         if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3609                 return TRUE;
3611         /* This is the only fatal call, since it can "corrupt" the buffer. */
3612         if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3613                 return FALSE;
3615         return TRUE;
3618 static void
3619 add_pager_refs(struct view *view, struct line *line)
3621         char buf[SIZEOF_STR];
3622         char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3623         struct ref_list *list;
3624         size_t bufpos = 0, i;
3625         const char *sep = "Refs: ";
3626         bool is_tag = FALSE;
3628         assert(line->type == LINE_COMMIT);
3630         list = get_ref_list(commit_id);
3631         if (!list) {
3632                 if (view->type == VIEW_DIFF)
3633                         goto try_add_describe_ref;
3634                 return;
3635         }
3637         for (i = 0; i < list->size; i++) {
3638                 struct ref *ref = list->refs[i];
3639                 const char *fmt = ref->tag    ? "%s[%s]" :
3640                                   ref->remote ? "%s<%s>" : "%s%s";
3642                 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3643                         return;
3644                 sep = ", ";
3645                 if (ref->tag)
3646                         is_tag = TRUE;
3647         }
3649         if (!is_tag && view->type == VIEW_DIFF) {
3650 try_add_describe_ref:
3651                 /* Add <tag>-g<commit_id> "fake" reference. */
3652                 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3653                         return;
3654         }
3656         if (bufpos == 0)
3657                 return;
3659         add_line_text(view, buf, LINE_PP_REFS);
3662 static bool
3663 pager_read(struct view *view, char *data)
3665         struct line *line;
3667         if (!data)
3668                 return TRUE;
3670         line = add_line_text(view, data, get_line_type(data));
3671         if (!line)
3672                 return FALSE;
3674         if (line->type == LINE_COMMIT &&
3675             (view->type == VIEW_DIFF ||
3676              view->type == VIEW_LOG))
3677                 add_pager_refs(view, line);
3679         return TRUE;
3682 static enum request
3683 pager_request(struct view *view, enum request request, struct line *line)
3685         int split = 0;
3687         if (request != REQ_ENTER)
3688                 return request;
3690         if (line->type == LINE_COMMIT &&
3691            (view->type == VIEW_LOG ||
3692             view->type == VIEW_PAGER)) {
3693                 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3694                 split = 1;
3695         }
3697         /* Always scroll the view even if it was split. That way
3698          * you can use Enter to scroll through the log view and
3699          * split open each commit diff. */
3700         scroll_view(view, REQ_SCROLL_LINE_DOWN);
3702         /* FIXME: A minor workaround. Scrolling the view will call report("")
3703          * but if we are scrolling a non-current view this won't properly
3704          * update the view title. */
3705         if (split)
3706                 update_view_title(view);
3708         return REQ_NONE;
3711 static bool
3712 pager_grep(struct view *view, struct line *line)
3714         const char *text[] = { line->data, NULL };
3716         return grep_text(view, text);
3719 static void
3720 pager_select(struct view *view, struct line *line)
3722         if (line->type == LINE_COMMIT) {
3723                 char *text = (char *)line->data + STRING_SIZE("commit ");
3725                 if (view->type != VIEW_PAGER)
3726                         string_copy_rev(view->ref, text);
3727                 string_copy_rev(ref_commit, text);
3728         }
3731 static struct view_ops pager_ops = {
3732         "line",
3733         NULL,
3734         NULL,
3735         pager_read,
3736         pager_draw,
3737         pager_request,
3738         pager_grep,
3739         pager_select,
3740 };
3742 static const char *log_argv[SIZEOF_ARG] = {
3743         "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3744 };
3746 static enum request
3747 log_request(struct view *view, enum request request, struct line *line)
3749         switch (request) {
3750         case REQ_REFRESH:
3751                 load_refs();
3752                 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3753                 return REQ_NONE;
3754         default:
3755                 return pager_request(view, request, line);
3756         }
3759 static struct view_ops log_ops = {
3760         "line",
3761         log_argv,
3762         NULL,
3763         pager_read,
3764         pager_draw,
3765         log_request,
3766         pager_grep,
3767         pager_select,
3768 };
3770 static const char *diff_argv[SIZEOF_ARG] = {
3771         "git", "show", "--pretty=fuller", "--no-color", "--root",
3772                 "--patch-with-stat", "--find-copies-harder", "-C",
3773                 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3774 };
3776 static bool
3777 diff_read(struct view *view, char *data)
3779         if (!data) {
3780                 /* Fall back to retry if no diff will be shown. */
3781                 if (view->lines == 0 && opt_file_argv) {
3782                         int pos = argv_size(view->argv)
3783                                 - argv_size(opt_file_argv) - 1;
3785                         if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3786                                 for (; view->argv[pos]; pos++) {
3787                                         free((void *) view->argv[pos]);
3788                                         view->argv[pos] = NULL;
3789                                 }
3791                                 if (view->pipe)
3792                                         io_done(view->pipe);
3793                                 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3794                                         return FALSE;
3795                         }
3796                 }
3797                 return TRUE;
3798         }
3800         return pager_read(view, data);
3803 static struct view_ops diff_ops = {
3804         "line",
3805         diff_argv,
3806         NULL,
3807         diff_read,
3808         pager_draw,
3809         pager_request,
3810         pager_grep,
3811         pager_select,
3812 };
3814 /*
3815  * Help backend
3816  */
3818 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3820 static bool
3821 help_open_keymap_title(struct view *view, enum keymap keymap)
3823         struct line *line;
3825         line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3826                                help_keymap_hidden[keymap] ? '+' : '-',
3827                                enum_name(keymap_table[keymap]));
3828         if (line)
3829                 line->other = keymap;
3831         return help_keymap_hidden[keymap];
3834 static void
3835 help_open_keymap(struct view *view, enum keymap keymap)
3837         const char *group = NULL;
3838         char buf[SIZEOF_STR];
3839         size_t bufpos;
3840         bool add_title = TRUE;
3841         int i;
3843         for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3844                 const char *key = NULL;
3846                 if (req_info[i].request == REQ_NONE)
3847                         continue;
3849                 if (!req_info[i].request) {
3850                         group = req_info[i].help;
3851                         continue;
3852                 }
3854                 key = get_keys(keymap, req_info[i].request, TRUE);
3855                 if (!key || !*key)
3856                         continue;
3858                 if (add_title && help_open_keymap_title(view, keymap))
3859                         return;
3860                 add_title = FALSE;
3862                 if (group) {
3863                         add_line_text(view, group, LINE_HELP_GROUP);
3864                         group = NULL;
3865                 }
3867                 add_line_format(view, LINE_DEFAULT, "    %-25s %-20s %s", key,
3868                                 enum_name(req_info[i]), req_info[i].help);
3869         }
3871         group = "External commands:";
3873         for (i = 0; i < run_requests; i++) {
3874                 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3875                 const char *key;
3876                 int argc;
3878                 if (!req || req->keymap != keymap)
3879                         continue;
3881                 key = get_key_name(req->key);
3882                 if (!*key)
3883                         key = "(no key defined)";
3885                 if (add_title && help_open_keymap_title(view, keymap))
3886                         return;
3887                 if (group) {
3888                         add_line_text(view, group, LINE_HELP_GROUP);
3889                         group = NULL;
3890                 }
3892                 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3893                         if (!string_format_from(buf, &bufpos, "%s%s",
3894                                                 argc ? " " : "", req->argv[argc]))
3895                                 return;
3897                 add_line_format(view, LINE_DEFAULT, "    %-25s `%s`", key, buf);
3898         }
3901 static bool
3902 help_open(struct view *view)
3904         enum keymap keymap;
3906         reset_view(view);
3907         add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3908         add_line_text(view, "", LINE_DEFAULT);
3910         for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3911                 help_open_keymap(view, keymap);
3913         return TRUE;
3916 static enum request
3917 help_request(struct view *view, enum request request, struct line *line)
3919         switch (request) {
3920         case REQ_ENTER:
3921                 if (line->type == LINE_HELP_KEYMAP) {
3922                         help_keymap_hidden[line->other] =
3923                                 !help_keymap_hidden[line->other];
3924                         view->p_restore = TRUE;
3925                         open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3926                 }
3928                 return REQ_NONE;
3929         default:
3930                 return pager_request(view, request, line);
3931         }
3934 static struct view_ops help_ops = {
3935         "line",
3936         NULL,
3937         help_open,
3938         NULL,
3939         pager_draw,
3940         help_request,
3941         pager_grep,
3942         pager_select,
3943 };
3946 /*
3947  * Tree backend
3948  */
3950 struct tree_stack_entry {
3951         struct tree_stack_entry *prev;  /* Entry below this in the stack */
3952         unsigned long lineno;           /* Line number to restore */
3953         char *name;                     /* Position of name in opt_path */
3954 };
3956 /* The top of the path stack. */
3957 static struct tree_stack_entry *tree_stack = NULL;
3958 unsigned long tree_lineno = 0;
3960 static void
3961 pop_tree_stack_entry(void)
3963         struct tree_stack_entry *entry = tree_stack;
3965         tree_lineno = entry->lineno;
3966         entry->name[0] = 0;
3967         tree_stack = entry->prev;
3968         free(entry);
3971 static void
3972 push_tree_stack_entry(const char *name, unsigned long lineno)
3974         struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3975         size_t pathlen = strlen(opt_path);
3977         if (!entry)
3978                 return;
3980         entry->prev = tree_stack;
3981         entry->name = opt_path + pathlen;
3982         tree_stack = entry;
3984         if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3985                 pop_tree_stack_entry();
3986                 return;
3987         }
3989         /* Move the current line to the first tree entry. */
3990         tree_lineno = 1;
3991         entry->lineno = lineno;
3994 /* Parse output from git-ls-tree(1):
3995  *
3996  * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3997  */
3999 #define SIZEOF_TREE_ATTR \
4000         STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4002 #define SIZEOF_TREE_MODE \
4003         STRING_SIZE("100644 ")
4005 #define TREE_ID_OFFSET \
4006         STRING_SIZE("100644 blob ")
4008 struct tree_entry {
4009         char id[SIZEOF_REV];
4010         mode_t mode;
4011         struct time time;               /* Date from the author ident. */
4012         const char *author;             /* Author of the commit. */
4013         char name[1];
4014 };
4016 static const char *
4017 tree_path(const struct line *line)
4019         return ((struct tree_entry *) line->data)->name;
4022 static int
4023 tree_compare_entry(const struct line *line1, const struct line *line2)
4025         if (line1->type != line2->type)
4026                 return line1->type == LINE_TREE_DIR ? -1 : 1;
4027         return strcmp(tree_path(line1), tree_path(line2));
4030 static const enum sort_field tree_sort_fields[] = {
4031         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4032 };
4033 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4035 static int
4036 tree_compare(const void *l1, const void *l2)
4038         const struct line *line1 = (const struct line *) l1;
4039         const struct line *line2 = (const struct line *) l2;
4040         const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4041         const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4043         if (line1->type == LINE_TREE_HEAD)
4044                 return -1;
4045         if (line2->type == LINE_TREE_HEAD)
4046                 return 1;
4048         switch (get_sort_field(tree_sort_state)) {
4049         case ORDERBY_DATE:
4050                 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4052         case ORDERBY_AUTHOR:
4053                 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
4055         case ORDERBY_NAME:
4056         default:
4057                 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4058         }
4062 static struct line *
4063 tree_entry(struct view *view, enum line_type type, const char *path,
4064            const char *mode, const char *id)
4066         struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4067         struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4069         if (!entry || !line) {
4070                 free(entry);
4071                 return NULL;
4072         }
4074         strncpy(entry->name, path, strlen(path));
4075         if (mode)
4076                 entry->mode = strtoul(mode, NULL, 8);
4077         if (id)
4078                 string_copy_rev(entry->id, id);
4080         return line;
4083 static bool
4084 tree_read_date(struct view *view, char *text, bool *read_date)
4086         static const char *author_name;
4087         static struct time author_time;
4089         if (!text && *read_date) {
4090                 *read_date = FALSE;
4091                 return TRUE;
4093         } else if (!text) {
4094                 char *path = *opt_path ? opt_path : ".";
4095                 /* Find next entry to process */
4096                 const char *log_file[] = {
4097                         "git", "log", "--no-color", "--pretty=raw",
4098                                 "--cc", "--raw", view->id, "--", path, NULL
4099                 };
4101                 if (!view->lines) {
4102                         tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4103                         report("Tree is empty");
4104                         return TRUE;
4105                 }
4107                 if (!start_update(view, log_file, opt_cdup)) {
4108                         report("Failed to load tree data");
4109                         return TRUE;
4110                 }
4112                 *read_date = TRUE;
4113                 return FALSE;
4115         } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4116                 parse_author_line(text + STRING_SIZE("author "),
4117                                   &author_name, &author_time);
4119         } else if (*text == ':') {
4120                 char *pos;
4121                 size_t annotated = 1;
4122                 size_t i;
4124                 pos = strchr(text, '\t');
4125                 if (!pos)
4126                         return TRUE;
4127                 text = pos + 1;
4128                 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4129                         text += strlen(opt_path);
4130                 pos = strchr(text, '/');
4131                 if (pos)
4132                         *pos = 0;
4134                 for (i = 1; i < view->lines; i++) {
4135                         struct line *line = &view->line[i];
4136                         struct tree_entry *entry = line->data;
4138                         annotated += !!entry->author;
4139                         if (entry->author || strcmp(entry->name, text))
4140                                 continue;
4142                         entry->author = author_name;
4143                         entry->time = author_time;
4144                         line->dirty = 1;
4145                         break;
4146                 }
4148                 if (annotated == view->lines)
4149                         io_kill(view->pipe);
4150         }
4151         return TRUE;
4154 static bool
4155 tree_read(struct view *view, char *text)
4157         static bool read_date = FALSE;
4158         struct tree_entry *data;
4159         struct line *entry, *line;
4160         enum line_type type;
4161         size_t textlen = text ? strlen(text) : 0;
4162         char *path = text + SIZEOF_TREE_ATTR;
4164         if (read_date || !text)
4165                 return tree_read_date(view, text, &read_date);
4167         if (textlen <= SIZEOF_TREE_ATTR)
4168                 return FALSE;
4169         if (view->lines == 0 &&
4170             !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4171                 return FALSE;
4173         /* Strip the path part ... */
4174         if (*opt_path) {
4175                 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4176                 size_t striplen = strlen(opt_path);
4178                 if (pathlen > striplen)
4179                         memmove(path, path + striplen,
4180                                 pathlen - striplen + 1);
4182                 /* Insert "link" to parent directory. */
4183                 if (view->lines == 1 &&
4184                     !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4185                         return FALSE;
4186         }
4188         type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4189         entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4190         if (!entry)
4191                 return FALSE;
4192         data = entry->data;
4194         /* Skip "Directory ..." and ".." line. */
4195         for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4196                 if (tree_compare_entry(line, entry) <= 0)
4197                         continue;
4199                 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4201                 line->data = data;
4202                 line->type = type;
4203                 for (; line <= entry; line++)
4204                         line->dirty = line->cleareol = 1;
4205                 return TRUE;
4206         }
4208         if (tree_lineno > view->lineno) {
4209                 view->lineno = tree_lineno;
4210                 tree_lineno = 0;
4211         }
4213         return TRUE;
4216 static bool
4217 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4219         struct tree_entry *entry = line->data;
4221         if (line->type == LINE_TREE_HEAD) {
4222                 if (draw_text(view, line->type, "Directory path /"))
4223                         return TRUE;
4224         } else {
4225                 if (draw_mode(view, entry->mode))
4226                         return TRUE;
4228                 if (opt_author && draw_author(view, entry->author))
4229                         return TRUE;
4231                 if (opt_date && draw_date(view, &entry->time))
4232                         return TRUE;
4233         }
4235         draw_text(view, line->type, entry->name);
4236         return TRUE;
4239 static void
4240 open_blob_editor(const char *id)
4242         const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4243         char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4244         int fd = mkstemp(file);
4246         if (fd == -1)
4247                 report("Failed to create temporary file");
4248         else if (!io_run_append(blob_argv, fd))
4249                 report("Failed to save blob data to file");
4250         else
4251                 open_editor(file);
4252         if (fd != -1)
4253                 unlink(file);
4256 static enum request
4257 tree_request(struct view *view, enum request request, struct line *line)
4259         enum open_flags flags;
4260         struct tree_entry *entry = line->data;
4262         switch (request) {
4263         case REQ_VIEW_BLAME:
4264                 if (line->type != LINE_TREE_FILE) {
4265                         report("Blame only supported for files");
4266                         return REQ_NONE;
4267                 }
4269                 string_copy(opt_ref, view->vid);
4270                 return request;
4272         case REQ_EDIT:
4273                 if (line->type != LINE_TREE_FILE) {
4274                         report("Edit only supported for files");
4275                 } else if (!is_head_commit(view->vid)) {
4276                         open_blob_editor(entry->id);
4277                 } else {
4278                         open_editor(opt_file);
4279                 }
4280                 return REQ_NONE;
4282         case REQ_TOGGLE_SORT_FIELD:
4283         case REQ_TOGGLE_SORT_ORDER:
4284                 sort_view(view, request, &tree_sort_state, tree_compare);
4285                 return REQ_NONE;
4287         case REQ_PARENT:
4288                 if (!*opt_path) {
4289                         /* quit view if at top of tree */
4290                         return REQ_VIEW_CLOSE;
4291                 }
4292                 /* fake 'cd  ..' */
4293                 line = &view->line[1];
4294                 break;
4296         case REQ_ENTER:
4297                 break;
4299         default:
4300                 return request;
4301         }
4303         /* Cleanup the stack if the tree view is at a different tree. */
4304         while (!*opt_path && tree_stack)
4305                 pop_tree_stack_entry();
4307         switch (line->type) {
4308         case LINE_TREE_DIR:
4309                 /* Depending on whether it is a subdirectory or parent link
4310                  * mangle the path buffer. */
4311                 if (line == &view->line[1] && *opt_path) {
4312                         pop_tree_stack_entry();
4314                 } else {
4315                         const char *basename = tree_path(line);
4317                         push_tree_stack_entry(basename, view->lineno);
4318                 }
4320                 /* Trees and subtrees share the same ID, so they are not not
4321                  * unique like blobs. */
4322                 flags = OPEN_RELOAD;
4323                 request = REQ_VIEW_TREE;
4324                 break;
4326         case LINE_TREE_FILE:
4327                 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4328                 request = REQ_VIEW_BLOB;
4329                 break;
4331         default:
4332                 return REQ_NONE;
4333         }
4335         open_view(view, request, flags);
4336         if (request == REQ_VIEW_TREE)
4337                 view->lineno = tree_lineno;
4339         return REQ_NONE;
4342 static bool
4343 tree_grep(struct view *view, struct line *line)
4345         struct tree_entry *entry = line->data;
4346         const char *text[] = {
4347                 entry->name,
4348                 opt_author ? entry->author : "",
4349                 mkdate(&entry->time, opt_date),
4350                 NULL
4351         };
4353         return grep_text(view, text);
4356 static void
4357 tree_select(struct view *view, struct line *line)
4359         struct tree_entry *entry = line->data;
4361         if (line->type == LINE_TREE_FILE) {
4362                 string_copy_rev(ref_blob, entry->id);
4363                 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4365         } else if (line->type != LINE_TREE_DIR) {
4366                 return;
4367         }
4369         string_copy_rev(view->ref, entry->id);
4372 static bool
4373 tree_prepare(struct view *view)
4375         if (view->lines == 0 && opt_prefix[0]) {
4376                 char *pos = opt_prefix;
4378                 while (pos && *pos) {
4379                         char *end = strchr(pos, '/');
4381                         if (end)
4382                                 *end = 0;
4383                         push_tree_stack_entry(pos, 0);
4384                         pos = end;
4385                         if (end) {
4386                                 *end = '/';
4387                                 pos++;
4388                         }
4389                 }
4391         } else if (strcmp(view->vid, view->id)) {
4392                 opt_path[0] = 0;
4393         }
4395         return prepare_io(view, opt_cdup, view->ops->argv, TRUE);
4398 static const char *tree_argv[SIZEOF_ARG] = {
4399         "git", "ls-tree", "%(commit)", "%(directory)", NULL
4400 };
4402 static struct view_ops tree_ops = {
4403         "file",
4404         tree_argv,
4405         NULL,
4406         tree_read,
4407         tree_draw,
4408         tree_request,
4409         tree_grep,
4410         tree_select,
4411         tree_prepare,
4412 };
4414 static bool
4415 blob_read(struct view *view, char *line)
4417         if (!line)
4418                 return TRUE;
4419         return add_line_text(view, line, LINE_DEFAULT) != NULL;
4422 static enum request
4423 blob_request(struct view *view, enum request request, struct line *line)
4425         switch (request) {
4426         case REQ_EDIT:
4427                 open_blob_editor(view->vid);
4428                 return REQ_NONE;
4429         default:
4430                 return pager_request(view, request, line);
4431         }
4434 static const char *blob_argv[SIZEOF_ARG] = {
4435         "git", "cat-file", "blob", "%(blob)", NULL
4436 };
4438 static struct view_ops blob_ops = {
4439         "line",
4440         blob_argv,
4441         NULL,
4442         blob_read,
4443         pager_draw,
4444         blob_request,
4445         pager_grep,
4446         pager_select,
4447 };
4449 /*
4450  * Blame backend
4451  *
4452  * Loading the blame view is a two phase job:
4453  *
4454  *  1. File content is read either using opt_file from the
4455  *     filesystem or using git-cat-file.
4456  *  2. Then blame information is incrementally added by
4457  *     reading output from git-blame.
4458  */
4460 struct blame_commit {
4461         char id[SIZEOF_REV];            /* SHA1 ID. */
4462         char title[128];                /* First line of the commit message. */
4463         const char *author;             /* Author of the commit. */
4464         struct time time;               /* Date from the author ident. */
4465         char filename[128];             /* Name of file. */
4466         char parent_id[SIZEOF_REV];     /* Parent/previous SHA1 ID. */
4467         char parent_filename[128];      /* Parent/previous name of file. */
4468 };
4470 struct blame {
4471         struct blame_commit *commit;
4472         unsigned long lineno;
4473         char text[1];
4474 };
4476 static bool
4477 blame_open(struct view *view)
4479         char path[SIZEOF_STR];
4480         size_t i;
4482         if (!view->prev && *opt_prefix) {
4483                 string_copy(path, opt_file);
4484                 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4485                         return FALSE;
4486         }
4488         if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4489                 const char *blame_cat_file_argv[] = {
4490                         "git", "cat-file", "blob", path, NULL
4491                 };
4493                 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4494                     !start_update(view, blame_cat_file_argv, opt_cdup))
4495                         return FALSE;
4496         }
4498         /* First pass: remove multiple references to the same commit. */
4499         for (i = 0; i < view->lines; i++) {
4500                 struct blame *blame = view->line[i].data;
4502                 if (blame->commit && blame->commit->id[0])
4503                         blame->commit->id[0] = 0;
4504                 else
4505                         blame->commit = NULL;
4506         }
4508         /* Second pass: free existing references. */
4509         for (i = 0; i < view->lines; i++) {
4510                 struct blame *blame = view->line[i].data;
4512                 if (blame->commit)
4513                         free(blame->commit);
4514         }
4516         setup_update(view, opt_file);
4517         string_format(view->ref, "%s ...", opt_file);
4519         return TRUE;
4522 static struct blame_commit *
4523 get_blame_commit(struct view *view, const char *id)
4525         size_t i;
4527         for (i = 0; i < view->lines; i++) {
4528                 struct blame *blame = view->line[i].data;
4530                 if (!blame->commit)
4531                         continue;
4533                 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4534                         return blame->commit;
4535         }
4537         {
4538                 struct blame_commit *commit = calloc(1, sizeof(*commit));
4540                 if (commit)
4541                         string_ncopy(commit->id, id, SIZEOF_REV);
4542                 return commit;
4543         }
4546 static bool
4547 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4549         const char *pos = *posref;
4551         *posref = NULL;
4552         pos = strchr(pos + 1, ' ');
4553         if (!pos || !isdigit(pos[1]))
4554                 return FALSE;
4555         *number = atoi(pos + 1);
4556         if (*number < min || *number > max)
4557                 return FALSE;
4559         *posref = pos;
4560         return TRUE;
4563 static struct blame_commit *
4564 parse_blame_commit(struct view *view, const char *text, int *blamed)
4566         struct blame_commit *commit;
4567         struct blame *blame;
4568         const char *pos = text + SIZEOF_REV - 2;
4569         size_t orig_lineno = 0;
4570         size_t lineno;
4571         size_t group;
4573         if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4574                 return NULL;
4576         if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4577             !parse_number(&pos, &lineno, 1, view->lines) ||
4578             !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4579                 return NULL;
4581         commit = get_blame_commit(view, text);
4582         if (!commit)
4583                 return NULL;
4585         *blamed += group;
4586         while (group--) {
4587                 struct line *line = &view->line[lineno + group - 1];
4589                 blame = line->data;
4590                 blame->commit = commit;
4591                 blame->lineno = orig_lineno + group - 1;
4592                 line->dirty = 1;
4593         }
4595         return commit;
4598 static bool
4599 blame_read_file(struct view *view, const char *line, bool *read_file)
4601         if (!line) {
4602                 const char *blame_argv[] = {
4603                         "git", "blame", "--incremental",
4604                                 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4605                 };
4607                 if (view->lines == 0 && !view->prev)
4608                         die("No blame exist for %s", view->vid);
4610                 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4611                         report("Failed to load blame data");
4612                         return TRUE;
4613                 }
4615                 *read_file = FALSE;
4616                 return FALSE;
4618         } else {
4619                 size_t linelen = strlen(line);
4620                 struct blame *blame = malloc(sizeof(*blame) + linelen);
4622                 if (!blame)
4623                         return FALSE;
4625                 blame->commit = NULL;
4626                 strncpy(blame->text, line, linelen);
4627                 blame->text[linelen] = 0;
4628                 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4629         }
4632 static bool
4633 match_blame_header(const char *name, char **line)
4635         size_t namelen = strlen(name);
4636         bool matched = !strncmp(name, *line, namelen);
4638         if (matched)
4639                 *line += namelen;
4641         return matched;
4644 static bool
4645 blame_read(struct view *view, char *line)
4647         static struct blame_commit *commit = NULL;
4648         static int blamed = 0;
4649         static bool read_file = TRUE;
4651         if (read_file)
4652                 return blame_read_file(view, line, &read_file);
4654         if (!line) {
4655                 /* Reset all! */
4656                 commit = NULL;
4657                 blamed = 0;
4658                 read_file = TRUE;
4659                 string_format(view->ref, "%s", view->vid);
4660                 if (view_is_displayed(view)) {
4661                         update_view_title(view);
4662                         redraw_view_from(view, 0);
4663                 }
4664                 return TRUE;
4665         }
4667         if (!commit) {
4668                 commit = parse_blame_commit(view, line, &blamed);
4669                 string_format(view->ref, "%s %2d%%", view->vid,
4670                               view->lines ? blamed * 100 / view->lines : 0);
4672         } else if (match_blame_header("author ", &line)) {
4673                 commit->author = get_author(line);
4675         } else if (match_blame_header("author-time ", &line)) {
4676                 parse_timesec(&commit->time, line);
4678         } else if (match_blame_header("author-tz ", &line)) {
4679                 parse_timezone(&commit->time, line);
4681         } else if (match_blame_header("summary ", &line)) {
4682                 string_ncopy(commit->title, line, strlen(line));
4684         } else if (match_blame_header("previous ", &line)) {
4685                 if (strlen(line) <= SIZEOF_REV)
4686                         return FALSE;
4687                 string_copy_rev(commit->parent_id, line);
4688                 line += SIZEOF_REV;
4689                 string_ncopy(commit->parent_filename, line, strlen(line));
4691         } else if (match_blame_header("filename ", &line)) {
4692                 string_ncopy(commit->filename, line, strlen(line));
4693                 commit = NULL;
4694         }
4696         return TRUE;
4699 static bool
4700 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4702         struct blame *blame = line->data;
4703         struct time *time = NULL;
4704         const char *id = NULL, *author = NULL;
4706         if (blame->commit && *blame->commit->filename) {
4707                 id = blame->commit->id;
4708                 author = blame->commit->author;
4709                 time = &blame->commit->time;
4710         }
4712         if (opt_date && draw_date(view, time))
4713                 return TRUE;
4715         if (opt_author && draw_author(view, author))
4716                 return TRUE;
4718         if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4719                 return TRUE;
4721         if (draw_lineno(view, lineno))
4722                 return TRUE;
4724         draw_text(view, LINE_DEFAULT, blame->text);
4725         return TRUE;
4728 static bool
4729 check_blame_commit(struct blame *blame, bool check_null_id)
4731         if (!blame->commit)
4732                 report("Commit data not loaded yet");
4733         else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4734                 report("No commit exist for the selected line");
4735         else
4736                 return TRUE;
4737         return FALSE;
4740 static void
4741 setup_blame_parent_line(struct view *view, struct blame *blame)
4743         char from[SIZEOF_REF + SIZEOF_STR];
4744         char to[SIZEOF_REF + SIZEOF_STR];
4745         const char *diff_tree_argv[] = {
4746                 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4747                         "-U0", from, to, "--", NULL
4748         };
4749         struct io io;
4750         int parent_lineno = -1;
4751         int blamed_lineno = -1;
4752         char *line;
4754         if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4755             !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4756             !io_run(&io, IO_RD, NULL, diff_tree_argv))
4757                 return;
4759         while ((line = io_get(&io, '\n', TRUE))) {
4760                 if (*line == '@') {
4761                         char *pos = strchr(line, '+');
4763                         parent_lineno = atoi(line + 4);
4764                         if (pos)
4765                                 blamed_lineno = atoi(pos + 1);
4767                 } else if (*line == '+' && parent_lineno != -1) {
4768                         if (blame->lineno == blamed_lineno - 1 &&
4769                             !strcmp(blame->text, line + 1)) {
4770                                 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4771                                 break;
4772                         }
4773                         blamed_lineno++;
4774                 }
4775         }
4777         io_done(&io);
4780 static enum request
4781 blame_request(struct view *view, enum request request, struct line *line)
4783         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4784         struct blame *blame = line->data;
4786         switch (request) {
4787         case REQ_VIEW_BLAME:
4788                 if (check_blame_commit(blame, TRUE)) {
4789                         string_copy(opt_ref, blame->commit->id);
4790                         string_copy(opt_file, blame->commit->filename);
4791                         if (blame->lineno)
4792                                 view->lineno = blame->lineno;
4793                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4794                 }
4795                 break;
4797         case REQ_PARENT:
4798                 if (!check_blame_commit(blame, TRUE))
4799                         break;
4800                 if (!*blame->commit->parent_id) {
4801                         report("The selected commit has no parents");
4802                 } else {
4803                         string_copy_rev(opt_ref, blame->commit->parent_id);
4804                         string_copy(opt_file, blame->commit->parent_filename);
4805                         setup_blame_parent_line(view, blame);
4806                         open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4807                 }
4808                 break;
4810         case REQ_ENTER:
4811                 if (!check_blame_commit(blame, FALSE))
4812                         break;
4814                 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4815                     !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4816                         break;
4818                 if (!strcmp(blame->commit->id, NULL_ID)) {
4819                         struct view *diff = VIEW(REQ_VIEW_DIFF);
4820                         const char *diff_index_argv[] = {
4821                                 "git", "diff-index", "--root", "--patch-with-stat",
4822                                         "-C", "-M", "HEAD", "--", view->vid, NULL
4823                         };
4825                         if (!*blame->commit->parent_id) {
4826                                 diff_index_argv[1] = "diff";
4827                                 diff_index_argv[2] = "--no-color";
4828                                 diff_index_argv[6] = "--";
4829                                 diff_index_argv[7] = "/dev/null";
4830                         }
4832                         if (!prepare_update(diff, diff_index_argv, NULL)) {
4833                                 report("Failed to allocate diff command");
4834                                 break;
4835                         }
4836                         flags |= OPEN_PREPARED;
4837                 }
4839                 open_view(view, REQ_VIEW_DIFF, flags);
4840                 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4841                         string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4842                 break;
4844         default:
4845                 return request;
4846         }
4848         return REQ_NONE;
4851 static bool
4852 blame_grep(struct view *view, struct line *line)
4854         struct blame *blame = line->data;
4855         struct blame_commit *commit = blame->commit;
4856         const char *text[] = {
4857                 blame->text,
4858                 commit ? commit->title : "",
4859                 commit ? commit->id : "",
4860                 commit && opt_author ? commit->author : "",
4861                 commit ? mkdate(&commit->time, opt_date) : "",
4862                 NULL
4863         };
4865         return grep_text(view, text);
4868 static void
4869 blame_select(struct view *view, struct line *line)
4871         struct blame *blame = line->data;
4872         struct blame_commit *commit = blame->commit;
4874         if (!commit)
4875                 return;
4877         if (!strcmp(commit->id, NULL_ID))
4878                 string_ncopy(ref_commit, "HEAD", 4);
4879         else
4880                 string_copy_rev(ref_commit, commit->id);
4883 static struct view_ops blame_ops = {
4884         "line",
4885         NULL,
4886         blame_open,
4887         blame_read,
4888         blame_draw,
4889         blame_request,
4890         blame_grep,
4891         blame_select,
4892 };
4894 /*
4895  * Branch backend
4896  */
4898 struct branch {
4899         const char *author;             /* Author of the last commit. */
4900         struct time time;               /* Date of the last activity. */
4901         const struct ref *ref;          /* Name and commit ID information. */
4902 };
4904 static const struct ref branch_all;
4906 static const enum sort_field branch_sort_fields[] = {
4907         ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4908 };
4909 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4911 static int
4912 branch_compare(const void *l1, const void *l2)
4914         const struct branch *branch1 = ((const struct line *) l1)->data;
4915         const struct branch *branch2 = ((const struct line *) l2)->data;
4917         switch (get_sort_field(branch_sort_state)) {
4918         case ORDERBY_DATE:
4919                 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4921         case ORDERBY_AUTHOR:
4922                 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4924         case ORDERBY_NAME:
4925         default:
4926                 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4927         }
4930 static bool
4931 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4933         struct branch *branch = line->data;
4934         enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4936         if (opt_date && draw_date(view, &branch->time))
4937                 return TRUE;
4939         if (opt_author && draw_author(view, branch->author))
4940                 return TRUE;
4942         draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4943         return TRUE;
4946 static enum request
4947 branch_request(struct view *view, enum request request, struct line *line)
4949         struct branch *branch = line->data;
4951         switch (request) {
4952         case REQ_REFRESH:
4953                 load_refs();
4954                 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4955                 return REQ_NONE;
4957         case REQ_TOGGLE_SORT_FIELD:
4958         case REQ_TOGGLE_SORT_ORDER:
4959                 sort_view(view, request, &branch_sort_state, branch_compare);
4960                 return REQ_NONE;
4962         case REQ_ENTER:
4963         {
4964                 const struct ref *ref = branch->ref;
4965                 const char *all_branches_argv[] = {
4966                         "git", "log", "--no-color", "--pretty=raw", "--parents",
4967                               "--topo-order",
4968                               ref == &branch_all ? "--all" : ref->name, NULL
4969                 };
4970                 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4972                 if (!prepare_update(main_view, all_branches_argv, NULL))
4973                         report("Failed to load view of all branches");
4974                 else
4975                         open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4976                 return REQ_NONE;
4977         }
4978         default:
4979                 return request;
4980         }
4983 static bool
4984 branch_read(struct view *view, char *line)
4986         static char id[SIZEOF_REV];
4987         struct branch *reference;
4988         size_t i;
4990         if (!line)
4991                 return TRUE;
4993         switch (get_line_type(line)) {
4994         case LINE_COMMIT:
4995                 string_copy_rev(id, line + STRING_SIZE("commit "));
4996                 return TRUE;
4998         case LINE_AUTHOR:
4999                 for (i = 0, reference = NULL; i < view->lines; i++) {
5000                         struct branch *branch = view->line[i].data;
5002                         if (strcmp(branch->ref->id, id))
5003                                 continue;
5005                         view->line[i].dirty = TRUE;
5006                         if (reference) {
5007                                 branch->author = reference->author;
5008                                 branch->time = reference->time;
5009                                 continue;
5010                         }
5012                         parse_author_line(line + STRING_SIZE("author "),
5013                                           &branch->author, &branch->time);
5014                         reference = branch;
5015                 }
5016                 return TRUE;
5018         default:
5019                 return TRUE;
5020         }
5024 static bool
5025 branch_open_visitor(void *data, const struct ref *ref)
5027         struct view *view = data;
5028         struct branch *branch;
5030         if (ref->tag || ref->ltag || ref->remote)
5031                 return TRUE;
5033         branch = calloc(1, sizeof(*branch));
5034         if (!branch)
5035                 return FALSE;
5037         branch->ref = ref;
5038         return !!add_line_data(view, branch, LINE_DEFAULT);
5041 static bool
5042 branch_open(struct view *view)
5044         const char *branch_log[] = {
5045                 "git", "log", "--no-color", "--pretty=raw",
5046                         "--simplify-by-decoration", "--all", NULL
5047         };
5049         if (!start_update(view, branch_log, NULL)) {
5050                 report("Failed to load branch data");
5051                 return TRUE;
5052         }
5054         setup_update(view, view->id);
5055         branch_open_visitor(view, &branch_all);
5056         foreach_ref(branch_open_visitor, view);
5057         view->p_restore = TRUE;
5059         return TRUE;
5062 static bool
5063 branch_grep(struct view *view, struct line *line)
5065         struct branch *branch = line->data;
5066         const char *text[] = {
5067                 branch->ref->name,
5068                 branch->author,
5069                 NULL
5070         };
5072         return grep_text(view, text);
5075 static void
5076 branch_select(struct view *view, struct line *line)
5078         struct branch *branch = line->data;
5080         string_copy_rev(view->ref, branch->ref->id);
5081         string_copy_rev(ref_commit, branch->ref->id);
5082         string_copy_rev(ref_head, branch->ref->id);
5083         string_copy_rev(ref_branch, branch->ref->name);
5086 static struct view_ops branch_ops = {
5087         "branch",
5088         NULL,
5089         branch_open,
5090         branch_read,
5091         branch_draw,
5092         branch_request,
5093         branch_grep,
5094         branch_select,
5095 };
5097 /*
5098  * Status backend
5099  */
5101 struct status {
5102         char status;
5103         struct {
5104                 mode_t mode;
5105                 char rev[SIZEOF_REV];
5106                 char name[SIZEOF_STR];
5107         } old;
5108         struct {
5109                 mode_t mode;
5110                 char rev[SIZEOF_REV];
5111                 char name[SIZEOF_STR];
5112         } new;
5113 };
5115 static char status_onbranch[SIZEOF_STR];
5116 static struct status stage_status;
5117 static enum line_type stage_line_type;
5118 static size_t stage_chunks;
5119 static int *stage_chunk;
5121 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5123 /* This should work even for the "On branch" line. */
5124 static inline bool
5125 status_has_none(struct view *view, struct line *line)
5127         return line < view->line + view->lines && !line[1].data;
5130 /* Get fields from the diff line:
5131  * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5132  */
5133 static inline bool
5134 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5136         const char *old_mode = buf +  1;
5137         const char *new_mode = buf +  8;
5138         const char *old_rev  = buf + 15;
5139         const char *new_rev  = buf + 56;
5140         const char *status   = buf + 97;
5142         if (bufsize < 98 ||
5143             old_mode[-1] != ':' ||
5144             new_mode[-1] != ' ' ||
5145             old_rev[-1]  != ' ' ||
5146             new_rev[-1]  != ' ' ||
5147             status[-1]   != ' ')
5148                 return FALSE;
5150         file->status = *status;
5152         string_copy_rev(file->old.rev, old_rev);
5153         string_copy_rev(file->new.rev, new_rev);
5155         file->old.mode = strtoul(old_mode, NULL, 8);
5156         file->new.mode = strtoul(new_mode, NULL, 8);
5158         file->old.name[0] = file->new.name[0] = 0;
5160         return TRUE;
5163 static bool
5164 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5166         struct status *unmerged = NULL;
5167         char *buf;
5168         struct io io;
5170         if (!io_run(&io, IO_RD, opt_cdup, argv))
5171                 return FALSE;
5173         add_line_data(view, NULL, type);
5175         while ((buf = io_get(&io, 0, TRUE))) {
5176                 struct status *file = unmerged;
5178                 if (!file) {
5179                         file = calloc(1, sizeof(*file));
5180                         if (!file || !add_line_data(view, file, type))
5181                                 goto error_out;
5182                 }
5184                 /* Parse diff info part. */
5185                 if (status) {
5186                         file->status = status;
5187                         if (status == 'A')
5188                                 string_copy(file->old.rev, NULL_ID);
5190                 } else if (!file->status || file == unmerged) {
5191                         if (!status_get_diff(file, buf, strlen(buf)))
5192                                 goto error_out;
5194                         buf = io_get(&io, 0, TRUE);
5195                         if (!buf)
5196                                 break;
5198                         /* Collapse all modified entries that follow an
5199                          * associated unmerged entry. */
5200                         if (unmerged == file) {
5201                                 unmerged->status = 'U';
5202                                 unmerged = NULL;
5203                         } else if (file->status == 'U') {
5204                                 unmerged = file;
5205                         }
5206                 }
5208                 /* Grab the old name for rename/copy. */
5209                 if (!*file->old.name &&
5210                     (file->status == 'R' || file->status == 'C')) {
5211                         string_ncopy(file->old.name, buf, strlen(buf));
5213                         buf = io_get(&io, 0, TRUE);
5214                         if (!buf)
5215                                 break;
5216                 }
5218                 /* git-ls-files just delivers a NUL separated list of
5219                  * file names similar to the second half of the
5220                  * git-diff-* output. */
5221                 string_ncopy(file->new.name, buf, strlen(buf));
5222                 if (!*file->old.name)
5223                         string_copy(file->old.name, file->new.name);
5224                 file = NULL;
5225         }
5227         if (io_error(&io)) {
5228 error_out:
5229                 io_done(&io);
5230                 return FALSE;
5231         }
5233         if (!view->line[view->lines - 1].data)
5234                 add_line_data(view, NULL, LINE_STAT_NONE);
5236         io_done(&io);
5237         return TRUE;
5240 /* Don't show unmerged entries in the staged section. */
5241 static const char *status_diff_index_argv[] = {
5242         "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5243                              "--cached", "-M", "HEAD", NULL
5244 };
5246 static const char *status_diff_files_argv[] = {
5247         "git", "diff-files", "-z", NULL
5248 };
5250 static const char *status_list_other_argv[] = {
5251         "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5252 };
5254 static const char *status_list_no_head_argv[] = {
5255         "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5256 };
5258 static const char *update_index_argv[] = {
5259         "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5260 };
5262 /* Restore the previous line number to stay in the context or select a
5263  * line with something that can be updated. */
5264 static void
5265 status_restore(struct view *view)
5267         if (view->p_lineno >= view->lines)
5268                 view->p_lineno = view->lines - 1;
5269         while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5270                 view->p_lineno++;
5271         while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5272                 view->p_lineno--;
5274         /* If the above fails, always skip the "On branch" line. */
5275         if (view->p_lineno < view->lines)
5276                 view->lineno = view->p_lineno;
5277         else
5278                 view->lineno = 1;
5280         if (view->lineno < view->offset)
5281                 view->offset = view->lineno;
5282         else if (view->offset + view->height <= view->lineno)
5283                 view->offset = view->lineno - view->height + 1;
5285         view->p_restore = FALSE;
5288 static void
5289 status_update_onbranch(void)
5291         static const char *paths[][2] = {
5292                 { "rebase-apply/rebasing",      "Rebasing" },
5293                 { "rebase-apply/applying",      "Applying mailbox" },
5294                 { "rebase-apply/",              "Rebasing mailbox" },
5295                 { "rebase-merge/interactive",   "Interactive rebase" },
5296                 { "rebase-merge/",              "Rebase merge" },
5297                 { "MERGE_HEAD",                 "Merging" },
5298                 { "BISECT_LOG",                 "Bisecting" },
5299                 { "HEAD",                       "On branch" },
5300         };
5301         char buf[SIZEOF_STR];
5302         struct stat stat;
5303         int i;
5305         if (is_initial_commit()) {
5306                 string_copy(status_onbranch, "Initial commit");
5307                 return;
5308         }
5310         for (i = 0; i < ARRAY_SIZE(paths); i++) {
5311                 char *head = opt_head;
5313                 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5314                     lstat(buf, &stat) < 0)
5315                         continue;
5317                 if (!*opt_head) {
5318                         struct io io;
5320                         if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5321                             io_read_buf(&io, buf, sizeof(buf))) {
5322                                 head = buf;
5323                                 if (!prefixcmp(head, "refs/heads/"))
5324                                         head += STRING_SIZE("refs/heads/");
5325                         }
5326                 }
5328                 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5329                         string_copy(status_onbranch, opt_head);
5330                 return;
5331         }
5333         string_copy(status_onbranch, "Not currently on any branch");
5336 /* First parse staged info using git-diff-index(1), then parse unstaged
5337  * info using git-diff-files(1), and finally untracked files using
5338  * git-ls-files(1). */
5339 static bool
5340 status_open(struct view *view)
5342         reset_view(view);
5344         add_line_data(view, NULL, LINE_STAT_HEAD);
5345         status_update_onbranch();
5347         io_run_bg(update_index_argv);
5349         if (is_initial_commit()) {
5350                 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5351                         return FALSE;
5352         } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5353                 return FALSE;
5354         }
5356         if (!opt_untracked_dirs_content)
5357                 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5359         if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5360             !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5361                 return FALSE;
5363         /* Restore the exact position or use the specialized restore
5364          * mode? */
5365         if (!view->p_restore)
5366                 status_restore(view);
5367         return TRUE;
5370 static bool
5371 status_draw(struct view *view, struct line *line, unsigned int lineno)
5373         struct status *status = line->data;
5374         enum line_type type;
5375         const char *text;
5377         if (!status) {
5378                 switch (line->type) {
5379                 case LINE_STAT_STAGED:
5380                         type = LINE_STAT_SECTION;
5381                         text = "Changes to be committed:";
5382                         break;
5384                 case LINE_STAT_UNSTAGED:
5385                         type = LINE_STAT_SECTION;
5386                         text = "Changed but not updated:";
5387                         break;
5389                 case LINE_STAT_UNTRACKED:
5390                         type = LINE_STAT_SECTION;
5391                         text = "Untracked files:";
5392                         break;
5394                 case LINE_STAT_NONE:
5395                         type = LINE_DEFAULT;
5396                         text = "  (no files)";
5397                         break;
5399                 case LINE_STAT_HEAD:
5400                         type = LINE_STAT_HEAD;
5401                         text = status_onbranch;
5402                         break;
5404                 default:
5405                         return FALSE;
5406                 }
5407         } else {
5408                 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5410                 buf[0] = status->status;
5411                 if (draw_text(view, line->type, buf))
5412                         return TRUE;
5413                 type = LINE_DEFAULT;
5414                 text = status->new.name;
5415         }
5417         draw_text(view, type, text);
5418         return TRUE;
5421 static enum request
5422 status_load_error(struct view *view, struct view *stage, const char *path)
5424         if (displayed_views() == 2 || display[current_view] != view)
5425                 maximize_view(view);
5426         report("Failed to load '%s': %s", path, io_strerror(&stage->io));
5427         return REQ_NONE;
5430 static enum request
5431 status_enter(struct view *view, struct line *line)
5433         struct status *status = line->data;
5434         const char *oldpath = status ? status->old.name : NULL;
5435         /* Diffs for unmerged entries are empty when passing the new
5436          * path, so leave it empty. */
5437         const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5438         const char *info;
5439         enum open_flags split;
5440         struct view *stage = VIEW(REQ_VIEW_STAGE);
5442         if (line->type == LINE_STAT_NONE ||
5443             (!status && line[1].type == LINE_STAT_NONE)) {
5444                 report("No file to diff");
5445                 return REQ_NONE;
5446         }
5448         switch (line->type) {
5449         case LINE_STAT_STAGED:
5450                 if (is_initial_commit()) {
5451                         const char *no_head_diff_argv[] = {
5452                                 "git", "diff", "--no-color", "--patch-with-stat",
5453                                         "--", "/dev/null", newpath, NULL
5454                         };
5456                         if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5457                                 return status_load_error(view, stage, newpath);
5458                 } else {
5459                         const char *index_show_argv[] = {
5460                                 "git", "diff-index", "--root", "--patch-with-stat",
5461                                         "-C", "-M", "--cached", "HEAD", "--",
5462                                         oldpath, newpath, NULL
5463                         };
5465                         if (!prepare_update(stage, index_show_argv, opt_cdup))
5466                                 return status_load_error(view, stage, newpath);
5467                 }
5469                 if (status)
5470                         info = "Staged changes to %s";
5471                 else
5472                         info = "Staged changes";
5473                 break;
5475         case LINE_STAT_UNSTAGED:
5476         {
5477                 const char *files_show_argv[] = {
5478                         "git", "diff-files", "--root", "--patch-with-stat",
5479                                 "-C", "-M", "--", oldpath, newpath, NULL
5480                 };
5482                 if (!prepare_update(stage, files_show_argv, opt_cdup))
5483                         return status_load_error(view, stage, newpath);
5484                 if (status)
5485                         info = "Unstaged changes to %s";
5486                 else
5487                         info = "Unstaged changes";
5488                 break;
5489         }
5490         case LINE_STAT_UNTRACKED:
5491                 if (!newpath) {
5492                         report("No file to show");
5493                         return REQ_NONE;
5494                 }
5496                 if (!suffixcmp(status->new.name, -1, "/")) {
5497                         report("Cannot display a directory");
5498                         return REQ_NONE;
5499                 }
5501                 if (!prepare_update_file(stage, newpath))
5502                         return status_load_error(view, stage, newpath);
5503                 info = "Untracked file %s";
5504                 break;
5506         case LINE_STAT_HEAD:
5507                 return REQ_NONE;
5509         default:
5510                 die("line type %d not handled in switch", line->type);
5511         }
5513         split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5514         open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5515         if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5516                 if (status) {
5517                         stage_status = *status;
5518                 } else {
5519                         memset(&stage_status, 0, sizeof(stage_status));
5520                 }
5522                 stage_line_type = line->type;
5523                 stage_chunks = 0;
5524                 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5525         }
5527         return REQ_NONE;
5530 static bool
5531 status_exists(struct status *status, enum line_type type)
5533         struct view *view = VIEW(REQ_VIEW_STATUS);
5534         unsigned long lineno;
5536         for (lineno = 0; lineno < view->lines; lineno++) {
5537                 struct line *line = &view->line[lineno];
5538                 struct status *pos = line->data;
5540                 if (line->type != type)
5541                         continue;
5542                 if (!pos && (!status || !status->status) && line[1].data) {
5543                         select_view_line(view, lineno);
5544                         return TRUE;
5545                 }
5546                 if (pos && !strcmp(status->new.name, pos->new.name)) {
5547                         select_view_line(view, lineno);
5548                         return TRUE;
5549                 }
5550         }
5552         return FALSE;
5556 static bool
5557 status_update_prepare(struct io *io, enum line_type type)
5559         const char *staged_argv[] = {
5560                 "git", "update-index", "-z", "--index-info", NULL
5561         };
5562         const char *others_argv[] = {
5563                 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5564         };
5566         switch (type) {
5567         case LINE_STAT_STAGED:
5568                 return io_run(io, IO_WR, opt_cdup, staged_argv);
5570         case LINE_STAT_UNSTAGED:
5571         case LINE_STAT_UNTRACKED:
5572                 return io_run(io, IO_WR, opt_cdup, others_argv);
5574         default:
5575                 die("line type %d not handled in switch", type);
5576                 return FALSE;
5577         }
5580 static bool
5581 status_update_write(struct io *io, struct status *status, enum line_type type)
5583         char buf[SIZEOF_STR];
5584         size_t bufsize = 0;
5586         switch (type) {
5587         case LINE_STAT_STAGED:
5588                 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5589                                         status->old.mode,
5590                                         status->old.rev,
5591                                         status->old.name, 0))
5592                         return FALSE;
5593                 break;
5595         case LINE_STAT_UNSTAGED:
5596         case LINE_STAT_UNTRACKED:
5597                 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5598                         return FALSE;
5599                 break;
5601         default:
5602                 die("line type %d not handled in switch", type);
5603         }
5605         return io_write(io, buf, bufsize);
5608 static bool
5609 status_update_file(struct status *status, enum line_type type)
5611         struct io io;
5612         bool result;
5614         if (!status_update_prepare(&io, type))
5615                 return FALSE;
5617         result = status_update_write(&io, status, type);
5618         return io_done(&io) && result;
5621 static bool
5622 status_update_files(struct view *view, struct line *line)
5624         char buf[sizeof(view->ref)];
5625         struct io io;
5626         bool result = TRUE;
5627         struct line *pos = view->line + view->lines;
5628         int files = 0;
5629         int file, done;
5630         int cursor_y = -1, cursor_x = -1;
5632         if (!status_update_prepare(&io, line->type))
5633                 return FALSE;
5635         for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5636                 files++;
5638         string_copy(buf, view->ref);
5639         getsyx(cursor_y, cursor_x);
5640         for (file = 0, done = 5; result && file < files; line++, file++) {
5641                 int almost_done = file * 100 / files;
5643                 if (almost_done > done) {
5644                         done = almost_done;
5645                         string_format(view->ref, "updating file %u of %u (%d%% done)",
5646                                       file, files, done);
5647                         update_view_title(view);
5648                         setsyx(cursor_y, cursor_x);
5649                         doupdate();
5650                 }
5651                 result = status_update_write(&io, line->data, line->type);
5652         }
5653         string_copy(view->ref, buf);
5655         return io_done(&io) && result;
5658 static bool
5659 status_update(struct view *view)
5661         struct line *line = &view->line[view->lineno];
5663         assert(view->lines);
5665         if (!line->data) {
5666                 /* This should work even for the "On branch" line. */
5667                 if (line < view->line + view->lines && !line[1].data) {
5668                         report("Nothing to update");
5669                         return FALSE;
5670                 }
5672                 if (!status_update_files(view, line + 1)) {
5673                         report("Failed to update file status");
5674                         return FALSE;
5675                 }
5677         } else if (!status_update_file(line->data, line->type)) {
5678                 report("Failed to update file status");
5679                 return FALSE;
5680         }
5682         return TRUE;
5685 static bool
5686 status_revert(struct status *status, enum line_type type, bool has_none)
5688         if (!status || type != LINE_STAT_UNSTAGED) {
5689                 if (type == LINE_STAT_STAGED) {
5690                         report("Cannot revert changes to staged files");
5691                 } else if (type == LINE_STAT_UNTRACKED) {
5692                         report("Cannot revert changes to untracked files");
5693                 } else if (has_none) {
5694                         report("Nothing to revert");
5695                 } else {
5696                         report("Cannot revert changes to multiple files");
5697                 }
5699         } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5700                 char mode[10] = "100644";
5701                 const char *reset_argv[] = {
5702                         "git", "update-index", "--cacheinfo", mode,
5703                                 status->old.rev, status->old.name, NULL
5704                 };
5705                 const char *checkout_argv[] = {
5706                         "git", "checkout", "--", status->old.name, NULL
5707                 };
5709                 if (status->status == 'U') {
5710                         string_format(mode, "%5o", status->old.mode);
5712                         if (status->old.mode == 0 && status->new.mode == 0) {
5713                                 reset_argv[2] = "--force-remove";
5714                                 reset_argv[3] = status->old.name;
5715                                 reset_argv[4] = NULL;
5716                         }
5718                         if (!io_run_fg(reset_argv, opt_cdup))
5719                                 return FALSE;
5720                         if (status->old.mode == 0 && status->new.mode == 0)
5721                                 return TRUE;
5722                 }
5724                 return io_run_fg(checkout_argv, opt_cdup);
5725         }
5727         return FALSE;
5730 static enum request
5731 status_request(struct view *view, enum request request, struct line *line)
5733         struct status *status = line->data;
5735         switch (request) {
5736         case REQ_STATUS_UPDATE:
5737                 if (!status_update(view))
5738                         return REQ_NONE;
5739                 break;
5741         case REQ_STATUS_REVERT:
5742                 if (!status_revert(status, line->type, status_has_none(view, line)))
5743                         return REQ_NONE;
5744                 break;
5746         case REQ_STATUS_MERGE:
5747                 if (!status || status->status != 'U') {
5748                         report("Merging only possible for files with unmerged status ('U').");
5749                         return REQ_NONE;
5750                 }
5751                 open_mergetool(status->new.name);
5752                 break;
5754         case REQ_EDIT:
5755                 if (!status)
5756                         return request;
5757                 if (status->status == 'D') {
5758                         report("File has been deleted.");
5759                         return REQ_NONE;
5760                 }
5762                 open_editor(status->new.name);
5763                 break;
5765         case REQ_VIEW_BLAME:
5766                 if (status)
5767                         opt_ref[0] = 0;
5768                 return request;
5770         case REQ_ENTER:
5771                 /* After returning the status view has been split to
5772                  * show the stage view. No further reloading is
5773                  * necessary. */
5774                 return status_enter(view, line);
5776         case REQ_REFRESH:
5777                 /* Simply reload the view. */
5778                 break;
5780         default:
5781                 return request;
5782         }
5784         open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5786         return REQ_NONE;
5789 static void
5790 status_select(struct view *view, struct line *line)
5792         struct status *status = line->data;
5793         char file[SIZEOF_STR] = "all files";
5794         const char *text;
5795         const char *key;
5797         if (status && !string_format(file, "'%s'", status->new.name))
5798                 return;
5800         if (!status && line[1].type == LINE_STAT_NONE)
5801                 line++;
5803         switch (line->type) {
5804         case LINE_STAT_STAGED:
5805                 text = "Press %s to unstage %s for commit";
5806                 break;
5808         case LINE_STAT_UNSTAGED:
5809                 text = "Press %s to stage %s for commit";
5810                 break;
5812         case LINE_STAT_UNTRACKED:
5813                 text = "Press %s to stage %s for addition";
5814                 break;
5816         case LINE_STAT_HEAD:
5817         case LINE_STAT_NONE:
5818                 text = "Nothing to update";
5819                 break;
5821         default:
5822                 die("line type %d not handled in switch", line->type);
5823         }
5825         if (status && status->status == 'U') {
5826                 text = "Press %s to resolve conflict in %s";
5827                 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5829         } else {
5830                 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5831         }
5833         string_format(view->ref, text, key, file);
5834         if (status)
5835                 string_copy(opt_file, status->new.name);
5838 static bool
5839 status_grep(struct view *view, struct line *line)
5841         struct status *status = line->data;
5843         if (status) {
5844                 const char buf[2] = { status->status, 0 };
5845                 const char *text[] = { status->new.name, buf, NULL };
5847                 return grep_text(view, text);
5848         }
5850         return FALSE;
5853 static struct view_ops status_ops = {
5854         "file",
5855         NULL,
5856         status_open,
5857         NULL,
5858         status_draw,
5859         status_request,
5860         status_grep,
5861         status_select,
5862 };
5865 static bool
5866 stage_diff_write(struct io *io, struct line *line, struct line *end)
5868         while (line < end) {
5869                 if (!io_write(io, line->data, strlen(line->data)) ||
5870                     !io_write(io, "\n", 1))
5871                         return FALSE;
5872                 line++;
5873                 if (line->type == LINE_DIFF_CHUNK ||
5874                     line->type == LINE_DIFF_HEADER)
5875                         break;
5876         }
5878         return TRUE;
5881 static struct line *
5882 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5884         for (; view->line < line; line--)
5885                 if (line->type == type)
5886                         return line;
5888         return NULL;
5891 static bool
5892 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5894         const char *apply_argv[SIZEOF_ARG] = {
5895                 "git", "apply", "--whitespace=nowarn", NULL
5896         };
5897         struct line *diff_hdr;
5898         struct io io;
5899         int argc = 3;
5901         diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5902         if (!diff_hdr)
5903                 return FALSE;
5905         if (!revert)
5906                 apply_argv[argc++] = "--cached";
5907         if (revert || stage_line_type == LINE_STAT_STAGED)
5908                 apply_argv[argc++] = "-R";
5909         apply_argv[argc++] = "-";
5910         apply_argv[argc++] = NULL;
5911         if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5912                 return FALSE;
5914         if (!stage_diff_write(&io, diff_hdr, chunk) ||
5915             !stage_diff_write(&io, chunk, view->line + view->lines))
5916                 chunk = NULL;
5918         io_done(&io);
5919         io_run_bg(update_index_argv);
5921         return chunk ? TRUE : FALSE;
5924 static bool
5925 stage_update(struct view *view, struct line *line)
5927         struct line *chunk = NULL;
5929         if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5930                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5932         if (chunk) {
5933                 if (!stage_apply_chunk(view, chunk, FALSE)) {
5934                         report("Failed to apply chunk");
5935                         return FALSE;
5936                 }
5938         } else if (!stage_status.status) {
5939                 view = VIEW(REQ_VIEW_STATUS);
5941                 for (line = view->line; line < view->line + view->lines; line++)
5942                         if (line->type == stage_line_type)
5943                                 break;
5945                 if (!status_update_files(view, line + 1)) {
5946                         report("Failed to update files");
5947                         return FALSE;
5948                 }
5950         } else if (!status_update_file(&stage_status, stage_line_type)) {
5951                 report("Failed to update file");
5952                 return FALSE;
5953         }
5955         return TRUE;
5958 static bool
5959 stage_revert(struct view *view, struct line *line)
5961         struct line *chunk = NULL;
5963         if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5964                 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5966         if (chunk) {
5967                 if (!prompt_yesno("Are you sure you want to revert changes?"))
5968                         return FALSE;
5970                 if (!stage_apply_chunk(view, chunk, TRUE)) {
5971                         report("Failed to revert chunk");
5972                         return FALSE;
5973                 }
5974                 return TRUE;
5976         } else {
5977                 return status_revert(stage_status.status ? &stage_status : NULL,
5978                                      stage_line_type, FALSE);
5979         }
5983 static void
5984 stage_next(struct view *view, struct line *line)
5986         int i;
5988         if (!stage_chunks) {
5989                 for (line = view->line; line < view->line + view->lines; line++) {
5990                         if (line->type != LINE_DIFF_CHUNK)
5991                                 continue;
5993                         if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5994                                 report("Allocation failure");
5995                                 return;
5996                         }
5998                         stage_chunk[stage_chunks++] = line - view->line;
5999                 }
6000         }
6002         for (i = 0; i < stage_chunks; i++) {
6003                 if (stage_chunk[i] > view->lineno) {
6004                         do_scroll_view(view, stage_chunk[i] - view->lineno);
6005                         report("Chunk %d of %d", i + 1, stage_chunks);
6006                         return;
6007                 }
6008         }
6010         report("No next chunk found");
6013 static enum request
6014 stage_request(struct view *view, enum request request, struct line *line)
6016         switch (request) {
6017         case REQ_STATUS_UPDATE:
6018                 if (!stage_update(view, line))
6019                         return REQ_NONE;
6020                 break;
6022         case REQ_STATUS_REVERT:
6023                 if (!stage_revert(view, line))
6024                         return REQ_NONE;
6025                 break;
6027         case REQ_STAGE_NEXT:
6028                 if (stage_line_type == LINE_STAT_UNTRACKED) {
6029                         report("File is untracked; press %s to add",
6030                                get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
6031                         return REQ_NONE;
6032                 }
6033                 stage_next(view, line);
6034                 return REQ_NONE;
6036         case REQ_EDIT:
6037                 if (!stage_status.new.name[0])
6038                         return request;
6039                 if (stage_status.status == 'D') {
6040                         report("File has been deleted.");
6041                         return REQ_NONE;
6042                 }
6044                 open_editor(stage_status.new.name);
6045                 break;
6047         case REQ_REFRESH:
6048                 /* Reload everything ... */
6049                 break;
6051         case REQ_VIEW_BLAME:
6052                 if (stage_status.new.name[0]) {
6053                         string_copy(opt_file, stage_status.new.name);
6054                         opt_ref[0] = 0;
6055                 }
6056                 return request;
6058         case REQ_ENTER:
6059                 return pager_request(view, request, line);
6061         default:
6062                 return request;
6063         }
6065         VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
6066         open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
6068         /* Check whether the staged entry still exists, and close the
6069          * stage view if it doesn't. */
6070         if (!status_exists(&stage_status, stage_line_type)) {
6071                 status_restore(VIEW(REQ_VIEW_STATUS));
6072                 return REQ_VIEW_CLOSE;
6073         }
6075         if (stage_line_type == LINE_STAT_UNTRACKED) {
6076                 if (!suffixcmp(stage_status.new.name, -1, "/")) {
6077                         report("Cannot display a directory");
6078                         return REQ_NONE;
6079                 }
6081                 if (!prepare_update_file(view, stage_status.new.name)) {
6082                         report("Failed to open file: %s", strerror(errno));
6083                         return REQ_NONE;
6084                 }
6085         }
6086         open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
6088         return REQ_NONE;
6091 static struct view_ops stage_ops = {
6092         "line",
6093         NULL,
6094         NULL,
6095         pager_read,
6096         pager_draw,
6097         stage_request,
6098         pager_grep,
6099         pager_select,
6100 };
6103 /*
6104  * Revision graph
6105  */
6107 struct commit {
6108         char id[SIZEOF_REV];            /* SHA1 ID. */
6109         char title[128];                /* First line of the commit message. */
6110         const char *author;             /* Author of the commit. */
6111         struct time time;               /* Date from the author ident. */
6112         struct ref_list *refs;          /* Repository references. */
6113         chtype graph[SIZEOF_REVGRAPH];  /* Ancestry chain graphics. */
6114         size_t graph_size;              /* The width of the graph array. */
6115         bool has_parents;               /* Rewritten --parents seen. */
6116 };
6118 /* Size of rev graph with no  "padding" columns */
6119 #define SIZEOF_REVITEMS (SIZEOF_REVGRAPH - (SIZEOF_REVGRAPH / 2))
6121 struct rev_graph {
6122         struct rev_graph *prev, *next, *parents;
6123         char rev[SIZEOF_REVITEMS][SIZEOF_REV];
6124         size_t size;
6125         struct commit *commit;
6126         size_t pos;
6127         unsigned int boundary:1;
6128 };
6130 /* Parents of the commit being visualized. */
6131 static struct rev_graph graph_parents[4];
6133 /* The current stack of revisions on the graph. */
6134 static struct rev_graph graph_stacks[4] = {
6135         { &graph_stacks[3], &graph_stacks[1], &graph_parents[0] },
6136         { &graph_stacks[0], &graph_stacks[2], &graph_parents[1] },
6137         { &graph_stacks[1], &graph_stacks[3], &graph_parents[2] },
6138         { &graph_stacks[2], &graph_stacks[0], &graph_parents[3] },
6139 };
6141 static inline bool
6142 graph_parent_is_merge(struct rev_graph *graph)
6144         return graph->parents->size > 1;
6147 static inline void
6148 append_to_rev_graph(struct rev_graph *graph, chtype symbol)
6150         struct commit *commit = graph->commit;
6152         if (commit->graph_size < ARRAY_SIZE(commit->graph) - 1)
6153                 commit->graph[commit->graph_size++] = symbol;
6156 static void
6157 clear_rev_graph(struct rev_graph *graph)
6159         graph->boundary = 0;
6160         graph->size = graph->pos = 0;
6161         graph->commit = NULL;
6162         memset(graph->parents, 0, sizeof(*graph->parents));
6165 static void
6166 done_rev_graph(struct rev_graph *graph)
6168         if (graph_parent_is_merge(graph) &&
6169             graph->pos < graph->size - 1 &&
6170             graph->next->size == graph->size + graph->parents->size - 1) {
6171                 size_t i = graph->pos + graph->parents->size - 1;
6173                 graph->commit->graph_size = i * 2;
6174                 while (i < graph->next->size - 1) {
6175                         append_to_rev_graph(graph, ' ');
6176                         append_to_rev_graph(graph, '\\');
6177                         i++;
6178                 }
6179         }
6181         clear_rev_graph(graph);
6184 static void
6185 push_rev_graph(struct rev_graph *graph, const char *parent)
6187         int i;
6189         /* "Collapse" duplicate parents lines.
6190          *
6191          * FIXME: This needs to also update update the drawn graph but
6192          * for now it just serves as a method for pruning graph lines. */
6193         for (i = 0; i < graph->size; i++)
6194                 if (!strncmp(graph->rev[i], parent, SIZEOF_REV))
6195                         return;
6197         if (graph->size < SIZEOF_REVITEMS) {
6198                 string_copy_rev(graph->rev[graph->size++], parent);
6199         }
6202 static chtype
6203 get_rev_graph_symbol(struct rev_graph *graph)
6205         chtype symbol;
6207         if (graph->boundary)
6208                 symbol = REVGRAPH_BOUND;
6209         else if (graph->parents->size == 0)
6210                 symbol = REVGRAPH_INIT;
6211         else if (graph_parent_is_merge(graph))
6212                 symbol = REVGRAPH_MERGE;
6213         else if (graph->pos >= graph->size)
6214                 symbol = REVGRAPH_BRANCH;
6215         else
6216                 symbol = REVGRAPH_COMMIT;
6218         return symbol;
6221 static void
6222 draw_rev_graph(struct rev_graph *graph)
6224         struct rev_filler {
6225                 chtype separator, line;
6226         };
6227         enum { DEFAULT, RSHARP, RDIAG, LDIAG };
6228         static struct rev_filler fillers[] = {
6229                 { ' ',  '|' },
6230                 { '`',  '.' },
6231                 { '\'', ' ' },
6232                 { '/',  ' ' },
6233         };
6234         chtype symbol = get_rev_graph_symbol(graph);
6235         struct rev_filler *filler;
6236         size_t i;
6238         fillers[DEFAULT].line = opt_line_graphics ? ACS_VLINE : '|';
6239         filler = &fillers[DEFAULT];
6241         for (i = 0; i < graph->pos; i++) {
6242                 append_to_rev_graph(graph, filler->line);
6243                 if (graph_parent_is_merge(graph->prev) &&
6244                     graph->prev->pos == i)
6245                         filler = &fillers[RSHARP];
6247                 append_to_rev_graph(graph, filler->separator);
6248         }
6250         /* Place the symbol for this revision. */
6251         append_to_rev_graph(graph, symbol);
6253         if (graph->prev->size > graph->size)
6254                 filler = &fillers[RDIAG];
6255         else
6256                 filler = &fillers[DEFAULT];
6258         i++;
6260         for (; i < graph->size; i++) {
6261                 append_to_rev_graph(graph, filler->separator);
6262                 append_to_rev_graph(graph, filler->line);
6263                 if (graph_parent_is_merge(graph->prev) &&
6264                     i < graph->prev->pos + graph->parents->size)
6265                         filler = &fillers[RSHARP];
6266                 if (graph->prev->size > graph->size)
6267                         filler = &fillers[LDIAG];
6268         }
6270         if (graph->prev->size > graph->size) {
6271                 append_to_rev_graph(graph, filler->separator);
6272                 if (filler->line != ' ')
6273                         append_to_rev_graph(graph, filler->line);
6274         }
6277 /* Prepare the next rev graph */
6278 static void
6279 prepare_rev_graph(struct rev_graph *graph)
6281         size_t i;
6283         /* First, traverse all lines of revisions up to the active one. */
6284         for (graph->pos = 0; graph->pos < graph->size; graph->pos++) {
6285                 if (!strcmp(graph->rev[graph->pos], graph->commit->id))
6286                         break;
6288                 push_rev_graph(graph->next, graph->rev[graph->pos]);
6289         }
6291         /* Interleave the new revision parent(s). */
6292         for (i = 0; !graph->boundary && i < graph->parents->size; i++)
6293                 push_rev_graph(graph->next, graph->parents->rev[i]);
6295         /* Lastly, put any remaining revisions. */
6296         for (i = graph->pos + 1; i < graph->size; i++)
6297                 push_rev_graph(graph->next, graph->rev[i]);
6300 static void
6301 update_rev_graph(struct view *view, struct rev_graph *graph)
6303         /* If this is the finalizing update ... */
6304         if (graph->commit)
6305                 prepare_rev_graph(graph);
6307         /* Graph visualization needs a one rev look-ahead,
6308          * so the first update doesn't visualize anything. */
6309         if (!graph->prev->commit)
6310                 return;
6312         if (view->lines > 2)
6313                 view->line[view->lines - 3].dirty = 1;
6314         if (view->lines > 1)
6315                 view->line[view->lines - 2].dirty = 1;
6316         draw_rev_graph(graph->prev);
6317         done_rev_graph(graph->prev->prev);
6321 /*
6322  * Main view backend
6323  */
6325 static const char *main_argv[SIZEOF_ARG] = {
6326         "git", "log", "--no-color", "--pretty=raw", "--parents",
6327                 "--topo-order", "%(diffargs)", "%(revargs)",
6328                 "--", "%(fileargs)", NULL
6329 };
6331 static bool
6332 main_draw(struct view *view, struct line *line, unsigned int lineno)
6334         struct commit *commit = line->data;
6336         if (!commit->author)
6337                 return FALSE;
6339         if (opt_date && draw_date(view, &commit->time))
6340                 return TRUE;
6342         if (opt_author && draw_author(view, commit->author))
6343                 return TRUE;
6345         if (opt_rev_graph && commit->graph_size &&
6346             draw_graphic(view, LINE_MAIN_REVGRAPH, commit->graph, commit->graph_size))
6347                 return TRUE;
6349         if (opt_show_refs && commit->refs) {
6350                 size_t i;
6352                 for (i = 0; i < commit->refs->size; i++) {
6353                         struct ref *ref = commit->refs->refs[i];
6354                         enum line_type type;
6356                         if (ref->head)
6357                                 type = LINE_MAIN_HEAD;
6358                         else if (ref->ltag)
6359                                 type = LINE_MAIN_LOCAL_TAG;
6360                         else if (ref->tag)
6361                                 type = LINE_MAIN_TAG;
6362                         else if (ref->tracked)
6363                                 type = LINE_MAIN_TRACKED;
6364                         else if (ref->remote)
6365                                 type = LINE_MAIN_REMOTE;
6366                         else
6367                                 type = LINE_MAIN_REF;
6369                         if (draw_text(view, type, "[") ||
6370                             draw_text(view, type, ref->name) ||
6371                             draw_text(view, type, "]"))
6372                                 return TRUE;
6374                         if (draw_text(view, LINE_DEFAULT, " "))
6375                                 return TRUE;
6376                 }
6377         }
6379         draw_text(view, LINE_DEFAULT, commit->title);
6380         return TRUE;
6383 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6384 static bool
6385 main_read(struct view *view, char *line)
6387         static struct rev_graph *graph = graph_stacks;
6388         enum line_type type;
6389         struct commit *commit;
6391         if (!line) {
6392                 int i;
6394                 if (!view->lines && !view->prev)
6395                         die("No revisions match the given arguments.");
6396                 if (view->lines > 0) {
6397                         commit = view->line[view->lines - 1].data;
6398                         view->line[view->lines - 1].dirty = 1;
6399                         if (!commit->author) {
6400                                 view->lines--;
6401                                 free(commit);
6402                                 graph->commit = NULL;
6403                         }
6404                 }
6405                 update_rev_graph(view, graph);
6407                 for (i = 0; i < ARRAY_SIZE(graph_stacks); i++)
6408                         clear_rev_graph(&graph_stacks[i]);
6409                 return TRUE;
6410         }
6412         type = get_line_type(line);
6413         if (type == LINE_COMMIT) {
6414                 commit = calloc(1, sizeof(struct commit));
6415                 if (!commit)
6416                         return FALSE;
6418                 line += STRING_SIZE("commit ");
6419                 if (*line == '-') {
6420                         graph->boundary = 1;
6421                         line++;
6422                 }
6424                 string_copy_rev(commit->id, line);
6425                 commit->refs = get_ref_list(commit->id);
6426                 graph->commit = commit;
6427                 add_line_data(view, commit, LINE_MAIN_COMMIT);
6429                 while ((line = strchr(line, ' '))) {
6430                         line++;
6431                         push_rev_graph(graph->parents, line);
6432                         commit->has_parents = TRUE;
6433                 }
6434                 return TRUE;
6435         }
6437         if (!view->lines)
6438                 return TRUE;
6439         commit = view->line[view->lines - 1].data;
6441         switch (type) {
6442         case LINE_PARENT:
6443                 if (commit->has_parents)
6444                         break;
6445                 push_rev_graph(graph->parents, line + STRING_SIZE("parent "));
6446                 break;
6448         case LINE_AUTHOR:
6449                 parse_author_line(line + STRING_SIZE("author "),
6450                                   &commit->author, &commit->time);
6451                 update_rev_graph(view, graph);
6452                 graph = graph->next;
6453                 break;
6455         default:
6456                 /* Fill in the commit title if it has not already been set. */
6457                 if (commit->title[0])
6458                         break;
6460                 /* Require titles to start with a non-space character at the
6461                  * offset used by git log. */
6462                 if (strncmp(line, "    ", 4))
6463                         break;
6464                 line += 4;
6465                 /* Well, if the title starts with a whitespace character,
6466                  * try to be forgiving.  Otherwise we end up with no title. */
6467                 while (isspace(*line))
6468                         line++;
6469                 if (*line == '\0')
6470                         break;
6471                 /* FIXME: More graceful handling of titles; append "..." to
6472                  * shortened titles, etc. */
6474                 string_expand(commit->title, sizeof(commit->title), line, 1);
6475                 view->line[view->lines - 1].dirty = 1;
6476         }
6478         return TRUE;
6481 static enum request
6482 main_request(struct view *view, enum request request, struct line *line)
6484         enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6486         switch (request) {
6487         case REQ_ENTER:
6488                 if (view_is_displayed(view) && display[0] != view)
6489                         maximize_view(view);
6490                 open_view(view, REQ_VIEW_DIFF, flags);
6491                 break;
6492         case REQ_REFRESH:
6493                 load_refs();
6494                 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
6495                 break;
6496         default:
6497                 return request;
6498         }
6500         return REQ_NONE;
6503 static bool
6504 grep_refs(struct ref_list *list, regex_t *regex)
6506         regmatch_t pmatch;
6507         size_t i;
6509         if (!opt_show_refs || !list)
6510                 return FALSE;
6512         for (i = 0; i < list->size; i++) {
6513                 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6514                         return TRUE;
6515         }
6517         return FALSE;
6520 static bool
6521 main_grep(struct view *view, struct line *line)
6523         struct commit *commit = line->data;
6524         const char *text[] = {
6525                 commit->title,
6526                 opt_author ? commit->author : "",
6527                 mkdate(&commit->time, opt_date),
6528                 NULL
6529         };
6531         return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6534 static void
6535 main_select(struct view *view, struct line *line)
6537         struct commit *commit = line->data;
6539         string_copy_rev(view->ref, commit->id);
6540         string_copy_rev(ref_commit, view->ref);
6543 static struct view_ops main_ops = {
6544         "commit",
6545         main_argv,
6546         NULL,
6547         main_read,
6548         main_draw,
6549         main_request,
6550         main_grep,
6551         main_select,
6552 };
6555 /*
6556  * Status management
6557  */
6559 /* Whether or not the curses interface has been initialized. */
6560 static bool cursed = FALSE;
6562 /* Terminal hacks and workarounds. */
6563 static bool use_scroll_redrawwin;
6564 static bool use_scroll_status_wclear;
6566 /* The status window is used for polling keystrokes. */
6567 static WINDOW *status_win;
6569 /* Reading from the prompt? */
6570 static bool input_mode = FALSE;
6572 static bool status_empty = FALSE;
6574 /* Update status and title window. */
6575 static void
6576 report(const char *msg, ...)
6578         struct view *view = display[current_view];
6580         if (input_mode)
6581                 return;
6583         if (!view) {
6584                 char buf[SIZEOF_STR];
6585                 va_list args;
6587                 va_start(args, msg);
6588                 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6589                         buf[sizeof(buf) - 1] = 0;
6590                         buf[sizeof(buf) - 2] = '.';
6591                         buf[sizeof(buf) - 3] = '.';
6592                         buf[sizeof(buf) - 4] = '.';
6593                 }
6594                 va_end(args);
6595                 die("%s", buf);
6596         }
6598         if (!status_empty || *msg) {
6599                 va_list args;
6601                 va_start(args, msg);
6603                 wmove(status_win, 0, 0);
6604                 if (view->has_scrolled && use_scroll_status_wclear)
6605                         wclear(status_win);
6606                 if (*msg) {
6607                         vwprintw(status_win, msg, args);
6608                         status_empty = FALSE;
6609                 } else {
6610                         status_empty = TRUE;
6611                 }
6612                 wclrtoeol(status_win);
6613                 wnoutrefresh(status_win);
6615                 va_end(args);
6616         }
6618         update_view_title(view);
6621 static void
6622 init_display(void)
6624         const char *term;
6625         int x, y;
6627         /* Initialize the curses library */
6628         if (isatty(STDIN_FILENO)) {
6629                 cursed = !!initscr();
6630                 opt_tty = stdin;
6631         } else {
6632                 /* Leave stdin and stdout alone when acting as a pager. */
6633                 opt_tty = fopen("/dev/tty", "r+");
6634                 if (!opt_tty)
6635                         die("Failed to open /dev/tty");
6636                 cursed = !!newterm(NULL, opt_tty, opt_tty);
6637         }
6639         if (!cursed)
6640                 die("Failed to initialize curses");
6642         nonl();         /* Disable conversion and detect newlines from input. */
6643         cbreak();       /* Take input chars one at a time, no wait for \n */
6644         noecho();       /* Don't echo input */
6645         leaveok(stdscr, FALSE);
6647         if (has_colors())
6648                 init_colors();
6650         getmaxyx(stdscr, y, x);
6651         status_win = newwin(1, x, y - 1, 0);
6652         if (!status_win)
6653                 die("Failed to create status window");
6655         /* Enable keyboard mapping */
6656         keypad(status_win, TRUE);
6657         wbkgdset(status_win, get_line_attr(LINE_STATUS));
6659 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6660         set_tabsize(opt_tab_size);
6661 #else
6662         TABSIZE = opt_tab_size;
6663 #endif
6665         term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6666         if (term && !strcmp(term, "gnome-terminal")) {
6667                 /* In the gnome-terminal-emulator, the message from
6668                  * scrolling up one line when impossible followed by
6669                  * scrolling down one line causes corruption of the
6670                  * status line. This is fixed by calling wclear. */
6671                 use_scroll_status_wclear = TRUE;
6672                 use_scroll_redrawwin = FALSE;
6674         } else if (term && !strcmp(term, "xrvt-xpm")) {
6675                 /* No problems with full optimizations in xrvt-(unicode)
6676                  * and aterm. */
6677                 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6679         } else {
6680                 /* When scrolling in (u)xterm the last line in the
6681                  * scrolling direction will update slowly. */
6682                 use_scroll_redrawwin = TRUE;
6683                 use_scroll_status_wclear = FALSE;
6684         }
6687 static int
6688 get_input(int prompt_position)
6690         struct view *view;
6691         int i, key, cursor_y, cursor_x;
6693         if (prompt_position)
6694                 input_mode = TRUE;
6696         while (TRUE) {
6697                 bool loading = FALSE;
6699                 foreach_view (view, i) {
6700                         update_view(view);
6701                         if (view_is_displayed(view) && view->has_scrolled &&
6702                             use_scroll_redrawwin)
6703                                 redrawwin(view->win);
6704                         view->has_scrolled = FALSE;
6705                         if (view->pipe)
6706                                 loading = TRUE;
6707                 }
6709                 /* Update the cursor position. */
6710                 if (prompt_position) {
6711                         getbegyx(status_win, cursor_y, cursor_x);
6712                         cursor_x = prompt_position;
6713                 } else {
6714                         view = display[current_view];
6715                         getbegyx(view->win, cursor_y, cursor_x);
6716                         cursor_x = view->width - 1;
6717                         cursor_y += view->lineno - view->offset;
6718                 }
6719                 setsyx(cursor_y, cursor_x);
6721                 /* Refresh, accept single keystroke of input */
6722                 doupdate();
6723                 nodelay(status_win, loading);
6724                 key = wgetch(status_win);
6726                 /* wgetch() with nodelay() enabled returns ERR when
6727                  * there's no input. */
6728                 if (key == ERR) {
6730                 } else if (key == KEY_RESIZE) {
6731                         int height, width;
6733                         getmaxyx(stdscr, height, width);
6735                         wresize(status_win, 1, width);
6736                         mvwin(status_win, height - 1, 0);
6737                         wnoutrefresh(status_win);
6738                         resize_display();
6739                         redraw_display(TRUE);
6741                 } else {
6742                         input_mode = FALSE;
6743                         return key;
6744                 }
6745         }
6748 static char *
6749 prompt_input(const char *prompt, input_handler handler, void *data)
6751         enum input_status status = INPUT_OK;
6752         static char buf[SIZEOF_STR];
6753         size_t pos = 0;
6755         buf[pos] = 0;
6757         while (status == INPUT_OK || status == INPUT_SKIP) {
6758                 int key;
6760                 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6761                 wclrtoeol(status_win);
6763                 key = get_input(pos + 1);
6764                 switch (key) {
6765                 case KEY_RETURN:
6766                 case KEY_ENTER:
6767                 case '\n':
6768                         status = pos ? INPUT_STOP : INPUT_CANCEL;
6769                         break;
6771                 case KEY_BACKSPACE:
6772                         if (pos > 0)
6773                                 buf[--pos] = 0;
6774                         else
6775                                 status = INPUT_CANCEL;
6776                         break;
6778                 case KEY_ESC:
6779                         status = INPUT_CANCEL;
6780                         break;
6782                 default:
6783                         if (pos >= sizeof(buf)) {
6784                                 report("Input string too long");
6785                                 return NULL;
6786                         }
6788                         status = handler(data, buf, key);
6789                         if (status == INPUT_OK)
6790                                 buf[pos++] = (char) key;
6791                 }
6792         }
6794         /* Clear the status window */
6795         status_empty = FALSE;
6796         report("");
6798         if (status == INPUT_CANCEL)
6799                 return NULL;
6801         buf[pos++] = 0;
6803         return buf;
6806 static enum input_status
6807 prompt_yesno_handler(void *data, char *buf, int c)
6809         if (c == 'y' || c == 'Y')
6810                 return INPUT_STOP;
6811         if (c == 'n' || c == 'N')
6812                 return INPUT_CANCEL;
6813         return INPUT_SKIP;
6816 static bool
6817 prompt_yesno(const char *prompt)
6819         char prompt2[SIZEOF_STR];
6821         if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6822                 return FALSE;
6824         return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6827 static enum input_status
6828 read_prompt_handler(void *data, char *buf, int c)
6830         return isprint(c) ? INPUT_OK : INPUT_SKIP;
6833 static char *
6834 read_prompt(const char *prompt)
6836         return prompt_input(prompt, read_prompt_handler, NULL);
6839 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6841         enum input_status status = INPUT_OK;
6842         int size = 0;
6844         while (items[size].text)
6845                 size++;
6847         while (status == INPUT_OK) {
6848                 const struct menu_item *item = &items[*selected];
6849                 int key;
6850                 int i;
6852                 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6853                           prompt, *selected + 1, size);
6854                 if (item->hotkey)
6855                         wprintw(status_win, "[%c] ", (char) item->hotkey);
6856                 wprintw(status_win, "%s", item->text);
6857                 wclrtoeol(status_win);
6859                 key = get_input(COLS - 1);
6860                 switch (key) {
6861                 case KEY_RETURN:
6862                 case KEY_ENTER:
6863                 case '\n':
6864                         status = INPUT_STOP;
6865                         break;
6867                 case KEY_LEFT:
6868                 case KEY_UP:
6869                         *selected = *selected - 1;
6870                         if (*selected < 0)
6871                                 *selected = size - 1;
6872                         break;
6874                 case KEY_RIGHT:
6875                 case KEY_DOWN:
6876                         *selected = (*selected + 1) % size;
6877                         break;
6879                 case KEY_ESC:
6880                         status = INPUT_CANCEL;
6881                         break;
6883                 default:
6884                         for (i = 0; items[i].text; i++)
6885                                 if (items[i].hotkey == key) {
6886                                         *selected = i;
6887                                         status = INPUT_STOP;
6888                                         break;
6889                                 }
6890                 }
6891         }
6893         /* Clear the status window */
6894         status_empty = FALSE;
6895         report("");
6897         return status != INPUT_CANCEL;
6900 /*
6901  * Repository properties
6902  */
6904 static struct ref **refs = NULL;
6905 static size_t refs_size = 0;
6906 static struct ref *refs_head = NULL;
6908 static struct ref_list **ref_lists = NULL;
6909 static size_t ref_lists_size = 0;
6911 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6912 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6913 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6915 static int
6916 compare_refs(const void *ref1_, const void *ref2_)
6918         const struct ref *ref1 = *(const struct ref **)ref1_;
6919         const struct ref *ref2 = *(const struct ref **)ref2_;
6921         if (ref1->tag != ref2->tag)
6922                 return ref2->tag - ref1->tag;
6923         if (ref1->ltag != ref2->ltag)
6924                 return ref2->ltag - ref2->ltag;
6925         if (ref1->head != ref2->head)
6926                 return ref2->head - ref1->head;
6927         if (ref1->tracked != ref2->tracked)
6928                 return ref2->tracked - ref1->tracked;
6929         if (ref1->remote != ref2->remote)
6930                 return ref2->remote - ref1->remote;
6931         return strcmp(ref1->name, ref2->name);
6934 static void
6935 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6937         size_t i;
6939         for (i = 0; i < refs_size; i++)
6940                 if (!visitor(data, refs[i]))
6941                         break;
6944 static struct ref *
6945 get_ref_head()
6947         return refs_head;
6950 static struct ref_list *
6951 get_ref_list(const char *id)
6953         struct ref_list *list;
6954         size_t i;
6956         for (i = 0; i < ref_lists_size; i++)
6957                 if (!strcmp(id, ref_lists[i]->id))
6958                         return ref_lists[i];
6960         if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6961                 return NULL;
6962         list = calloc(1, sizeof(*list));
6963         if (!list)
6964                 return NULL;
6966         for (i = 0; i < refs_size; i++) {
6967                 if (!strcmp(id, refs[i]->id) &&
6968                     realloc_refs_list(&list->refs, list->size, 1))
6969                         list->refs[list->size++] = refs[i];
6970         }
6972         if (!list->refs) {
6973                 free(list);
6974                 return NULL;
6975         }
6977         qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6978         ref_lists[ref_lists_size++] = list;
6979         return list;
6982 static int
6983 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6985         struct ref *ref = NULL;
6986         bool tag = FALSE;
6987         bool ltag = FALSE;
6988         bool remote = FALSE;
6989         bool tracked = FALSE;
6990         bool head = FALSE;
6991         int from = 0, to = refs_size - 1;
6993         if (!prefixcmp(name, "refs/tags/")) {
6994                 if (!suffixcmp(name, namelen, "^{}")) {
6995                         namelen -= 3;
6996                         name[namelen] = 0;
6997                 } else {
6998                         ltag = TRUE;
6999                 }
7001                 tag = TRUE;
7002                 namelen -= STRING_SIZE("refs/tags/");
7003                 name    += STRING_SIZE("refs/tags/");
7005         } else if (!prefixcmp(name, "refs/remotes/")) {
7006                 remote = TRUE;
7007                 namelen -= STRING_SIZE("refs/remotes/");
7008                 name    += STRING_SIZE("refs/remotes/");
7009                 tracked  = !strcmp(opt_remote, name);
7011         } else if (!prefixcmp(name, "refs/heads/")) {
7012                 namelen -= STRING_SIZE("refs/heads/");
7013                 name    += STRING_SIZE("refs/heads/");
7014                 if (!strncmp(opt_head, name, namelen))
7015                         return OK;
7017         } else if (!strcmp(name, "HEAD")) {
7018                 head     = TRUE;
7019                 if (*opt_head) {
7020                         namelen  = strlen(opt_head);
7021                         name     = opt_head;
7022                 }
7023         }
7025         /* If we are reloading or it's an annotated tag, replace the
7026          * previous SHA1 with the resolved commit id; relies on the fact
7027          * git-ls-remote lists the commit id of an annotated tag right
7028          * before the commit id it points to. */
7029         while (from <= to) {
7030                 size_t pos = (to + from) / 2;
7031                 int cmp = strcmp(name, refs[pos]->name);
7033                 if (!cmp) {
7034                         ref = refs[pos];
7035                         break;
7036                 }
7038                 if (cmp < 0)
7039                         to = pos - 1;
7040                 else
7041                         from = pos + 1;
7042         }
7044         if (!ref) {
7045                 if (!realloc_refs(&refs, refs_size, 1))
7046                         return ERR;
7047                 ref = calloc(1, sizeof(*ref) + namelen);
7048                 if (!ref)
7049                         return ERR;
7050                 memmove(refs + from + 1, refs + from,
7051                         (refs_size - from) * sizeof(*refs));
7052                 refs[from] = ref;
7053                 strncpy(ref->name, name, namelen);
7054                 refs_size++;
7055         }
7057         ref->head = head;
7058         ref->tag = tag;
7059         ref->ltag = ltag;
7060         ref->remote = remote;
7061         ref->tracked = tracked;
7062         string_copy_rev(ref->id, id);
7064         if (head)
7065                 refs_head = ref;
7066         return OK;
7069 static int
7070 load_refs(void)
7072         const char *head_argv[] = {
7073                 "git", "symbolic-ref", "HEAD", NULL
7074         };
7075         static const char *ls_remote_argv[SIZEOF_ARG] = {
7076                 "git", "ls-remote", opt_git_dir, NULL
7077         };
7078         static bool init = FALSE;
7079         size_t i;
7081         if (!init) {
7082                 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7083                         die("TIG_LS_REMOTE contains too many arguments");
7084                 init = TRUE;
7085         }
7087         if (!*opt_git_dir)
7088                 return OK;
7090         if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7091             !prefixcmp(opt_head, "refs/heads/")) {
7092                 char *offset = opt_head + STRING_SIZE("refs/heads/");
7094                 memmove(opt_head, offset, strlen(offset) + 1);
7095         }
7097         refs_head = NULL;
7098         for (i = 0; i < refs_size; i++)
7099                 refs[i]->id[0] = 0;
7101         if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7102                 return ERR;
7104         /* Update the ref lists to reflect changes. */
7105         for (i = 0; i < ref_lists_size; i++) {
7106                 struct ref_list *list = ref_lists[i];
7107                 size_t old, new;
7109                 for (old = new = 0; old < list->size; old++)
7110                         if (!strcmp(list->id, list->refs[old]->id))
7111                                 list->refs[new++] = list->refs[old];
7112                 list->size = new;
7113         }
7115         return OK;
7118 static void
7119 set_remote_branch(const char *name, const char *value, size_t valuelen)
7121         if (!strcmp(name, ".remote")) {
7122                 string_ncopy(opt_remote, value, valuelen);
7124         } else if (*opt_remote && !strcmp(name, ".merge")) {
7125                 size_t from = strlen(opt_remote);
7127                 if (!prefixcmp(value, "refs/heads/"))
7128                         value += STRING_SIZE("refs/heads/");
7130                 if (!string_format_from(opt_remote, &from, "/%s", value))
7131                         opt_remote[0] = 0;
7132         }
7135 static void
7136 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7138         const char *argv[SIZEOF_ARG] = { name, "=" };
7139         int argc = 1 + (cmd == option_set_command);
7140         enum option_code error;
7142         if (!argv_from_string(argv, &argc, value))
7143                 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7144         else
7145                 error = cmd(argc, argv);
7147         if (error != OPT_OK)
7148                 warn("Option 'tig.%s': %s", name, option_errors[error]);
7151 static bool
7152 set_environment_variable(const char *name, const char *value)
7154         size_t len = strlen(name) + 1 + strlen(value) + 1;
7155         char *env = malloc(len);
7157         if (env &&
7158             string_nformat(env, len, NULL, "%s=%s", name, value) &&
7159             putenv(env) == 0)
7160                 return TRUE;
7161         free(env);
7162         return FALSE;
7165 static void
7166 set_work_tree(const char *value)
7168         char cwd[SIZEOF_STR];
7170         if (!getcwd(cwd, sizeof(cwd)))
7171                 die("Failed to get cwd path: %s", strerror(errno));
7172         if (chdir(opt_git_dir) < 0)
7173                 die("Failed to chdir(%s): %s", strerror(errno));
7174         if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7175                 die("Failed to get git path: %s", strerror(errno));
7176         if (chdir(cwd) < 0)
7177                 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7178         if (chdir(value) < 0)
7179                 die("Failed to chdir(%s): %s", value, strerror(errno));
7180         if (!getcwd(cwd, sizeof(cwd)))
7181                 die("Failed to get cwd path: %s", strerror(errno));
7182         if (!set_environment_variable("GIT_WORK_TREE", cwd))
7183                 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7184         if (!set_environment_variable("GIT_DIR", opt_git_dir))
7185                 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7186         opt_is_inside_work_tree = TRUE;
7189 static int
7190 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7192         if (!strcmp(name, "i18n.commitencoding"))
7193                 string_ncopy(opt_encoding, value, valuelen);
7195         else if (!strcmp(name, "core.editor"))
7196                 string_ncopy(opt_editor, value, valuelen);
7198         else if (!strcmp(name, "core.worktree"))
7199                 set_work_tree(value);
7201         else if (!prefixcmp(name, "tig.color."))
7202                 set_repo_config_option(name + 10, value, option_color_command);
7204         else if (!prefixcmp(name, "tig.bind."))
7205                 set_repo_config_option(name + 9, value, option_bind_command);
7207         else if (!prefixcmp(name, "tig."))
7208                 set_repo_config_option(name + 4, value, option_set_command);
7210         else if (*opt_head && !prefixcmp(name, "branch.") &&
7211                  !strncmp(name + 7, opt_head, strlen(opt_head)))
7212                 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7214         return OK;
7217 static int
7218 load_git_config(void)
7220         const char *config_list_argv[] = { "git", "config", "--list", NULL };
7222         return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7225 static int
7226 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7228         if (!opt_git_dir[0]) {
7229                 string_ncopy(opt_git_dir, name, namelen);
7231         } else if (opt_is_inside_work_tree == -1) {
7232                 /* This can be 3 different values depending on the
7233                  * version of git being used. If git-rev-parse does not
7234                  * understand --is-inside-work-tree it will simply echo
7235                  * the option else either "true" or "false" is printed.
7236                  * Default to true for the unknown case. */
7237                 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7239         } else if (*name == '.') {
7240                 string_ncopy(opt_cdup, name, namelen);
7242         } else {
7243                 string_ncopy(opt_prefix, name, namelen);
7244         }
7246         return OK;
7249 static int
7250 load_repo_info(void)
7252         const char *rev_parse_argv[] = {
7253                 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7254                         "--show-cdup", "--show-prefix", NULL
7255         };
7257         return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7261 /*
7262  * Main
7263  */
7265 static const char usage[] =
7266 "tig " TIG_VERSION " (" __DATE__ ")\n"
7267 "\n"
7268 "Usage: tig        [options] [revs] [--] [paths]\n"
7269 "   or: tig show   [options] [revs] [--] [paths]\n"
7270 "   or: tig blame  [rev] path\n"
7271 "   or: tig status\n"
7272 "   or: tig <      [git command output]\n"
7273 "\n"
7274 "Options:\n"
7275 "  -v, --version   Show version and exit\n"
7276 "  -h, --help      Show help message and exit";
7278 static void __NORETURN
7279 quit(int sig)
7281         /* XXX: Restore tty modes and let the OS cleanup the rest! */
7282         if (cursed)
7283                 endwin();
7284         exit(0);
7287 static void __NORETURN
7288 die(const char *err, ...)
7290         va_list args;
7292         endwin();
7294         va_start(args, err);
7295         fputs("tig: ", stderr);
7296         vfprintf(stderr, err, args);
7297         fputs("\n", stderr);
7298         va_end(args);
7300         exit(1);
7303 static void
7304 warn(const char *msg, ...)
7306         va_list args;
7308         va_start(args, msg);
7309         fputs("tig warning: ", stderr);
7310         vfprintf(stderr, msg, args);
7311         fputs("\n", stderr);
7312         va_end(args);
7315 static int
7316 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7318         const char ***filter_args = data;
7320         return argv_append(filter_args, name) ? OK : ERR;
7323 static void
7324 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7326         const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7327         const char **all_argv = NULL;
7329         if (!argv_append_array(&all_argv, rev_parse_argv) ||
7330             !argv_append_array(&all_argv, argv) ||
7331             !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7332                 die("Failed to split arguments");
7333         argv_free(all_argv);
7334         free(all_argv);
7337 static void
7338 filter_options(const char *argv[])
7340         filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7341         filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7342         filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7345 static enum request
7346 parse_options(int argc, const char *argv[])
7348         enum request request = REQ_VIEW_MAIN;
7349         const char *subcommand;
7350         bool seen_dashdash = FALSE;
7351         const char **filter_argv = NULL;
7352         int i;
7354         if (!isatty(STDIN_FILENO))
7355                 return REQ_VIEW_PAGER;
7357         if (argc <= 1)
7358                 return REQ_VIEW_MAIN;
7360         subcommand = argv[1];
7361         if (!strcmp(subcommand, "status")) {
7362                 if (argc > 2)
7363                         warn("ignoring arguments after `%s'", subcommand);
7364                 return REQ_VIEW_STATUS;
7366         } else if (!strcmp(subcommand, "blame")) {
7367                 if (argc <= 2 || argc > 4)
7368                         die("invalid number of options to blame\n\n%s", usage);
7370                 i = 2;
7371                 if (argc == 4) {
7372                         string_ncopy(opt_ref, argv[i], strlen(argv[i]));
7373                         i++;
7374                 }
7376                 string_ncopy(opt_file, argv[i], strlen(argv[i]));
7377                 return REQ_VIEW_BLAME;
7379         } else if (!strcmp(subcommand, "show")) {
7380                 request = REQ_VIEW_DIFF;
7382         } else {
7383                 subcommand = NULL;
7384         }
7386         for (i = 1 + !!subcommand; i < argc; i++) {
7387                 const char *opt = argv[i];
7389                 if (seen_dashdash) {
7390                         argv_append(&opt_file_argv, opt);
7391                         continue;
7393                 } else if (!strcmp(opt, "--")) {
7394                         seen_dashdash = TRUE;
7395                         continue;
7397                 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7398                         printf("tig version %s\n", TIG_VERSION);
7399                         quit(0);
7401                 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7402                         printf("%s\n", usage);
7403                         quit(0);
7405                 } else if (!strcmp(opt, "--all")) {
7406                         argv_append(&opt_rev_argv, opt);
7407                         continue;
7408                 }
7410                 if (!argv_append(&filter_argv, opt))
7411                         die("command too long");
7412         }
7414         if (filter_argv)
7415                 filter_options(filter_argv);
7417         return request;
7420 int
7421 main(int argc, const char *argv[])
7423         const char *codeset = "UTF-8";
7424         enum request request = parse_options(argc, argv);
7425         struct view *view;
7426         size_t i;
7428         signal(SIGINT, quit);
7429         signal(SIGPIPE, SIG_IGN);
7431         if (setlocale(LC_ALL, "")) {
7432                 codeset = nl_langinfo(CODESET);
7433         }
7435         if (load_repo_info() == ERR)
7436                 die("Failed to load repo info.");
7438         if (load_options() == ERR)
7439                 die("Failed to load user config.");
7441         if (load_git_config() == ERR)
7442                 die("Failed to load repo config.");
7444         /* Require a git repository unless when running in pager mode. */
7445         if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7446                 die("Not a git repository");
7448         if (*opt_encoding && strcmp(codeset, "UTF-8")) {
7449                 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
7450                 if (opt_iconv_in == ICONV_NONE)
7451                         die("Failed to initialize character set conversion");
7452         }
7454         if (codeset && strcmp(codeset, "UTF-8")) {
7455                 opt_iconv_out = iconv_open(codeset, "UTF-8");
7456                 if (opt_iconv_out == ICONV_NONE)
7457                         die("Failed to initialize character set conversion");
7458         }
7460         if (load_refs() == ERR)
7461                 die("Failed to load refs.");
7463         foreach_view (view, i) {
7464                 if (getenv(view->cmd_env))
7465                         warn("Use of the %s environment variable is deprecated,"
7466                              " use options or TIG_DIFF_ARGS instead",
7467                              view->cmd_env);
7468                 if (!argv_from_env(view->ops->argv, view->cmd_env))
7469                         die("Too many arguments in the `%s` environment variable",
7470                             view->cmd_env);
7471         }
7473         init_display();
7475         while (view_driver(display[current_view], request)) {
7476                 int key = get_input(0);
7478                 view = display[current_view];
7479                 request = get_keybinding(view->keymap, key);
7481                 /* Some low-level request handling. This keeps access to
7482                  * status_win restricted. */
7483                 switch (request) {
7484                 case REQ_NONE:
7485                         report("Unknown key, press %s for help",
7486                                get_key(view->keymap, REQ_VIEW_HELP));
7487                         break;
7488                 case REQ_PROMPT:
7489                 {
7490                         char *cmd = read_prompt(":");
7492                         if (cmd && isdigit(*cmd)) {
7493                                 int lineno = view->lineno + 1;
7495                                 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
7496                                         select_view_line(view, lineno - 1);
7497                                         report("");
7498                                 } else {
7499                                         report("Unable to parse '%s' as a line number", cmd);
7500                                 }
7502                         } else if (cmd) {
7503                                 struct view *next = VIEW(REQ_VIEW_PAGER);
7504                                 const char *argv[SIZEOF_ARG] = { "git" };
7505                                 int argc = 1;
7507                                 /* When running random commands, initially show the
7508                                  * command in the title. However, it maybe later be
7509                                  * overwritten if a commit line is selected. */
7510                                 string_ncopy(next->ref, cmd, strlen(cmd));
7512                                 if (!argv_from_string(argv, &argc, cmd)) {
7513                                         report("Too many arguments");
7514                                 } else if (!prepare_update(next, argv, NULL)) {
7515                                         report("Failed to format command");
7516                                 } else {
7517                                         open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7518                                 }
7519                         }
7521                         request = REQ_NONE;
7522                         break;
7523                 }
7524                 case REQ_SEARCH:
7525                 case REQ_SEARCH_BACK:
7526                 {
7527                         const char *prompt = request == REQ_SEARCH ? "/" : "?";
7528                         char *search = read_prompt(prompt);
7530                         if (search)
7531                                 string_ncopy(opt_search, search, strlen(search));
7532                         else if (*opt_search)
7533                                 request = request == REQ_SEARCH ?
7534                                         REQ_FIND_NEXT :
7535                                         REQ_FIND_PREV;
7536                         else
7537                                 request = REQ_NONE;
7538                         break;
7539                 }
7540                 default:
7541                         break;
7542                 }
7543         }
7545         quit(0);
7547         return 0;