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