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