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