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