Improve documentation; optional tab size; move up/down + enter req; fix wrapping
[tig] / tig.c
1 /* Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
2  * See license info at the bottom. */
3 /**
4  * TIG(1)
5  * ======
6  *
7  * NAME
8  * ----
9  * tig - text-mode interface for git
10  *
11  * SYNOPSIS
12  * --------
13  * [verse]
14  * tig [options]
15  * tig [options] [--] [git log options]
16  * tig [options] log  [git log options]
17  * tig [options] diff [git diff options]
18  * tig [options] show [git show options]
19  * tig [options] <    [git command output]
20  *
21  * DESCRIPTION
22  * -----------
23  * Browse changes in a git repository. Additionally, tig(1) can also act
24  * as a pager for output of various git commands.
25  *
26  * Commit limiting
27  * ~~~~~~~~~~~~~~~
28  * To speed up interaction with git, you can limit the amount of commits
29  * to show both for the log and main view. Either limit by date using
30  * e.g. `--since=1.month` or limit by the number of commits using `-n400`.
31  *
32  * Alternatively, commits can be limited to a specific range, such as
33  * "all commits between tag-1.0 and tag-2.0". For example:
34  *
35  *      $ tig log tag-1.0..tag-2.0
36  *
37  * Git interprets this as "all commits reachable from commit-2
38  * but not from commit-1". The above can also be written:
39  *
40  *      $ tig log tag-2.0 ^tag-1.0
41  *
42  * You can think of '^' as a negator. Using this alternate syntax,
43  * it is possible to furthur prune commits by specifying multiple
44  * negators.
45  *
46  * This way of commit limiting makes it trivial to only browse the commit
47  * which hasn't been pushed to a remote branch. Assuming origin is your
48  * upstream remote branch, using:
49  *
50  *      $ tig log origin..HEAD
51  *
52  * Optionally, with "HEAD" left out, will list what will be pushed to
53  * the remote branch.
54  *
55  * See the section on environment variables, on how to further tune the
56  * interaction with git.
57  **/
58
59 #ifndef VERSION
60 #define VERSION "tig-0.1"
61 #endif
62
63 #ifndef DEBUG
64 #define NDEBUG
65 #endif
66
67 #include <assert.h>
68 #include <errno.h>
69 #include <ctype.h>
70 #include <signal.h>
71 #include <stdarg.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <time.h>
77
78 #include <curses.h>
79
80 static void die(const char *err, ...);
81 static void report(const char *msg, ...);
82 static void set_nonblocking_input(bool loading);
83
84 #define ABS(x)          ((x) >= 0  ? (x) : -(x))
85 #define MIN(x, y)       ((x) < (y) ? (x) :  (y))
86
87 #define ARRAY_SIZE(x)   (sizeof(x) / sizeof(x[0]))
88 #define STRING_SIZE(x)  (sizeof(x) - 1)
89
90 #define SIZEOF_REF      256     /* Size of symbolic or SHA1 ID. */
91 #define SIZEOF_CMD      1024    /* Size of command buffer. */
92
93 /* This color name can be used to refer to the default term colors. */
94 #define COLOR_DEFAULT   (-1)
95
96 /* The format and size of the date column in the main view. */
97 #define DATE_FORMAT     "%Y-%m-%d %H:%M"
98 #define DATE_COLS       STRING_SIZE("2006-04-29 14:21 ")
99
100 /* The default interval between line numbers. */
101 #define NUMBER_INTERVAL 1
102
103 #define TABSIZE         8
104
105 #define SCALE_SPLIT_VIEW(height)        ((height) * 2 / 3)
106
107 /* Some ascii-shorthands fitted into the ncurses namespace. */
108 #define KEY_TAB         '\t'
109 #define KEY_RETURN      '\r'
110 #define KEY_ESC         27
111
112
113 /* User action requests. */
114 enum request {
115         /* Offset all requests to avoid conflicts with ncurses getch values. */
116         REQ_OFFSET = KEY_MAX + 1,
117
118         /* XXX: Keep the view request first and in sync with views[]. */
119         REQ_VIEW_MAIN,
120         REQ_VIEW_DIFF,
121         REQ_VIEW_LOG,
122         REQ_VIEW_HELP,
123         REQ_VIEW_PAGER,
124
125         REQ_ENTER,
126         REQ_QUIT,
127         REQ_PROMPT,
128         REQ_SCREEN_REDRAW,
129         REQ_SCREEN_RESIZE,
130         REQ_SCREEN_UPDATE,
131         REQ_SHOW_VERSION,
132         REQ_STOP_LOADING,
133         REQ_TOGGLE_LINE_NUMBERS,
134         REQ_VIEW_NEXT,
135
136         REQ_MOVE_UP,
137         REQ_MOVE_UP_ENTER,
138         REQ_MOVE_DOWN,
139         REQ_MOVE_DOWN_ENTER,
140         REQ_MOVE_PAGE_UP,
141         REQ_MOVE_PAGE_DOWN,
142         REQ_MOVE_FIRST_LINE,
143         REQ_MOVE_LAST_LINE,
144
145         REQ_SCROLL_LINE_UP,
146         REQ_SCROLL_LINE_DOWN,
147         REQ_SCROLL_PAGE_UP,
148         REQ_SCROLL_PAGE_DOWN,
149 };
150
151 struct ref {
152         char *name;
153         char id[41];
154         unsigned int tag:1;
155         unsigned int next:1;
156 };
157
158 struct commit {
159         char id[41];            /* SHA1 ID. */
160         char title[75];         /* The first line of the commit message. */
161         char author[75];        /* The author of the commit. */
162         struct tm time;         /* Date from the author ident. */
163         struct ref **refs;      /* Repository references; tags & branch heads. */
164 };
165
166
167 /*
168  * String helpers
169  */
170
171 static inline void
172 string_ncopy(char *dst, char *src, int dstlen)
173 {
174         strncpy(dst, src, dstlen - 1);
175         dst[dstlen - 1] = 0;
176
177 }
178
179 /* Shorthand for safely copying into a fixed buffer. */
180 #define string_copy(dst, src) \
181         string_ncopy(dst, src, sizeof(dst))
182
183
184 /* Shell quoting
185  *
186  * NOTE: The following is a slightly modified copy of the git project's shell
187  * quoting routines found in the quote.c file.
188  *
189  * Help to copy the thing properly quoted for the shell safety.  any single
190  * quote is replaced with '\'', any exclamation point is replaced with '\!',
191  * and the whole thing is enclosed in a
192  *
193  * E.g.
194  *  original     sq_quote     result
195  *  name     ==> name      ==> 'name'
196  *  a b      ==> a b       ==> 'a b'
197  *  a'b      ==> a'\''b    ==> 'a'\''b'
198  *  a!b      ==> a'\!'b    ==> 'a'\!'b'
199  */
200
201 static size_t
202 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
203 {
204         char c;
205
206 #define BUFPUT(x) ( (bufsize < SIZEOF_CMD) && (buf[bufsize++] = (x)) )
207
208         BUFPUT('\'');
209         while ((c = *src++)) {
210                 if (c == '\'' || c == '!') {
211                         BUFPUT('\'');
212                         BUFPUT('\\');
213                         BUFPUT(c);
214                         BUFPUT('\'');
215                 } else {
216                         BUFPUT(c);
217                 }
218         }
219         BUFPUT('\'');
220
221         return bufsize;
222 }
223
224
225 /**
226  * OPTIONS
227  * -------
228  **/
229
230 /* Option and state variables. */
231 static bool opt_line_number     = FALSE;
232 static int opt_num_interval     = NUMBER_INTERVAL;
233 static int opt_tab_size         = TABSIZE;
234 static enum request opt_request = REQ_VIEW_MAIN;
235 static char opt_cmd[SIZEOF_CMD] = "";
236 static FILE *opt_pipe           = NULL;
237
238 /* Returns the index of log or diff command or -1 to exit. */
239 static bool
240 parse_options(int argc, char *argv[])
241 {
242         int i;
243
244         for (i = 1; i < argc; i++) {
245                 char *opt = argv[i];
246
247                 /**
248                  * -l::
249                  *      Start up in log view using the internal log command.
250                  **/
251                 if (!strcmp(opt, "-l")) {
252                         opt_request = REQ_VIEW_LOG;
253                         continue;
254                 }
255
256                 /**
257                  * -d::
258                  *      Start up in diff view using the internal diff command.
259                  **/
260                 if (!strcmp(opt, "-d")) {
261                         opt_request = REQ_VIEW_DIFF;
262                         continue;
263                 }
264
265                 /**
266                  * -n[INTERVAL], --line-number[=INTERVAL]::
267                  *      Prefix line numbers in log and diff view.
268                  *      Optionally, with interval different than each line.
269                  **/
270                 if (!strncmp(opt, "-n", 2) ||
271                     !strncmp(opt, "--line-number", 13)) {
272                         char *num = opt;
273
274                         if (opt[1] == 'n') {
275                                 num = opt + 2;
276
277                         } else if (opt[STRING_SIZE("--line-number")] == '=') {
278                                 num = opt + STRING_SIZE("--line-number=");
279                         }
280
281                         if (isdigit(*num))
282                                 opt_num_interval = atoi(num);
283
284                         opt_line_number = TRUE;
285                         continue;
286                 }
287
288                 /**
289                  * -t[NSPACES], --tab-size[=NSPACES]::
290                  *      Set the number of spaces tabs should be expanded to.
291                  **/
292                 if (!strncmp(opt, "-t", 2) ||
293                     !strncmp(opt, "--tab-size", 10)) {
294                         char *num = opt;
295
296                         if (opt[1] == 't') {
297                                 num = opt + 2;
298
299                         } else if (opt[STRING_SIZE("--tab-size")] == '=') {
300                                 num = opt + STRING_SIZE("--tab-size=");
301                         }
302
303                         if (isdigit(*num))
304                                 opt_tab_size = MIN(atoi(num), TABSIZE);
305                         continue;
306                 }
307
308                 /**
309                  * -v, --version::
310                  *      Show version and exit.
311                  **/
312                 if (!strcmp(opt, "-v") ||
313                     !strcmp(opt, "--version")) {
314                         printf("tig version %s\n", VERSION);
315                         return FALSE;
316                 }
317
318                 /**
319                  * \--::
320                  *      End of tig(1) options. Useful when specifying commands
321                  *      for the main view. Example:
322                  *
323                  *              $ tig -- --since=1.month
324                  **/
325                 if (!strcmp(opt, "--")) {
326                         i++;
327                         break;
328                 }
329
330                 /**
331                  * log [options]::
332                  *      Open log view using the given git log options.
333                  *
334                  * diff [options]::
335                  *      Open diff view using the given git diff options.
336                  *
337                  * show [options]::
338                  *      Open diff view using the given git show options.
339                  **/
340                 if (!strcmp(opt, "log") ||
341                     !strcmp(opt, "diff") ||
342                     !strcmp(opt, "show")) {
343                         opt_request = opt[0] == 'l'
344                                     ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
345                         break;
346                 }
347
348                 /* Make stuff like:
349                  *
350                  *      $ tig tag-1.0..HEAD
351                  *
352                  * work. */
353                 if (opt[0] && opt[0] != '-')
354                         break;
355
356                 die("unknown command '%s'", opt);
357         }
358
359         if (!isatty(STDIN_FILENO)) {
360                 /**
361                  * Pager mode
362                  * ~~~~~~~~~~
363                  * If stdin is a pipe, any log or diff options will be ignored and the
364                  * pager view will be opened loading data from stdin. The pager mode
365                  * can be used for colorizing output from various git commands.
366                  *
367                  * Example on how to colorize the output of git-show(1):
368                  *
369                  *      $ git show | tig
370                  **/
371                 opt_request = REQ_VIEW_PAGER;
372                 opt_pipe = stdin;
373
374         } else if (i < argc) {
375                 size_t buf_size;
376
377                 /**
378                  * Git command options
379                  * ~~~~~~~~~~~~~~~~~~~
380                  * All git command options specified on the command line will
381                  * be passed to the given command and all will be shell quoted
382                  * before used.
383                  *
384                  * NOTE: It is possible to specify options even for the main
385                  * view. If doing this you should not touch the `--pretty`
386                  * option.
387                  *
388                  * Example on how to open the log view and show both author and
389                  * committer information:
390                  *
391                  *      $ tig log --pretty=fuller
392                  **/
393
394                 if (opt_request == REQ_VIEW_MAIN)
395                         /* XXX: This is vulnerable to the user overriding
396                          * options required for the main view parser. */
397                         string_copy(opt_cmd, "git log --stat --pretty=raw");
398                 else
399                         string_copy(opt_cmd, "git");
400                 buf_size = strlen(opt_cmd);
401
402                 while (buf_size < sizeof(opt_cmd) && i < argc) {
403                         opt_cmd[buf_size++] = ' ';
404                         buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
405                 }
406
407                 if (buf_size >= sizeof(opt_cmd))
408                         die("command too long");
409
410                 opt_cmd[buf_size] = 0;
411
412         }
413
414         return TRUE;
415 }
416
417
418 /**
419  * KEYS
420  * ----
421  * Below the default key bindings are shown.
422  **/
423
424 #define HELP "(d)iff, (l)og, (m)ain, (q)uit, (v)ersion, (h)elp"
425
426 struct keymap {
427         int alias;
428         int request;
429 };
430
431 struct keymap keymap[] = {
432         /**
433          * View switching
434          * ~~~~~~~~~~~~~~
435          * d::
436          *      Switch to diff view.
437          * l::
438          *      Switch to log view.
439          * m::
440          *      Switch to main view.
441          * p::
442          *      Switch to pager view.
443          * h::
444          *      Show man page.
445          * Return::
446          *      If on a commit line show the commit diff. Addiionally, if in
447          *      main or log view this will split the view. To open the commit
448          *      diff in full size view either use 'd' or press Return twice.
449          *
450          * Tab::
451          *      Switch to next view.
452          **/
453         { 'm',          REQ_VIEW_MAIN },
454         { 'd',          REQ_VIEW_DIFF },
455         { 'l',          REQ_VIEW_LOG },
456         { 'p',          REQ_VIEW_PAGER },
457         { 'h',          REQ_VIEW_HELP },
458
459         { KEY_TAB,      REQ_VIEW_NEXT },
460         { KEY_RETURN,   REQ_ENTER },
461
462         /**
463          * Cursor navigation
464          * ~~~~~~~~~~~~~~~~~
465          * Up::
466          *      Move curser one line up.
467          * Down::
468          *      Move cursor one line down.
469          * k::
470          *
471          *      Move curser one line up and enter. When used in the main view
472          *      this will always show the diff of the current commit in the
473          *      split diff view.
474          *
475          * j::
476          *      Move cursor one line down and enter.
477          * PgUp::
478          *      Move curser one page up.
479          * PgDown::
480          *      Move cursor one page down.
481          * Home::
482          *      Jump to first line.
483          * End::
484          *      Jump to last line.
485          **/
486         { KEY_UP,       REQ_MOVE_UP },
487         { KEY_DOWN,     REQ_MOVE_DOWN },
488         { 'k',          REQ_MOVE_UP_ENTER },
489         { 'j',          REQ_MOVE_DOWN_ENTER },
490         { KEY_HOME,     REQ_MOVE_FIRST_LINE },
491         { KEY_END,      REQ_MOVE_LAST_LINE },
492         { KEY_NPAGE,    REQ_MOVE_PAGE_DOWN },
493         { KEY_PPAGE,    REQ_MOVE_PAGE_UP },
494
495         /**
496          * Scrolling
497          * ~~~~~~~~~
498          * Insert::
499          *      Scroll view one line up.
500          * Delete::
501          *      Scroll view one line down.
502          * w::
503          *      Scroll view one page up.
504          * s::
505          *      Scroll view one page down.
506          **/
507         { KEY_IC,       REQ_SCROLL_LINE_UP },
508         { KEY_DC,       REQ_SCROLL_LINE_DOWN },
509         { 'w',          REQ_SCROLL_PAGE_UP },
510         { 's',          REQ_SCROLL_PAGE_DOWN },
511
512         /**
513          * Misc
514          * ~~~~
515          * q::
516          *      Quit
517          * r::
518          *      Redraw screen.
519          * z::
520          *      Stop all background loading. This can be useful if you ran
521          *      tig(1) in a repository with a long history without limiting
522          *      the log output.
523          * v::
524          *      Show version.
525          * n::
526          *      Toggle line numbers on/off.
527          * ':'::
528          *      Open prompt. This allows you to specify what git command
529          *      to run. Example:
530          *
531          *      :log -p
532          *
533          **/
534         { 'q',          REQ_QUIT },
535         { 'z',          REQ_STOP_LOADING },
536         { 'v',          REQ_SHOW_VERSION },
537         { 'r',          REQ_SCREEN_REDRAW },
538         { 'n',          REQ_TOGGLE_LINE_NUMBERS },
539         { ':',          REQ_PROMPT },
540
541         /* wgetch() with nodelay() enabled returns ERR when there's no input. */
542         { ERR,          REQ_SCREEN_UPDATE },
543
544         /* Use the ncurses SIGWINCH handler. */
545         { KEY_RESIZE,   REQ_SCREEN_RESIZE },
546 };
547
548 static enum request
549 get_request(int key)
550 {
551         int i;
552
553         for (i = 0; i < ARRAY_SIZE(keymap); i++)
554                 if (keymap[i].alias == key)
555                         return keymap[i].request;
556
557         return (enum request) key;
558 }
559
560
561 /*
562  * Line-oriented content detection.
563  */
564
565 #define LINE_INFO \
566 /*   Line type     String to match      Foreground      Background      Attributes
567  *   ---------     ---------------      ----------      ----------      ---------- */ \
568 /* Diff markup */ \
569 LINE(DIFF,         "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
570 LINE(DIFF_INDEX,   "index ",            COLOR_BLUE,     COLOR_DEFAULT,  0), \
571 LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
572 LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0), \
573 LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0), \
574 LINE(DIFF_OLDMODE, "old file mode ",    COLOR_YELLOW,   COLOR_DEFAULT,  0), \
575 LINE(DIFF_NEWMODE, "new file mode ",    COLOR_YELLOW,   COLOR_DEFAULT,  0), \
576 LINE(DIFF_COPY,    "copy ",             COLOR_YELLOW,   COLOR_DEFAULT,  0), \
577 LINE(DIFF_RENAME,  "rename ",           COLOR_YELLOW,   COLOR_DEFAULT,  0), \
578 LINE(DIFF_SIM,     "similarity ",       COLOR_YELLOW,   COLOR_DEFAULT,  0), \
579 LINE(DIFF_DISSIM,  "dissimilarity ",    COLOR_YELLOW,   COLOR_DEFAULT,  0), \
580 /* Pretty print commit header */ \
581 LINE(PP_AUTHOR,    "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0), \
582 LINE(PP_COMMIT,    "Commit: ",          COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
583 LINE(PP_MERGE,     "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
584 LINE(PP_DATE,      "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0), \
585 LINE(PP_ADATE,     "AuthorDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
586 LINE(PP_CDATE,     "CommitDate: ",      COLOR_YELLOW,   COLOR_DEFAULT,  0), \
587 /* Raw commit header */ \
588 LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0), \
589 LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0), \
590 LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0), \
591 LINE(AUTHOR,       "author ",           COLOR_CYAN,     COLOR_DEFAULT,  0), \
592 LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
593 /* Misc */ \
594 LINE(DIFF_TREE,    "diff-tree ",        COLOR_BLUE,     COLOR_DEFAULT,  0), \
595 LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0), \
596 /* UI colors */ \
597 LINE(DEFAULT,      "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL), \
598 LINE(CURSOR,       "",                  COLOR_WHITE,    COLOR_GREEN,    A_BOLD), \
599 LINE(STATUS,       "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
600 LINE(TITLE_BLUR,   "",                  COLOR_WHITE,    COLOR_BLUE,     0), \
601 LINE(TITLE_FOCUS,  "",                  COLOR_WHITE,    COLOR_BLUE,     A_BOLD), \
602 LINE(MAIN_DATE,    "",                  COLOR_BLUE,     COLOR_DEFAULT,  0), \
603 LINE(MAIN_AUTHOR,  "",                  COLOR_GREEN,    COLOR_DEFAULT,  0), \
604 LINE(MAIN_COMMIT,  "",                  COLOR_DEFAULT,  COLOR_DEFAULT,  0), \
605 LINE(MAIN_DELIM,   "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  0), \
606 LINE(MAIN_TAG,     "",                  COLOR_MAGENTA,  COLOR_DEFAULT,  A_BOLD), \
607 LINE(MAIN_REF,     "",                  COLOR_CYAN,     COLOR_DEFAULT,  A_BOLD),
608
609 enum line_type {
610 #define LINE(type, line, fg, bg, attr) \
611         LINE_##type
612         LINE_INFO
613 #undef  LINE
614 };
615
616 struct line_info {
617         char *line;             /* The start of line to match. */
618         int linelen;            /* Size of string to match. */
619         int fg, bg, attr;       /* Color and text attributes for the lines. */
620 };
621
622 static struct line_info line_info[] = {
623 #define LINE(type, line, fg, bg, attr) \
624         { (line), STRING_SIZE(line), (fg), (bg), (attr) }
625         LINE_INFO
626 #undef  LINE
627 };
628
629 static enum line_type
630 get_line_type(char *line)
631 {
632         int linelen = strlen(line);
633         enum line_type type;
634
635         for (type = 0; type < ARRAY_SIZE(line_info); type++)
636                 /* Case insensitive search matches Signed-off-by lines better. */
637                 if (linelen >= line_info[type].linelen &&
638                     !strncasecmp(line_info[type].line, line, line_info[type].linelen))
639                         return type;
640
641         return LINE_DEFAULT;
642 }
643
644 static inline int
645 get_line_attr(enum line_type type)
646 {
647         assert(type < ARRAY_SIZE(line_info));
648         return COLOR_PAIR(type) | line_info[type].attr;
649 }
650
651 static void
652 init_colors(void)
653 {
654         int default_bg = COLOR_BLACK;
655         int default_fg = COLOR_WHITE;
656         enum line_type type;
657
658         start_color();
659
660         if (use_default_colors() != ERR) {
661                 default_bg = -1;
662                 default_fg = -1;
663         }
664
665         for (type = 0; type < ARRAY_SIZE(line_info); type++) {
666                 struct line_info *info = &line_info[type];
667                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
668                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
669
670                 init_pair(type, fg, bg);
671         }
672 }
673
674
675 /**
676  * ENVIRONMENT VARIABLES
677  * ---------------------
678  * Several options related to the interface with git can be configured
679  * via environment options.
680  *
681  * Repository references
682  * ~~~~~~~~~~~~~~~~~~~~~
683  * Commits that are referenced by tags and branch heads will be marked
684  * by the reference name surrounded by '[' and ']':
685  *
686  *      2006-04-18 23:12 Jonas Fonseca       | [tig-0.2] tig version 0.2
687  *
688  * If you want to filter out certain directories under `.git/refs/`, say
689  * `tmp` you can do it by setting the following variable:
690  *
691  *      $ TIG_LS_REMOTE="git ls-remote . | sed /\/tmp\//d" tig
692  *
693  * Or set the variable permanently in your environment.
694  *
695  * TIG_LS_REMOTE::
696  *      Set command for retrieving all repository references. The command
697  *      should output data in the same format as git-ls-remote(1).
698  **/
699
700 #define TIG_LS_REMOTE \
701         "git ls-remote ."
702
703 /**
704  * View commands
705  * ~~~~~~~~~~~~~
706  * It is possible to alter which commands are used for the different views.
707  * If for example you prefer commits in the main view to be sorted by date
708  * and only show 500 commits, use:
709  *
710  *      $ TIG_MAIN_CMD="git log --date-order -n500 --pretty=raw %s" tig
711  *
712  * Or set the variable permanently in your environment.
713  *
714  * Notice, how `%s` is used to specify the commit reference. There can
715  * be a maximum of 5 `%s` ref specifications.
716  *
717  * TIG_DIFF_CMD::
718  *      The command used for the diff view. By default, git show is used
719  *      as a backend.
720  *
721  * TIG_LOG_CMD::
722  *      The command used for the log view. If you prefer to have both
723  *      author and committer shown in the log view be sure to pass
724  *      `--pretty=fuller` to git log.
725  *
726  * TIG_MAIN_CMD::
727  *      The command used for the main view. Note, you must always specify
728  *      the option: `--pretty=raw` since the main view parser expects to
729  *      read that format.
730  **/
731
732 #define TIG_DIFF_CMD \
733         "git show --patch-with-stat --find-copies-harder -B -C %s"
734
735 #define TIG_LOG_CMD     \
736         "git log --cc --stat -n100 %s"
737
738 #define TIG_MAIN_CMD \
739         "git log --topo-order --stat --pretty=raw %s"
740
741 /* We silently ignore that the following are also exported. */
742
743 #define TIG_HELP_CMD \
744         "man tig 2> /dev/null"
745
746 #define TIG_PAGER_CMD \
747         ""
748
749
750 /*
751  * Viewer
752  */
753
754 struct view {
755         const char *name;       /* View name */
756         char *cmd_fmt;          /* Default command line format */
757         char *cmd_env;          /* Command line set via environment */
758         char *id;               /* Points to either of ref_{head,commit} */
759         size_t objsize;         /* Size of objects in the line index */
760
761         struct view_ops {
762                 /* What type of content being displayed. Used in the
763                  * title bar. */
764                 char *type;
765                 /* Draw one line; @lineno must be < view->height. */
766                 bool (*draw)(struct view *view, unsigned int lineno);
767                 /* Read one line; updates view->line. */
768                 bool (*read)(struct view *view, char *line);
769                 /* Depending on view, change display based on current line. */
770                 bool (*enter)(struct view *view);
771         } *ops;
772
773         char cmd[SIZEOF_CMD];   /* Command buffer */
774         char ref[SIZEOF_REF];   /* Hovered commit reference */
775         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
776
777         int height, width;      /* The width and height of the main window */
778         WINDOW *win;            /* The main window */
779         WINDOW *title;          /* The title window living below the main window */
780
781         /* Navigation */
782         unsigned long offset;   /* Offset of the window top */
783         unsigned long lineno;   /* Current line number */
784
785         /* Buffering */
786         unsigned long lines;    /* Total number of lines */
787         void **line;            /* Line index; each line contains user data */
788         unsigned int digits;    /* Number of digits in the lines member. */
789
790         /* Loading */
791         FILE *pipe;
792         time_t start_time;
793 };
794
795 static struct view_ops pager_ops;
796 static struct view_ops main_ops;
797
798 char ref_head[SIZEOF_REF]       = "HEAD";
799 char ref_commit[SIZEOF_REF]     = "HEAD";
800
801 #define VIEW_STR(name, cmd, env, ref, objsize, ops) \
802         { name, cmd, #env, ref, objsize, ops }
803
804 #define VIEW_(id, name, ops, ref, objsize) \
805         VIEW_STR(name, TIG_##id##_CMD,  TIG_##id##_CMD, ref, objsize, ops)
806
807 static struct view views[] = {
808         VIEW_(MAIN,  "main",  &main_ops,  ref_head,   sizeof(struct commit)),
809         VIEW_(DIFF,  "diff",  &pager_ops, ref_commit, sizeof(char)),
810         VIEW_(LOG,   "log",   &pager_ops, ref_head,   sizeof(char)),
811         VIEW_(HELP,  "help",  &pager_ops, ref_head,   sizeof(char)),
812         VIEW_(PAGER, "pager", &pager_ops, "static",   sizeof(char)),
813 };
814
815 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
816
817 /* The display array of active views and the index of the current view. */
818 static struct view *display[2];
819 static unsigned int current_view;
820
821 #define foreach_view(view, i) \
822         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
823
824
825 static void
826 redraw_view_from(struct view *view, int lineno)
827 {
828         assert(0 <= lineno && lineno < view->height);
829
830         for (; lineno < view->height; lineno++) {
831                 if (!view->ops->draw(view, lineno))
832                         break;
833         }
834
835         redrawwin(view->win);
836         wrefresh(view->win);
837 }
838
839 static void
840 redraw_view(struct view *view)
841 {
842         wclear(view->win);
843         redraw_view_from(view, 0);
844 }
845
846 static void
847 resize_display(void)
848 {
849         int offset, i;
850         struct view *base = display[0];
851         struct view *view = display[1] ? display[1] : display[0];
852
853         /* Setup window dimensions */
854
855         getmaxyx(stdscr, base->height, base->width);
856
857         /* Make room for the status window. */
858         base->height -= 1;
859
860         if (view != base) {
861                 /* Horizontal split. */
862                 view->width   = base->width;
863                 view->height  = SCALE_SPLIT_VIEW(base->height);
864                 base->height -= view->height;
865
866                 /* Make room for the title bar. */
867                 view->height -= 1;
868         }
869
870         /* Make room for the title bar. */
871         base->height -= 1;
872
873         offset = 0;
874
875         foreach_view (view, i) {
876                 /* Keep the size of the all view windows one lager than is
877                  * required. This makes current line management easier when the
878                  * cursor will go outside the window. */
879                 if (!view->win) {
880                         view->win = newwin(view->height + 1, 0, offset, 0);
881                         if (!view->win)
882                                 die("Failed to create %s view", view->name);
883
884                         scrollok(view->win, TRUE);
885
886                         view->title = newwin(1, 0, offset + view->height, 0);
887                         if (!view->title)
888                                 die("Failed to create title window");
889
890                 } else {
891                         wresize(view->win, view->height + 1, view->width);
892                         mvwin(view->win,   offset, 0);
893                         mvwin(view->title, offset + view->height, 0);
894                         wrefresh(view->win);
895                 }
896
897                 offset += view->height + 1;
898         }
899 }
900
901 static void
902 update_view_title(struct view *view)
903 {
904         if (view == display[current_view])
905                 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
906         else
907                 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
908
909         werase(view->title);
910         wmove(view->title, 0, 0);
911
912         /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
913
914         if (*view->ref)
915                 wprintw(view->title, "[%s] ref: %s", view->name, view->ref);
916         else
917                 wprintw(view->title, "[%s]", view->name);
918
919         if (view->lines) {
920                 wprintw(view->title, " - %s %d of %d (%d%%)",
921                         view->ops->type,
922                         view->lineno + 1,
923                         view->lines,
924                         (view->lineno + 1) * 100 / view->lines);
925         }
926
927         wrefresh(view->title);
928 }
929
930 /*
931  * Navigation
932  */
933
934 /* Scrolling backend */
935 static void
936 do_scroll_view(struct view *view, int lines)
937 {
938         /* The rendering expects the new offset. */
939         view->offset += lines;
940
941         assert(0 <= view->offset && view->offset < view->lines);
942         assert(lines);
943
944         /* Redraw the whole screen if scrolling is pointless. */
945         if (view->height < ABS(lines)) {
946                 redraw_view(view);
947
948         } else {
949                 int line = lines > 0 ? view->height - lines : 0;
950                 int end = line + ABS(lines);
951
952                 wscrl(view->win, lines);
953
954                 for (; line < end; line++) {
955                         if (!view->ops->draw(view, line))
956                                 break;
957                 }
958         }
959
960         /* Move current line into the view. */
961         if (view->lineno < view->offset) {
962                 view->lineno = view->offset;
963                 view->ops->draw(view, 0);
964
965         } else if (view->lineno >= view->offset + view->height) {
966                 if (view->lineno == view->offset + view->height) {
967                         /* Clear the hidden line so it doesn't show if the view
968                          * is scrolled up. */
969                         wmove(view->win, view->height, 0);
970                         wclrtoeol(view->win);
971                 }
972                 view->lineno = view->offset + view->height - 1;
973                 view->ops->draw(view, view->lineno - view->offset);
974         }
975
976         assert(view->offset <= view->lineno && view->lineno < view->lines);
977
978         redrawwin(view->win);
979         wrefresh(view->win);
980         report("");
981 }
982
983 /* Scroll frontend */
984 static void
985 scroll_view(struct view *view, enum request request)
986 {
987         int lines = 1;
988
989         switch (request) {
990         case REQ_SCROLL_PAGE_DOWN:
991                 lines = view->height;
992         case REQ_SCROLL_LINE_DOWN:
993                 if (view->offset + lines > view->lines)
994                         lines = view->lines - view->offset;
995
996                 if (lines == 0 || view->offset + view->height >= view->lines) {
997                         report("Cannot scroll beyond the last line");
998                         return;
999                 }
1000                 break;
1001
1002         case REQ_SCROLL_PAGE_UP:
1003                 lines = view->height;
1004         case REQ_SCROLL_LINE_UP:
1005                 if (lines > view->offset)
1006                         lines = view->offset;
1007
1008                 if (lines == 0) {
1009                         report("Cannot scroll beyond the first line");
1010                         return;
1011                 }
1012
1013                 lines = -lines;
1014                 break;
1015
1016         default:
1017                 die("request %d not handled in switch", request);
1018         }
1019
1020         do_scroll_view(view, lines);
1021 }
1022
1023 /* Cursor moving */
1024 static void
1025 move_view(struct view *view, enum request request)
1026 {
1027         int steps;
1028
1029         switch (request) {
1030         case REQ_MOVE_FIRST_LINE:
1031                 steps = -view->lineno;
1032                 break;
1033
1034         case REQ_MOVE_LAST_LINE:
1035                 steps = view->lines - view->lineno - 1;
1036                 break;
1037
1038         case REQ_MOVE_PAGE_UP:
1039                 steps = view->height > view->lineno
1040                       ? -view->lineno : -view->height;
1041                 break;
1042
1043         case REQ_MOVE_PAGE_DOWN:
1044                 steps = view->lineno + view->height >= view->lines
1045                       ? view->lines - view->lineno - 1 : view->height;
1046                 break;
1047
1048         case REQ_MOVE_UP:
1049         case REQ_MOVE_UP_ENTER:
1050                 steps = -1;
1051                 break;
1052
1053         case REQ_MOVE_DOWN:
1054         case REQ_MOVE_DOWN_ENTER:
1055                 steps = 1;
1056                 break;
1057
1058         default:
1059                 die("request %d not handled in switch", request);
1060         }
1061
1062         if (steps <= 0 && view->lineno == 0) {
1063                 report("Cannot move beyond the first line");
1064                 return;
1065
1066         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
1067                 report("Cannot move beyond the last line");
1068                 return;
1069         }
1070
1071         /* Move the current line */
1072         view->lineno += steps;
1073         assert(0 <= view->lineno && view->lineno < view->lines);
1074
1075         /* Repaint the old "current" line if we be scrolling */
1076         if (ABS(steps) < view->height) {
1077                 int prev_lineno = view->lineno - steps - view->offset;
1078
1079                 wmove(view->win, prev_lineno, 0);
1080                 wclrtoeol(view->win);
1081                 view->ops->draw(view, prev_lineno);
1082         }
1083
1084         /* Check whether the view needs to be scrolled */
1085         if (view->lineno < view->offset ||
1086             view->lineno >= view->offset + view->height) {
1087                 if (steps < 0 && -steps > view->offset) {
1088                         steps = -view->offset;
1089
1090                 } else if (steps > 0) {
1091                         if (view->lineno == view->lines - 1 &&
1092                             view->lines > view->height) {
1093                                 steps = view->lines - view->offset - 1;
1094                                 if (steps >= view->height)
1095                                         steps -= view->height - 1;
1096                         }
1097                 }
1098
1099                 do_scroll_view(view, steps);
1100                 return;
1101         }
1102
1103         /* Draw the current line */
1104         view->ops->draw(view, view->lineno - view->offset);
1105
1106         redrawwin(view->win);
1107         wrefresh(view->win);
1108         report("");
1109 }
1110
1111
1112 /*
1113  * Incremental updating
1114  */
1115
1116 static bool
1117 begin_update(struct view *view)
1118 {
1119         char *id = view->id;
1120
1121         if (opt_cmd[0]) {
1122                 string_copy(view->cmd, opt_cmd);
1123                 opt_cmd[0] = 0;
1124                 /* When running random commands, the view ref could have become
1125                  * invalid so clear it. */
1126                 view->ref[0] = 0;
1127         } else {
1128                 char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1129
1130                 if (snprintf(view->cmd, sizeof(view->cmd), format,
1131                              id, id, id, id, id) >= sizeof(view->cmd))
1132                         return FALSE;
1133         }
1134
1135         /* Special case for the pager view. */
1136         if (opt_pipe) {
1137                 view->pipe = opt_pipe;
1138                 opt_pipe = NULL;
1139         } else {
1140                 view->pipe = popen(view->cmd, "r");
1141         }
1142
1143         if (!view->pipe)
1144                 return FALSE;
1145
1146         set_nonblocking_input(TRUE);
1147
1148         view->offset = 0;
1149         view->lines  = 0;
1150         view->lineno = 0;
1151         string_copy(view->vid, id);
1152
1153         if (view->line) {
1154                 int i;
1155
1156                 for (i = 0; i < view->lines; i++)
1157                         if (view->line[i])
1158                                 free(view->line[i]);
1159
1160                 free(view->line);
1161                 view->line = NULL;
1162         }
1163
1164         view->start_time = time(NULL);
1165
1166         return TRUE;
1167 }
1168
1169 static void
1170 end_update(struct view *view)
1171 {
1172         if (!view->pipe)
1173                 return;
1174         set_nonblocking_input(FALSE);
1175         if (view->pipe == stdin)
1176                 fclose(view->pipe);
1177         else
1178                 pclose(view->pipe);
1179         view->pipe = NULL;
1180 }
1181
1182 static bool
1183 update_view(struct view *view)
1184 {
1185         char buffer[BUFSIZ];
1186         char *line;
1187         void **tmp;
1188         /* The number of lines to read. If too low it will cause too much
1189          * redrawing (and possible flickering), if too high responsiveness
1190          * will suffer. */
1191         unsigned long lines = view->height;
1192         int redraw_from = -1;
1193
1194         if (!view->pipe)
1195                 return TRUE;
1196
1197         /* Only redraw if lines are visible. */
1198         if (view->offset + view->height >= view->lines)
1199                 redraw_from = view->lines - view->offset;
1200
1201         tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1202         if (!tmp)
1203                 goto alloc_error;
1204
1205         view->line = tmp;
1206
1207         while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1208                 int linelen = strlen(line);
1209
1210                 if (linelen)
1211                         line[linelen - 1] = 0;
1212
1213                 if (!view->ops->read(view, line))
1214                         goto alloc_error;
1215
1216                 if (lines-- == 1)
1217                         break;
1218         }
1219
1220         {
1221                 int digits;
1222
1223                 lines = view->lines;
1224                 for (digits = 0; lines; digits++)
1225                         lines /= 10;
1226
1227                 /* Keep the displayed view in sync with line number scaling. */
1228                 if (digits != view->digits) {
1229                         view->digits = digits;
1230                         redraw_from = 0;
1231                 }
1232         }
1233
1234         if (redraw_from >= 0) {
1235                 /* If this is an incremental update, redraw the previous line
1236                  * since for commits some members could have changed when
1237                  * loading the main view. */
1238                 if (redraw_from > 0)
1239                         redraw_from--;
1240
1241                 /* Incrementally draw avoids flickering. */
1242                 redraw_view_from(view, redraw_from);
1243         }
1244
1245         /* Update the title _after_ the redraw so that if the redraw picks up a
1246          * commit reference in view->ref it'll be available here. */
1247         update_view_title(view);
1248
1249         if (ferror(view->pipe)) {
1250                 report("Failed to read: %s", strerror(errno));
1251                 goto end;
1252
1253         } else if (feof(view->pipe)) {
1254                 time_t secs = time(NULL) - view->start_time;
1255
1256                 if (view == VIEW(REQ_VIEW_HELP)) {
1257                         report("%s", HELP);
1258                         goto end;
1259                 }
1260
1261                 report("Loaded %d lines in %ld second%s", view->lines, secs,
1262                        secs == 1 ? "" : "s");
1263                 goto end;
1264         }
1265
1266         return TRUE;
1267
1268 alloc_error:
1269         report("Allocation failure");
1270
1271 end:
1272         end_update(view);
1273         return FALSE;
1274 }
1275
1276 enum open_flags {
1277         OPEN_DEFAULT = 0,       /* Use default view switching. */
1278         OPEN_SPLIT = 1,         /* Split current view. */
1279         OPEN_BACKGROUNDED = 2,  /* Backgrounded. */
1280         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1281 };
1282
1283 static void
1284 open_view(struct view *prev, enum request request, enum open_flags flags)
1285 {
1286         bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1287         bool split = !!(flags & OPEN_SPLIT);
1288         bool reload = !!(flags & OPEN_RELOAD);
1289         struct view *view = VIEW(request);
1290         struct view *displayed;
1291         int nviews;
1292
1293         /* Cycle between displayed views and count the views. */
1294         foreach_view (displayed, nviews) {
1295                 if (prev != view &&
1296                     view == displayed &&
1297                     !strcmp(view->vid, prev->vid)) {
1298                         current_view = nviews;
1299                         /* Blur out the title of the previous view. */
1300                         update_view_title(prev);
1301                         report("");
1302                         return;
1303                 }
1304         }
1305
1306         if (view == prev && nviews == 1 && !reload) {
1307                 report("Already in %s view", view->name);
1308                 return;
1309         }
1310
1311         if ((reload || strcmp(view->vid, view->id)) &&
1312             !begin_update(view)) {
1313                 report("Failed to load %s view", view->name);
1314                 return;
1315         }
1316
1317         if (split) {
1318                 display[current_view + 1] = view;
1319                 if (!backgrounded)
1320                         current_view++;
1321         } else {
1322                 /* Maximize the current view. */
1323                 memset(display, 0, sizeof(display));
1324                 current_view = 0;
1325                 display[current_view] = view;
1326         }
1327
1328         resize_display();
1329
1330         if (split && prev->lineno - prev->offset >= prev->height) {
1331                 /* Take the title line into account. */
1332                 int lines = prev->lineno - prev->offset - prev->height + 1;
1333
1334                 /* Scroll the view that was split if the current line is
1335                  * outside the new limited view. */
1336                 do_scroll_view(prev, lines);
1337         }
1338
1339         if (prev && view != prev) {
1340                 /* "Blur" the previous view. */
1341                 if (!backgrounded)
1342                         update_view_title(prev);
1343
1344                 /* Continue loading split views in the background. */
1345                 if (!split)
1346                         end_update(prev);
1347         }
1348
1349         if (view->pipe) {
1350                 /* Clear the old view and let the incremental updating refill
1351                  * the screen. */
1352                 wclear(view->win);
1353                 report("Loading...");
1354         } else {
1355                 redraw_view(view);
1356                 report("");
1357         }
1358
1359         /* If the view is backgrounded the above calls to report()
1360          * won't redraw the view title. */
1361         if (backgrounded)
1362                 update_view_title(view);
1363 }
1364
1365
1366 /*
1367  * User request switch noodle
1368  */
1369
1370 static int
1371 view_driver(struct view *view, enum request request)
1372 {
1373         int i;
1374
1375         switch (request) {
1376         case REQ_MOVE_UP:
1377         case REQ_MOVE_DOWN:
1378         case REQ_MOVE_PAGE_UP:
1379         case REQ_MOVE_PAGE_DOWN:
1380         case REQ_MOVE_FIRST_LINE:
1381         case REQ_MOVE_LAST_LINE:
1382                 move_view(view, request);
1383                 break;
1384
1385         case REQ_SCROLL_LINE_DOWN:
1386         case REQ_SCROLL_LINE_UP:
1387         case REQ_SCROLL_PAGE_DOWN:
1388         case REQ_SCROLL_PAGE_UP:
1389                 scroll_view(view, request);
1390                 break;
1391
1392         case REQ_VIEW_MAIN:
1393         case REQ_VIEW_DIFF:
1394         case REQ_VIEW_LOG:
1395         case REQ_VIEW_HELP:
1396         case REQ_VIEW_PAGER:
1397                 open_view(view, request, OPEN_DEFAULT);
1398                 break;
1399
1400         case REQ_MOVE_UP_ENTER:
1401         case REQ_MOVE_DOWN_ENTER:
1402                 move_view(view, request);
1403                 /* Fall-through */
1404
1405         case REQ_ENTER:
1406                 if (!view->lines) {
1407                         report("Nothing to enter");
1408                         break;
1409                 }
1410                 return view->ops->enter(view);
1411
1412         case REQ_VIEW_NEXT:
1413         {
1414                 int nviews = display[1] ? 2 : 1;
1415                 int next_view = (current_view + 1) % nviews;
1416
1417                 if (next_view == current_view) {
1418                         report("Only one view is displayed");
1419                         break;
1420                 }
1421
1422                 current_view = next_view;
1423                 /* Blur out the title of the previous view. */
1424                 update_view_title(view);
1425                 report("");
1426                 break;
1427         }
1428         case REQ_TOGGLE_LINE_NUMBERS:
1429                 opt_line_number = !opt_line_number;
1430                 redraw_view(view);
1431                 update_view_title(view);
1432                 break;
1433
1434         case REQ_PROMPT:
1435                 /* Always reload^Wrerun commands from the prompt. */
1436                 open_view(view, opt_request, OPEN_RELOAD);
1437                 break;
1438
1439         case REQ_STOP_LOADING:
1440                 foreach_view (view, i) {
1441                         if (view->pipe)
1442                                 report("Stopped loaded the %s view", view->name),
1443                         end_update(view);
1444                 }
1445                 break;
1446
1447         case REQ_SHOW_VERSION:
1448                 report("Version: %s", VERSION);
1449                 return TRUE;
1450
1451         case REQ_SCREEN_RESIZE:
1452                 resize_display();
1453                 /* Fall-through */
1454         case REQ_SCREEN_REDRAW:
1455                 foreach_view (view, i) {
1456                         redraw_view(view);
1457                         update_view_title(view);
1458                 }
1459                 break;
1460
1461         case REQ_SCREEN_UPDATE:
1462                 doupdate();
1463                 return TRUE;
1464
1465         case REQ_QUIT:
1466                 return FALSE;
1467
1468         default:
1469                 /* An unknown key will show most commonly used commands. */
1470                 report("%s", HELP);
1471                 return TRUE;
1472         }
1473
1474         return TRUE;
1475 }
1476
1477
1478 /*
1479  * View backend handlers
1480  */
1481
1482 static bool
1483 pager_draw(struct view *view, unsigned int lineno)
1484 {
1485         enum line_type type;
1486         char *line;
1487         int linelen;
1488         int attr;
1489
1490         if (view->offset + lineno >= view->lines)
1491                 return FALSE;
1492
1493         line = view->line[view->offset + lineno];
1494         type = get_line_type(line);
1495
1496         wmove(view->win, lineno, 0);
1497
1498         if (view->offset + lineno == view->lineno) {
1499                 if (type == LINE_COMMIT) {
1500                         string_copy(view->ref, line + 7);
1501                         string_copy(ref_commit, view->ref);
1502                 }
1503
1504                 type = LINE_CURSOR;
1505                 wchgat(view->win, -1, 0, type, NULL);
1506         }
1507
1508         attr = get_line_attr(type);
1509         wattrset(view->win, attr);
1510
1511         linelen = strlen(line);
1512
1513         if (opt_line_number || opt_tab_size < TABSIZE) {
1514                 static char spaces[] = "                    ";
1515                 int col_offset = 0, col = 0;
1516
1517                 if (opt_line_number) {
1518                         unsigned long real_lineno = view->offset + lineno + 1;
1519
1520                         if (real_lineno == 1 ||
1521                             (real_lineno % opt_num_interval) == 0) {
1522                                 wprintw(view->win, "%.*d", view->digits, real_lineno);
1523
1524                         } else {
1525                                 waddnstr(view->win, spaces,
1526                                          MIN(view->digits, STRING_SIZE(spaces)));
1527                         }
1528                         waddstr(view->win, ": ");
1529                         col_offset = view->digits + 2;
1530                 }
1531
1532                 while (line && col_offset + col < view->width) {
1533                         int cols_max = view->width - col_offset - col;
1534                         char *text = line;
1535                         int cols;
1536
1537                         if (*line == '\t') {
1538                                 assert(sizeof(spaces) > TABSIZE);
1539                                 line++;
1540                                 text = spaces;
1541                                 cols = opt_tab_size - (col % opt_tab_size);
1542
1543                         } else {
1544                                 line = strchr(line, '\t');
1545                                 cols = line ? line - text : strlen(text);
1546                         }
1547
1548                         waddnstr(view->win, text, MIN(cols, cols_max));
1549                         col += cols;
1550                 }
1551
1552         } else {
1553                 int col = 0, pos = 0;
1554
1555                 for (; pos < linelen && col < view->width; pos++, col++)
1556                         if (line[pos] == '\t')
1557                                 col += TABSIZE - (col % TABSIZE) - 1;
1558
1559                 waddnstr(view->win, line, pos);
1560         }
1561
1562         return TRUE;
1563 }
1564
1565 static bool
1566 pager_read(struct view *view, char *line)
1567 {
1568         /* Compress empty lines in the help view. */
1569         if (view == VIEW(REQ_VIEW_HELP) &&
1570             !*line &&
1571             view->lines &&
1572             !*((char *) view->line[view->lines - 1]))
1573                 return TRUE;
1574
1575         view->line[view->lines] = strdup(line);
1576         if (!view->line[view->lines])
1577                 return FALSE;
1578
1579         view->lines++;
1580         return TRUE;
1581 }
1582
1583 static bool
1584 pager_enter(struct view *view)
1585 {
1586         char *line = view->line[view->lineno];
1587
1588         if (get_line_type(line) == LINE_COMMIT) {
1589                 if (view == VIEW(REQ_VIEW_LOG))
1590                         open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1591                 else
1592                         open_view(view, REQ_VIEW_DIFF, OPEN_DEFAULT);
1593         }
1594
1595         return TRUE;
1596 }
1597
1598 static struct view_ops pager_ops = {
1599         "line",
1600         pager_draw,
1601         pager_read,
1602         pager_enter,
1603 };
1604
1605
1606 static struct ref **get_refs(char *id);
1607
1608 static bool
1609 main_draw(struct view *view, unsigned int lineno)
1610 {
1611         char buf[DATE_COLS + 1];
1612         struct commit *commit;
1613         enum line_type type;
1614         int col = 0;
1615         size_t timelen;
1616
1617         if (view->offset + lineno >= view->lines)
1618                 return FALSE;
1619
1620         commit = view->line[view->offset + lineno];
1621         if (!*commit->author)
1622                 return FALSE;
1623
1624         wmove(view->win, lineno, col);
1625
1626         if (view->offset + lineno == view->lineno) {
1627                 string_copy(view->ref, commit->id);
1628                 string_copy(ref_commit, view->ref);
1629                 type = LINE_CURSOR;
1630                 wattrset(view->win, get_line_attr(type));
1631                 wchgat(view->win, -1, 0, type, NULL);
1632
1633         } else {
1634                 type = LINE_MAIN_COMMIT;
1635                 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1636         }
1637
1638         timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1639         waddnstr(view->win, buf, timelen);
1640         waddstr(view->win, " ");
1641
1642         col += DATE_COLS;
1643         wmove(view->win, lineno, col);
1644         if (type != LINE_CURSOR)
1645                 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1646
1647         if (strlen(commit->author) > 19) {
1648                 waddnstr(view->win, commit->author, 18);
1649                 if (type != LINE_CURSOR)
1650                         wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1651                 waddch(view->win, '~');
1652         } else {
1653                 waddstr(view->win, commit->author);
1654         }
1655
1656         col += 20;
1657         if (type != LINE_CURSOR)
1658                 wattrset(view->win, A_NORMAL);
1659
1660         mvwaddch(view->win, lineno, col, ACS_LTEE);
1661         wmove(view->win, lineno, col + 2);
1662         col += 2;
1663
1664         if (commit->refs) {
1665                 size_t i = 0;
1666
1667                 do {
1668                         if (type == LINE_CURSOR)
1669                                 ;
1670                         else if (commit->refs[i]->tag)
1671                                 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1672                         else
1673                                 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1674                         waddstr(view->win, "[");
1675                         waddstr(view->win, commit->refs[i]->name);
1676                         waddstr(view->win, "]");
1677                         if (type != LINE_CURSOR)
1678                                 wattrset(view->win, A_NORMAL);
1679                         waddstr(view->win, " ");
1680                         col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
1681                 } while (commit->refs[i++]->next);
1682         }
1683
1684         if (type != LINE_CURSOR)
1685                 wattrset(view->win, get_line_attr(type));
1686
1687         {
1688                 int titlelen = strlen(commit->title);
1689
1690                 if (col + titlelen > view->width)
1691                         titlelen = view->width - col;
1692
1693                 waddnstr(view->win, commit->title, titlelen);
1694         }
1695
1696         return TRUE;
1697 }
1698
1699 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1700 static bool
1701 main_read(struct view *view, char *line)
1702 {
1703         enum line_type type = get_line_type(line);
1704         struct commit *commit;
1705
1706         switch (type) {
1707         case LINE_COMMIT:
1708                 commit = calloc(1, sizeof(struct commit));
1709                 if (!commit)
1710                         return FALSE;
1711
1712                 line += STRING_SIZE("commit ");
1713
1714                 view->line[view->lines++] = commit;
1715                 string_copy(commit->id, line);
1716                 commit->refs = get_refs(commit->id);
1717                 break;
1718
1719         case LINE_AUTHOR:
1720         {
1721                 char *ident = line + STRING_SIZE("author ");
1722                 char *end = strchr(ident, '<');
1723
1724                 if (end) {
1725                         for (; end > ident && isspace(end[-1]); end--) ;
1726                         *end = 0;
1727                 }
1728
1729                 commit = view->line[view->lines - 1];
1730                 string_copy(commit->author, ident);
1731
1732                 /* Parse epoch and timezone */
1733                 if (end) {
1734                         char *secs = strchr(end + 1, '>');
1735                         char *zone;
1736                         time_t time;
1737
1738                         if (!secs || secs[1] != ' ')
1739                                 break;
1740
1741                         secs += 2;
1742                         time = (time_t) atol(secs);
1743                         zone = strchr(secs, ' ');
1744                         if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1745                                 long tz;
1746
1747                                 zone++;
1748                                 tz  = ('0' - zone[1]) * 60 * 60 * 10;
1749                                 tz += ('0' - zone[2]) * 60 * 60;
1750                                 tz += ('0' - zone[3]) * 60;
1751                                 tz += ('0' - zone[4]) * 60;
1752
1753                                 if (zone[0] == '-')
1754                                         tz = -tz;
1755
1756                                 time -= tz;
1757                         }
1758                         gmtime_r(&time, &commit->time);
1759                 }
1760                 break;
1761         }
1762         default:
1763                 /* We should only ever end up here if there has already been a
1764                  * commit line, however, be safe. */
1765                 if (view->lines == 0)
1766                         break;
1767
1768                 /* Fill in the commit title if it has not already been set. */
1769                 commit = view->line[view->lines - 1];
1770                 if (commit->title[0])
1771                         break;
1772
1773                 /* Require titles to start with a non-space character at the
1774                  * offset used by git log. */
1775                 /* FIXME: More gracefull handling of titles; append "..." to
1776                  * shortened titles, etc. */
1777                 if (strncmp(line, "    ", 4) ||
1778                     isspace(line[4]))
1779                         break;
1780
1781                 string_copy(commit->title, line + 4);
1782         }
1783
1784         return TRUE;
1785 }
1786
1787 static bool
1788 main_enter(struct view *view)
1789 {
1790         open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1791         return TRUE;
1792 }
1793
1794 static struct view_ops main_ops = {
1795         "commit",
1796         main_draw,
1797         main_read,
1798         main_enter,
1799 };
1800
1801
1802 /*
1803  * Status management
1804  */
1805
1806 /* Whether or not the curses interface has been initialized. */
1807 bool cursed = FALSE;
1808
1809 /* The status window is used for polling keystrokes. */
1810 static WINDOW *status_win;
1811
1812 /* Update status and title window. */
1813 static void
1814 report(const char *msg, ...)
1815 {
1816         static bool empty = TRUE;
1817         struct view *view = display[current_view];
1818
1819         if (!empty || *msg) {
1820                 va_list args;
1821
1822                 va_start(args, msg);
1823
1824                 werase(status_win);
1825                 wmove(status_win, 0, 0);
1826                 if (*msg) {
1827                         vwprintw(status_win, msg, args);
1828                         empty = FALSE;
1829                 } else {
1830                         empty = TRUE;
1831                 }
1832                 wrefresh(status_win);
1833
1834                 va_end(args);
1835         }
1836
1837         update_view_title(view);
1838
1839         /* Move the cursor to the right-most column of the cursor line.
1840          *
1841          * XXX: This could turn out to be a bit expensive, but it ensures that
1842          * the cursor does not jump around. */
1843         if (view->lines) {
1844                 wmove(view->win, view->lineno - view->offset, view->width - 1);
1845                 wrefresh(view->win);
1846         }
1847 }
1848
1849 /* Controls when nodelay should be in effect when polling user input. */
1850 static void
1851 set_nonblocking_input(bool loading)
1852 {
1853         static unsigned int loading_views;
1854
1855         if ((loading == FALSE && loading_views-- == 1) ||
1856             (loading == TRUE  && loading_views++ == 0))
1857                 nodelay(status_win, loading);
1858 }
1859
1860 static void
1861 init_display(void)
1862 {
1863         int x, y;
1864
1865         /* Initialize the curses library */
1866         if (isatty(STDIN_FILENO)) {
1867                 cursed = !!initscr();
1868         } else {
1869                 /* Leave stdin and stdout alone when acting as a pager. */
1870                 FILE *io = fopen("/dev/tty", "r+");
1871
1872                 cursed = !!newterm(NULL, io, io);
1873         }
1874
1875         if (!cursed)
1876                 die("Failed to initialize curses");
1877
1878         nonl();         /* Tell curses not to do NL->CR/NL on output */
1879         cbreak();       /* Take input chars one at a time, no wait for \n */
1880         noecho();       /* Don't echo input */
1881         leaveok(stdscr, TRUE);
1882
1883         if (has_colors())
1884                 init_colors();
1885
1886         getmaxyx(stdscr, y, x);
1887         status_win = newwin(1, 0, y - 1, 0);
1888         if (!status_win)
1889                 die("Failed to create status window");
1890
1891         /* Enable keyboard mapping */
1892         keypad(status_win, TRUE);
1893         wbkgdset(status_win, get_line_attr(LINE_STATUS));
1894 }
1895
1896
1897 /*
1898  * Repository references
1899  */
1900
1901 static struct ref *refs;
1902 size_t refs_size;
1903
1904 static struct ref **
1905 get_refs(char *id)
1906 {
1907         struct ref **id_refs = NULL;
1908         size_t id_refs_size = 0;
1909         size_t i;
1910
1911         for (i = 0; i < refs_size; i++) {
1912                 struct ref **tmp;
1913
1914                 if (strcmp(id, refs[i].id))
1915                         continue;
1916
1917                 tmp = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
1918                 if (!tmp) {
1919                         if (id_refs)
1920                                 free(id_refs);
1921                         return NULL;
1922                 }
1923
1924                 id_refs = tmp;
1925                 if (id_refs_size > 0)
1926                         id_refs[id_refs_size - 1]->next = 1;
1927                 id_refs[id_refs_size] = &refs[i];
1928
1929                 /* XXX: The properties of the commit chains ensures that we can
1930                  * safely modify the shared ref. The repo references will
1931                  * always be similar for the same id. */
1932                 id_refs[id_refs_size]->next = 0;
1933                 id_refs_size++;
1934         }
1935
1936         return id_refs;
1937 }
1938
1939 static int
1940 load_refs(void)
1941 {
1942         char *cmd_env = getenv("TIG_LS_REMOTE");
1943         char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
1944         FILE *pipe = popen(cmd, "r");
1945         char buffer[BUFSIZ];
1946         char *line;
1947
1948         if (!pipe)
1949                 return ERR;
1950
1951         while ((line = fgets(buffer, sizeof(buffer), pipe))) {
1952                 char *name = strchr(line, '\t');
1953                 struct ref *ref;
1954                 int namelen;
1955                 bool tag = FALSE;
1956                 bool tag_commit = FALSE;
1957
1958                 if (!name)
1959                         continue;
1960
1961                 *name++ = 0;
1962                 namelen = strlen(name) - 1;
1963
1964                 /* Commits referenced by tags has "^{}" appended. */
1965                 if (name[namelen - 1] == '}') {
1966                         while (namelen > 0 && name[namelen] != '^')
1967                                 namelen--;
1968                         if (namelen > 0)
1969                                 tag_commit = TRUE;
1970                 }
1971                 name[namelen] = 0;
1972
1973                 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
1974                         if (!tag_commit)
1975                                 continue;
1976                         name += STRING_SIZE("refs/tags/");
1977                         tag = TRUE;
1978
1979                 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
1980                         name += STRING_SIZE("refs/heads/");
1981
1982                 } else if (!strcmp(name, "HEAD")) {
1983                         continue;
1984                 }
1985
1986                 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
1987                 if (!refs)
1988                         return ERR;
1989
1990                 ref = &refs[refs_size++];
1991                 ref->tag = tag;
1992                 ref->name = strdup(name);
1993                 if (!ref->name)
1994                         return ERR;
1995
1996                 string_copy(ref->id, line);
1997         }
1998
1999         if (ferror(pipe))
2000                 return ERR;
2001
2002         pclose(pipe);
2003
2004         return OK;
2005 }
2006
2007 /*
2008  * Main
2009  */
2010
2011 static void
2012 quit(int sig)
2013 {
2014         /* XXX: Restore tty modes and let the OS cleanup the rest! */
2015         if (cursed)
2016                 endwin();
2017         exit(0);
2018 }
2019
2020 static void die(const char *err, ...)
2021 {
2022         va_list args;
2023
2024         endwin();
2025
2026         va_start(args, err);
2027         fputs("tig: ", stderr);
2028         vfprintf(stderr, err, args);
2029         fputs("\n", stderr);
2030         va_end(args);
2031
2032         exit(1);
2033 }
2034
2035 int
2036 main(int argc, char *argv[])
2037 {
2038         struct view *view;
2039         enum request request;
2040         size_t i;
2041
2042         signal(SIGINT, quit);
2043
2044         if (!parse_options(argc, argv))
2045                 return 0;
2046
2047         if (load_refs() == ERR)
2048                 die("Failed to load refs.");
2049
2050         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2051                 view->cmd_env = getenv(view->cmd_env);
2052
2053         request = opt_request;
2054
2055         init_display();
2056
2057         while (view_driver(display[current_view], request)) {
2058                 int key;
2059                 int i;
2060
2061                 foreach_view (view, i)
2062                         update_view(view);
2063
2064                 /* Refresh, accept single keystroke of input */
2065                 key = wgetch(status_win);
2066                 request = get_request(key);
2067
2068                 /* Some low-level request handling. This keeps access to
2069                  * status_win restricted. */
2070                 switch (request) {
2071                 case REQ_PROMPT:
2072                         report(":");
2073                         /* Temporarily switch to line-oriented and echoed
2074                          * input. */
2075                         nocbreak();
2076                         echo();
2077
2078                         if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
2079                                 memcpy(opt_cmd, "git ", 4);
2080                                 opt_request = REQ_VIEW_PAGER;
2081                         } else {
2082                                 request = ERR;
2083                         }
2084
2085                         noecho();
2086                         cbreak();
2087                         break;
2088
2089                 case REQ_SCREEN_RESIZE:
2090                 {
2091                         int height, width;
2092
2093                         getmaxyx(stdscr, height, width);
2094
2095                         /* Resize the status view and let the view driver take
2096                          * care of resizing the displayed views. */
2097                         wresize(status_win, 1, width);
2098                         mvwin(status_win, height - 1, 0);
2099                         wrefresh(status_win);
2100                         break;
2101                 }
2102                 default:
2103                         break;
2104                 }
2105         }
2106
2107         quit(0);
2108
2109         return 0;
2110 }
2111
2112 /**
2113  * BUGS
2114  * ----
2115  * Known bugs and problems:
2116  *
2117  * - If the screen width is very small the main view can draw
2118  *   outside the current view causing bad wrapping.
2119  *
2120  * TODO
2121  * ----
2122  * Features that should be explored.
2123  *
2124  * - Searching.
2125  *
2126  * - Locale support.
2127  *
2128  * COPYRIGHT
2129  * ---------
2130  * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
2131  *
2132  * This program is free software; you can redistribute it and/or modify
2133  * it under the terms of the GNU General Public License as published by
2134  * the Free Software Foundation; either version 2 of the License, or
2135  * (at your option) any later version.
2136  *
2137  * SEE ALSO
2138  * --------
2139  * [verse]
2140  * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
2141  * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
2142  * gitk(1): git repository browser written using tcl/tk,
2143  * gitview(1): git repository browser written using python/gtk.
2144  **/