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