1 /* Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
2 * See license info at the bottom. */
9 * tig - text-mode interface for git
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]
23 * Browse changes in a git repository. Additionally, tig(1) can also act
24 * as a pager for output of various git commands.
28 * To speed up interaction with git, you can limit the amount of commits
29 * to show both for the log and main view. Either limit by date using
30 * e.g. `--since=1.month` or limit by the number of commits using `-n400`.
32 * Alternatively, commits can be limited to a specific range, such as
33 * "all commits between tag-1.0 and tag-2.0". For example:
35 * $ tig log tag-1.0..tag-2.0
37 * Git interprets this as "all commits reachable from commit-2
38 * but not from commit-1". The above can also be written:
40 * $ tig log tag-2.0 ^tag-1.0
42 * You can think of '^' as a negator. Using this alternate syntax,
43 * it is possible to furthur prune commits by specifying multiple
46 * This way of commit limiting makes it trivial to only browse the commit
47 * which hasn't been pushed to a remote branch. Assuming origin is your
48 * upstream remote branch, using:
50 * $ tig log origin..HEAD
52 * Optionally, with "HEAD" left out, will list what will be pushed to
55 * See the section on environment variables, on how to further tune the
56 * interaction with git.
60 #define VERSION "tig-0.1"
80 static void die(const char *err, ...);
81 static void report(const char *msg, ...);
82 static void set_nonblocking_input(bool loading);
84 #define ABS(x) ((x) >= 0 ? (x) : -(x))
85 #define MIN(x, y) ((x) < (y) ? (x) : (y))
87 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
88 #define STRING_SIZE(x) (sizeof(x) - 1)
90 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
91 #define SIZEOF_CMD 1024 /* Size of command buffer. */
93 /* This color name can be used to refer to the default term colors. */
94 #define COLOR_DEFAULT (-1)
96 /* The format and size of the date column in the main view. */
97 #define DATE_FORMAT "%Y-%m-%d %H:%M"
98 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
100 /* The default interval between line numbers. */
101 #define NUMBER_INTERVAL 1
105 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
107 /* Some ascii-shorthands fitted into the ncurses namespace. */
109 #define KEY_RETURN '\r'
113 /* User action requests. */
115 /* Offset all requests to avoid conflicts with ncurses getch values. */
116 REQ_OFFSET = KEY_MAX + 1,
118 /* XXX: Keep the view request first and in sync with views[]. */
133 REQ_TOGGLE_LINE_NUMBERS,
146 REQ_SCROLL_LINE_DOWN,
148 REQ_SCROLL_PAGE_DOWN,
159 char id[41]; /* SHA1 ID. */
160 char title[75]; /* The first line of the commit message. */
161 char author[75]; /* The author of the commit. */
162 struct tm time; /* Date from the author ident. */
163 struct ref **refs; /* Repository references; tags & branch heads. */
172 string_ncopy(char *dst, char *src, int dstlen)
174 strncpy(dst, src, dstlen - 1);
179 /* Shorthand for safely copying into a fixed buffer. */
180 #define string_copy(dst, src) \
181 string_ncopy(dst, src, sizeof(dst))
186 * NOTE: The following is a slightly modified copy of the git project's shell
187 * quoting routines found in the quote.c file.
189 * Help to copy the thing properly quoted for the shell safety. any single
190 * quote is replaced with '\'', any exclamation point is replaced with '\!',
191 * and the whole thing is enclosed in a
194 * original sq_quote result
195 * name ==> name ==> 'name'
196 * a b ==> a b ==> 'a b'
197 * a'b ==> a'\''b ==> 'a'\''b'
198 * a!b ==> a'\!'b ==> 'a'\!'b'
202 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
206 #define BUFPUT(x) ( (bufsize < SIZEOF_CMD) && (buf[bufsize++] = (x)) )
209 while ((c = *src++)) {
210 if (c == '\'' || c == '!') {
230 /* Option and state variables. */
231 static bool opt_line_number = FALSE;
232 static int opt_num_interval = NUMBER_INTERVAL;
233 static int opt_tab_size = TABSIZE;
234 static enum request opt_request = REQ_VIEW_MAIN;
235 static char opt_cmd[SIZEOF_CMD] = "";
236 static FILE *opt_pipe = NULL;
238 /* Returns the index of log or diff command or -1 to exit. */
240 parse_options(int argc, char *argv[])
244 for (i = 1; i < argc; i++) {
249 * Start up in log view using the internal log command.
251 if (!strcmp(opt, "-l")) {
252 opt_request = REQ_VIEW_LOG;
258 * Start up in diff view using the internal diff command.
260 if (!strcmp(opt, "-d")) {
261 opt_request = REQ_VIEW_DIFF;
266 * -n[INTERVAL], --line-number[=INTERVAL]::
267 * Prefix line numbers in log and diff view.
268 * Optionally, with interval different than each line.
270 if (!strncmp(opt, "-n", 2) ||
271 !strncmp(opt, "--line-number", 13)) {
277 } else if (opt[STRING_SIZE("--line-number")] == '=') {
278 num = opt + STRING_SIZE("--line-number=");
282 opt_num_interval = atoi(num);
284 opt_line_number = TRUE;
289 * -t[NSPACES], --tab-size[=NSPACES]::
290 * Set the number of spaces tabs should be expanded to.
292 if (!strncmp(opt, "-t", 2) ||
293 !strncmp(opt, "--tab-size", 10)) {
299 } else if (opt[STRING_SIZE("--tab-size")] == '=') {
300 num = opt + STRING_SIZE("--tab-size=");
304 opt_tab_size = MIN(atoi(num), TABSIZE);
310 * Show version and exit.
312 if (!strcmp(opt, "-v") ||
313 !strcmp(opt, "--version")) {
314 printf("tig version %s\n", VERSION);
320 * End of tig(1) options. Useful when specifying commands
321 * for the main view. Example:
323 * $ tig -- --since=1.month
325 if (!strcmp(opt, "--")) {
332 * Open log view using the given git log options.
335 * Open diff view using the given git diff options.
338 * Open diff view using the given git show options.
340 if (!strcmp(opt, "log") ||
341 !strcmp(opt, "diff") ||
342 !strcmp(opt, "show")) {
343 opt_request = opt[0] == 'l'
344 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
350 * $ tig tag-1.0..HEAD
353 if (opt[0] && opt[0] != '-')
356 die("unknown command '%s'", opt);
359 if (!isatty(STDIN_FILENO)) {
363 * If stdin is a pipe, any log or diff options will be ignored and the
364 * pager view will be opened loading data from stdin. The pager mode
365 * can be used for colorizing output from various git commands.
367 * Example on how to colorize the output of git-show(1):
371 opt_request = REQ_VIEW_PAGER;
374 } else if (i < argc) {
378 * Git command options
379 * ~~~~~~~~~~~~~~~~~~~
380 * All git command options specified on the command line will
381 * be passed to the given command and all will be shell quoted
384 * NOTE: It is possible to specify options even for the main
385 * view. If doing this you should not touch the `--pretty`
388 * Example on how to open the log view and show both author and
389 * committer information:
391 * $ tig log --pretty=fuller
394 if (opt_request == REQ_VIEW_MAIN)
395 /* XXX: This is vulnerable to the user overriding
396 * options required for the main view parser. */
397 string_copy(opt_cmd, "git log --stat --pretty=raw");
399 string_copy(opt_cmd, "git");
400 buf_size = strlen(opt_cmd);
402 while (buf_size < sizeof(opt_cmd) && i < argc) {
403 opt_cmd[buf_size++] = ' ';
404 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
407 if (buf_size >= sizeof(opt_cmd))
408 die("command too long");
410 opt_cmd[buf_size] = 0;
421 * Below the default key bindings are shown.
424 #define HELP "(d)iff, (l)og, (m)ain, (q)uit, (v)ersion, (h)elp"
431 struct keymap keymap[] = {
436 * Switch to diff view.
438 * Switch to log view.
440 * Switch to main view.
442 * Switch to pager view.
446 * If on a commit line show the commit diff. Addiionally, if in
447 * main or log view this will split the view. To open the commit
448 * diff in full size view either use 'd' or press Return twice.
451 * Switch to next view.
453 { 'm', REQ_VIEW_MAIN },
454 { 'd', REQ_VIEW_DIFF },
455 { 'l', REQ_VIEW_LOG },
456 { 'p', REQ_VIEW_PAGER },
457 { 'h', REQ_VIEW_HELP },
459 { KEY_TAB, REQ_VIEW_NEXT },
460 { KEY_RETURN, REQ_ENTER },
466 * Move curser one line up.
468 * Move cursor one line down.
471 * Move curser one line up and enter. When used in the main view
472 * this will always show the diff of the current commit in the
476 * Move cursor one line down and enter.
478 * Move curser one page up.
480 * Move cursor one page down.
482 * Jump to first line.
486 { KEY_UP, REQ_MOVE_UP },
487 { KEY_DOWN, REQ_MOVE_DOWN },
488 { 'k', REQ_MOVE_UP_ENTER },
489 { 'j', REQ_MOVE_DOWN_ENTER },
490 { KEY_HOME, REQ_MOVE_FIRST_LINE },
491 { KEY_END, REQ_MOVE_LAST_LINE },
492 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
493 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
499 * Scroll view one line up.
501 * Scroll view one line down.
503 * Scroll view one page up.
505 * Scroll view one page down.
507 { KEY_IC, REQ_SCROLL_LINE_UP },
508 { KEY_DC, REQ_SCROLL_LINE_DOWN },
509 { 'w', REQ_SCROLL_PAGE_UP },
510 { 's', REQ_SCROLL_PAGE_DOWN },
520 * Stop all background loading. This can be useful if you ran
521 * tig(1) in a repository with a long history without limiting
526 * Toggle line numbers on/off.
528 * Open prompt. This allows you to specify what git command
535 { 'z', REQ_STOP_LOADING },
536 { 'v', REQ_SHOW_VERSION },
537 { 'r', REQ_SCREEN_REDRAW },
538 { 'n', REQ_TOGGLE_LINE_NUMBERS },
541 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
542 { ERR, REQ_SCREEN_UPDATE },
544 /* Use the ncurses SIGWINCH handler. */
545 { KEY_RESIZE, REQ_SCREEN_RESIZE },
553 for (i = 0; i < ARRAY_SIZE(keymap); i++)
554 if (keymap[i].alias == key)
555 return keymap[i].request;
557 return (enum request) key;
562 * Line-oriented content detection.
566 /* Line type String to match Foreground Background Attributes
567 * --------- --------------- ---------- ---------- ---------- */ \
569 LINE(DIFF, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
570 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
571 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
572 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
573 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
574 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
575 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
576 LINE(DIFF_COPY, "copy ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
577 LINE(DIFF_RENAME, "rename ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
578 LINE(DIFF_SIM, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
579 LINE(DIFF_DISSIM, "dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
580 /* Pretty print commit header */ \
581 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
582 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
583 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
584 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
585 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
586 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
587 /* Raw commit header */ \
588 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
589 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
590 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
591 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
592 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
594 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
595 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
597 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
598 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
599 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
600 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
601 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
602 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
603 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
604 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
605 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
606 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
607 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD),
610 #define LINE(type, line, fg, bg, attr) \
617 char *line; /* The start of line to match. */
618 int linelen; /* Size of string to match. */
619 int fg, bg, attr; /* Color and text attributes for the lines. */
622 static struct line_info line_info[] = {
623 #define LINE(type, line, fg, bg, attr) \
624 { (line), STRING_SIZE(line), (fg), (bg), (attr) }
629 static enum line_type
630 get_line_type(char *line)
632 int linelen = strlen(line);
635 for (type = 0; type < ARRAY_SIZE(line_info); type++)
636 /* Case insensitive search matches Signed-off-by lines better. */
637 if (linelen >= line_info[type].linelen &&
638 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
645 get_line_attr(enum line_type type)
647 assert(type < ARRAY_SIZE(line_info));
648 return COLOR_PAIR(type) | line_info[type].attr;
654 int default_bg = COLOR_BLACK;
655 int default_fg = COLOR_WHITE;
660 if (use_default_colors() != ERR) {
665 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
666 struct line_info *info = &line_info[type];
667 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
668 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
670 init_pair(type, fg, bg);
676 * ENVIRONMENT VARIABLES
677 * ---------------------
678 * Several options related to the interface with git can be configured
679 * via environment options.
681 * Repository references
682 * ~~~~~~~~~~~~~~~~~~~~~
683 * Commits that are referenced by tags and branch heads will be marked
684 * by the reference name surrounded by '[' and ']':
686 * 2006-04-18 23:12 Jonas Fonseca | [tig-0.2] tig version 0.2
688 * If you want to filter out certain directories under `.git/refs/`, say
689 * `tmp` you can do it by setting the following variable:
691 * $ TIG_LS_REMOTE="git ls-remote . | sed /\/tmp\//d" tig
693 * Or set the variable permanently in your environment.
696 * Set command for retrieving all repository references. The command
697 * should output data in the same format as git-ls-remote(1).
700 #define TIG_LS_REMOTE \
706 * It is possible to alter which commands are used for the different views.
707 * If for example you prefer commits in the main view to be sorted by date
708 * and only show 500 commits, use:
710 * $ TIG_MAIN_CMD="git log --date-order -n500 --pretty=raw %s" tig
712 * Or set the variable permanently in your environment.
714 * Notice, how `%s` is used to specify the commit reference. There can
715 * be a maximum of 5 `%s` ref specifications.
718 * The command used for the diff view. By default, git show is used
722 * The command used for the log view. If you prefer to have both
723 * author and committer shown in the log view be sure to pass
724 * `--pretty=fuller` to git log.
727 * The command used for the main view. Note, you must always specify
728 * the option: `--pretty=raw` since the main view parser expects to
732 #define TIG_DIFF_CMD \
733 "git show --patch-with-stat --find-copies-harder -B -C %s"
735 #define TIG_LOG_CMD \
736 "git log --cc --stat -n100 %s"
738 #define TIG_MAIN_CMD \
739 "git log --topo-order --stat --pretty=raw %s"
741 /* We silently ignore that the following are also exported. */
743 #define TIG_HELP_CMD \
744 "man tig 2> /dev/null"
746 #define TIG_PAGER_CMD \
755 const char *name; /* View name */
756 char *cmd_fmt; /* Default command line format */
757 char *cmd_env; /* Command line set via environment */
758 char *id; /* Points to either of ref_{head,commit} */
759 size_t objsize; /* Size of objects in the line index */
762 /* What type of content being displayed. Used in the
765 /* Draw one line; @lineno must be < view->height. */
766 bool (*draw)(struct view *view, unsigned int lineno);
767 /* Read one line; updates view->line. */
768 bool (*read)(struct view *view, char *line);
769 /* Depending on view, change display based on current line. */
770 bool (*enter)(struct view *view);
773 char cmd[SIZEOF_CMD]; /* Command buffer */
774 char ref[SIZEOF_REF]; /* Hovered commit reference */
775 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
777 int height, width; /* The width and height of the main window */
778 WINDOW *win; /* The main window */
779 WINDOW *title; /* The title window living below the main window */
782 unsigned long offset; /* Offset of the window top */
783 unsigned long lineno; /* Current line number */
786 unsigned long lines; /* Total number of lines */
787 void **line; /* Line index; each line contains user data */
788 unsigned int digits; /* Number of digits in the lines member. */
795 static struct view_ops pager_ops;
796 static struct view_ops main_ops;
798 char ref_head[SIZEOF_REF] = "HEAD";
799 char ref_commit[SIZEOF_REF] = "HEAD";
801 #define VIEW_STR(name, cmd, env, ref, objsize, ops) \
802 { name, cmd, #env, ref, objsize, ops }
804 #define VIEW_(id, name, ops, ref, objsize) \
805 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, objsize, ops)
807 static struct view views[] = {
808 VIEW_(MAIN, "main", &main_ops, ref_head, sizeof(struct commit)),
809 VIEW_(DIFF, "diff", &pager_ops, ref_commit, sizeof(char)),
810 VIEW_(LOG, "log", &pager_ops, ref_head, sizeof(char)),
811 VIEW_(HELP, "help", &pager_ops, ref_head, sizeof(char)),
812 VIEW_(PAGER, "pager", &pager_ops, "static", sizeof(char)),
815 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
817 /* The display array of active views and the index of the current view. */
818 static struct view *display[2];
819 static unsigned int current_view;
821 #define foreach_view(view, i) \
822 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
826 redraw_view_from(struct view *view, int lineno)
828 assert(0 <= lineno && lineno < view->height);
830 for (; lineno < view->height; lineno++) {
831 if (!view->ops->draw(view, lineno))
835 redrawwin(view->win);
840 redraw_view(struct view *view)
843 redraw_view_from(view, 0);
850 struct view *base = display[0];
851 struct view *view = display[1] ? display[1] : display[0];
853 /* Setup window dimensions */
855 getmaxyx(stdscr, base->height, base->width);
857 /* Make room for the status window. */
861 /* Horizontal split. */
862 view->width = base->width;
863 view->height = SCALE_SPLIT_VIEW(base->height);
864 base->height -= view->height;
866 /* Make room for the title bar. */
870 /* Make room for the title bar. */
875 foreach_view (view, i) {
876 /* Keep the size of the all view windows one lager than is
877 * required. This makes current line management easier when the
878 * cursor will go outside the window. */
880 view->win = newwin(view->height + 1, 0, offset, 0);
882 die("Failed to create %s view", view->name);
884 scrollok(view->win, TRUE);
886 view->title = newwin(1, 0, offset + view->height, 0);
888 die("Failed to create title window");
891 wresize(view->win, view->height + 1, view->width);
892 mvwin(view->win, offset, 0);
893 mvwin(view->title, offset + view->height, 0);
897 offset += view->height + 1;
902 update_view_title(struct view *view)
904 if (view == display[current_view])
905 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
907 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
910 wmove(view->title, 0, 0);
912 /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
915 wprintw(view->title, "[%s] ref: %s", view->name, view->ref);
917 wprintw(view->title, "[%s]", view->name);
920 wprintw(view->title, " - %s %d of %d (%d%%)",
924 (view->lineno + 1) * 100 / view->lines);
927 wrefresh(view->title);
934 /* Scrolling backend */
936 do_scroll_view(struct view *view, int lines)
938 /* The rendering expects the new offset. */
939 view->offset += lines;
941 assert(0 <= view->offset && view->offset < view->lines);
944 /* Redraw the whole screen if scrolling is pointless. */
945 if (view->height < ABS(lines)) {
949 int line = lines > 0 ? view->height - lines : 0;
950 int end = line + ABS(lines);
952 wscrl(view->win, lines);
954 for (; line < end; line++) {
955 if (!view->ops->draw(view, line))
960 /* Move current line into the view. */
961 if (view->lineno < view->offset) {
962 view->lineno = view->offset;
963 view->ops->draw(view, 0);
965 } else if (view->lineno >= view->offset + view->height) {
966 if (view->lineno == view->offset + view->height) {
967 /* Clear the hidden line so it doesn't show if the view
969 wmove(view->win, view->height, 0);
970 wclrtoeol(view->win);
972 view->lineno = view->offset + view->height - 1;
973 view->ops->draw(view, view->lineno - view->offset);
976 assert(view->offset <= view->lineno && view->lineno < view->lines);
978 redrawwin(view->win);
983 /* Scroll frontend */
985 scroll_view(struct view *view, enum request request)
990 case REQ_SCROLL_PAGE_DOWN:
991 lines = view->height;
992 case REQ_SCROLL_LINE_DOWN:
993 if (view->offset + lines > view->lines)
994 lines = view->lines - view->offset;
996 if (lines == 0 || view->offset + view->height >= view->lines) {
997 report("Cannot scroll beyond the last line");
1002 case REQ_SCROLL_PAGE_UP:
1003 lines = view->height;
1004 case REQ_SCROLL_LINE_UP:
1005 if (lines > view->offset)
1006 lines = view->offset;
1009 report("Cannot scroll beyond the first line");
1017 die("request %d not handled in switch", request);
1020 do_scroll_view(view, lines);
1025 move_view(struct view *view, enum request request)
1030 case REQ_MOVE_FIRST_LINE:
1031 steps = -view->lineno;
1034 case REQ_MOVE_LAST_LINE:
1035 steps = view->lines - view->lineno - 1;
1038 case REQ_MOVE_PAGE_UP:
1039 steps = view->height > view->lineno
1040 ? -view->lineno : -view->height;
1043 case REQ_MOVE_PAGE_DOWN:
1044 steps = view->lineno + view->height >= view->lines
1045 ? view->lines - view->lineno - 1 : view->height;
1049 case REQ_MOVE_UP_ENTER:
1054 case REQ_MOVE_DOWN_ENTER:
1059 die("request %d not handled in switch", request);
1062 if (steps <= 0 && view->lineno == 0) {
1063 report("Cannot move beyond the first line");
1066 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
1067 report("Cannot move beyond the last line");
1071 /* Move the current line */
1072 view->lineno += steps;
1073 assert(0 <= view->lineno && view->lineno < view->lines);
1075 /* Repaint the old "current" line if we be scrolling */
1076 if (ABS(steps) < view->height) {
1077 int prev_lineno = view->lineno - steps - view->offset;
1079 wmove(view->win, prev_lineno, 0);
1080 wclrtoeol(view->win);
1081 view->ops->draw(view, prev_lineno);
1084 /* Check whether the view needs to be scrolled */
1085 if (view->lineno < view->offset ||
1086 view->lineno >= view->offset + view->height) {
1087 if (steps < 0 && -steps > view->offset) {
1088 steps = -view->offset;
1090 } else if (steps > 0) {
1091 if (view->lineno == view->lines - 1 &&
1092 view->lines > view->height) {
1093 steps = view->lines - view->offset - 1;
1094 if (steps >= view->height)
1095 steps -= view->height - 1;
1099 do_scroll_view(view, steps);
1103 /* Draw the current line */
1104 view->ops->draw(view, view->lineno - view->offset);
1106 redrawwin(view->win);
1107 wrefresh(view->win);
1113 * Incremental updating
1117 begin_update(struct view *view)
1119 char *id = view->id;
1122 string_copy(view->cmd, opt_cmd);
1124 /* When running random commands, the view ref could have become
1125 * invalid so clear it. */
1128 char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1130 if (snprintf(view->cmd, sizeof(view->cmd), format,
1131 id, id, id, id, id) >= sizeof(view->cmd))
1135 /* Special case for the pager view. */
1137 view->pipe = opt_pipe;
1140 view->pipe = popen(view->cmd, "r");
1146 set_nonblocking_input(TRUE);
1151 string_copy(view->vid, id);
1156 for (i = 0; i < view->lines; i++)
1158 free(view->line[i]);
1164 view->start_time = time(NULL);
1170 end_update(struct view *view)
1174 set_nonblocking_input(FALSE);
1175 if (view->pipe == stdin)
1183 update_view(struct view *view)
1185 char buffer[BUFSIZ];
1188 /* The number of lines to read. If too low it will cause too much
1189 * redrawing (and possible flickering), if too high responsiveness
1191 unsigned long lines = view->height;
1192 int redraw_from = -1;
1197 /* Only redraw if lines are visible. */
1198 if (view->offset + view->height >= view->lines)
1199 redraw_from = view->lines - view->offset;
1201 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1207 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1208 int linelen = strlen(line);
1211 line[linelen - 1] = 0;
1213 if (!view->ops->read(view, line))
1223 lines = view->lines;
1224 for (digits = 0; lines; digits++)
1227 /* Keep the displayed view in sync with line number scaling. */
1228 if (digits != view->digits) {
1229 view->digits = digits;
1234 if (redraw_from >= 0) {
1235 /* If this is an incremental update, redraw the previous line
1236 * since for commits some members could have changed when
1237 * loading the main view. */
1238 if (redraw_from > 0)
1241 /* Incrementally draw avoids flickering. */
1242 redraw_view_from(view, redraw_from);
1245 /* Update the title _after_ the redraw so that if the redraw picks up a
1246 * commit reference in view->ref it'll be available here. */
1247 update_view_title(view);
1249 if (ferror(view->pipe)) {
1250 report("Failed to read: %s", strerror(errno));
1253 } else if (feof(view->pipe)) {
1254 time_t secs = time(NULL) - view->start_time;
1256 if (view == VIEW(REQ_VIEW_HELP)) {
1261 report("Loaded %d lines in %ld second%s", view->lines, secs,
1262 secs == 1 ? "" : "s");
1269 report("Allocation failure");
1277 OPEN_DEFAULT = 0, /* Use default view switching. */
1278 OPEN_SPLIT = 1, /* Split current view. */
1279 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1280 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1284 open_view(struct view *prev, enum request request, enum open_flags flags)
1286 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1287 bool split = !!(flags & OPEN_SPLIT);
1288 bool reload = !!(flags & OPEN_RELOAD);
1289 struct view *view = VIEW(request);
1290 struct view *displayed;
1293 /* Cycle between displayed views and count the views. */
1294 foreach_view (displayed, nviews) {
1296 view == displayed &&
1297 !strcmp(view->vid, prev->vid)) {
1298 current_view = nviews;
1299 /* Blur out the title of the previous view. */
1300 update_view_title(prev);
1306 if (view == prev && nviews == 1 && !reload) {
1307 report("Already in %s view", view->name);
1311 if ((reload || strcmp(view->vid, view->id)) &&
1312 !begin_update(view)) {
1313 report("Failed to load %s view", view->name);
1318 display[current_view + 1] = view;
1322 /* Maximize the current view. */
1323 memset(display, 0, sizeof(display));
1325 display[current_view] = view;
1330 if (split && prev->lineno - prev->offset >= prev->height) {
1331 /* Take the title line into account. */
1332 int lines = prev->lineno - prev->offset - prev->height + 1;
1334 /* Scroll the view that was split if the current line is
1335 * outside the new limited view. */
1336 do_scroll_view(prev, lines);
1339 if (prev && view != prev) {
1340 /* "Blur" the previous view. */
1342 update_view_title(prev);
1344 /* Continue loading split views in the background. */
1350 /* Clear the old view and let the incremental updating refill
1353 report("Loading...");
1359 /* If the view is backgrounded the above calls to report()
1360 * won't redraw the view title. */
1362 update_view_title(view);
1367 * User request switch noodle
1371 view_driver(struct view *view, enum request request)
1378 case REQ_MOVE_PAGE_UP:
1379 case REQ_MOVE_PAGE_DOWN:
1380 case REQ_MOVE_FIRST_LINE:
1381 case REQ_MOVE_LAST_LINE:
1382 move_view(view, request);
1385 case REQ_SCROLL_LINE_DOWN:
1386 case REQ_SCROLL_LINE_UP:
1387 case REQ_SCROLL_PAGE_DOWN:
1388 case REQ_SCROLL_PAGE_UP:
1389 scroll_view(view, request);
1396 case REQ_VIEW_PAGER:
1397 open_view(view, request, OPEN_DEFAULT);
1400 case REQ_MOVE_UP_ENTER:
1401 case REQ_MOVE_DOWN_ENTER:
1402 move_view(view, request);
1407 report("Nothing to enter");
1410 return view->ops->enter(view);
1414 int nviews = display[1] ? 2 : 1;
1415 int next_view = (current_view + 1) % nviews;
1417 if (next_view == current_view) {
1418 report("Only one view is displayed");
1422 current_view = next_view;
1423 /* Blur out the title of the previous view. */
1424 update_view_title(view);
1428 case REQ_TOGGLE_LINE_NUMBERS:
1429 opt_line_number = !opt_line_number;
1431 update_view_title(view);
1435 /* Always reload^Wrerun commands from the prompt. */
1436 open_view(view, opt_request, OPEN_RELOAD);
1439 case REQ_STOP_LOADING:
1440 foreach_view (view, i) {
1442 report("Stopped loaded the %s view", view->name),
1447 case REQ_SHOW_VERSION:
1448 report("Version: %s", VERSION);
1451 case REQ_SCREEN_RESIZE:
1454 case REQ_SCREEN_REDRAW:
1455 foreach_view (view, i) {
1457 update_view_title(view);
1461 case REQ_SCREEN_UPDATE:
1469 /* An unknown key will show most commonly used commands. */
1479 * View backend handlers
1483 pager_draw(struct view *view, unsigned int lineno)
1485 enum line_type type;
1490 if (view->offset + lineno >= view->lines)
1493 line = view->line[view->offset + lineno];
1494 type = get_line_type(line);
1496 wmove(view->win, lineno, 0);
1498 if (view->offset + lineno == view->lineno) {
1499 if (type == LINE_COMMIT) {
1500 string_copy(view->ref, line + 7);
1501 string_copy(ref_commit, view->ref);
1505 wchgat(view->win, -1, 0, type, NULL);
1508 attr = get_line_attr(type);
1509 wattrset(view->win, attr);
1511 linelen = strlen(line);
1513 if (opt_line_number || opt_tab_size < TABSIZE) {
1514 static char spaces[] = " ";
1515 int col_offset = 0, col = 0;
1517 if (opt_line_number) {
1518 unsigned long real_lineno = view->offset + lineno + 1;
1520 if (real_lineno == 1 ||
1521 (real_lineno % opt_num_interval) == 0) {
1522 wprintw(view->win, "%.*d", view->digits, real_lineno);
1525 waddnstr(view->win, spaces,
1526 MIN(view->digits, STRING_SIZE(spaces)));
1528 waddstr(view->win, ": ");
1529 col_offset = view->digits + 2;
1532 while (line && col_offset + col < view->width) {
1533 int cols_max = view->width - col_offset - col;
1537 if (*line == '\t') {
1538 assert(sizeof(spaces) > TABSIZE);
1541 cols = opt_tab_size - (col % opt_tab_size);
1544 line = strchr(line, '\t');
1545 cols = line ? line - text : strlen(text);
1548 waddnstr(view->win, text, MIN(cols, cols_max));
1553 int col = 0, pos = 0;
1555 for (; pos < linelen && col < view->width; pos++, col++)
1556 if (line[pos] == '\t')
1557 col += TABSIZE - (col % TABSIZE) - 1;
1559 waddnstr(view->win, line, pos);
1566 pager_read(struct view *view, char *line)
1568 /* Compress empty lines in the help view. */
1569 if (view == VIEW(REQ_VIEW_HELP) &&
1572 !*((char *) view->line[view->lines - 1]))
1575 view->line[view->lines] = strdup(line);
1576 if (!view->line[view->lines])
1584 pager_enter(struct view *view)
1586 char *line = view->line[view->lineno];
1588 if (get_line_type(line) == LINE_COMMIT) {
1589 if (view == VIEW(REQ_VIEW_LOG))
1590 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1592 open_view(view, REQ_VIEW_DIFF, OPEN_DEFAULT);
1598 static struct view_ops pager_ops = {
1606 static struct ref **get_refs(char *id);
1609 main_draw(struct view *view, unsigned int lineno)
1611 char buf[DATE_COLS + 1];
1612 struct commit *commit;
1613 enum line_type type;
1617 if (view->offset + lineno >= view->lines)
1620 commit = view->line[view->offset + lineno];
1621 if (!*commit->author)
1624 wmove(view->win, lineno, col);
1626 if (view->offset + lineno == view->lineno) {
1627 string_copy(view->ref, commit->id);
1628 string_copy(ref_commit, view->ref);
1630 wattrset(view->win, get_line_attr(type));
1631 wchgat(view->win, -1, 0, type, NULL);
1634 type = LINE_MAIN_COMMIT;
1635 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1638 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1639 waddnstr(view->win, buf, timelen);
1640 waddstr(view->win, " ");
1643 wmove(view->win, lineno, col);
1644 if (type != LINE_CURSOR)
1645 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1647 if (strlen(commit->author) > 19) {
1648 waddnstr(view->win, commit->author, 18);
1649 if (type != LINE_CURSOR)
1650 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1651 waddch(view->win, '~');
1653 waddstr(view->win, commit->author);
1657 if (type != LINE_CURSOR)
1658 wattrset(view->win, A_NORMAL);
1660 mvwaddch(view->win, lineno, col, ACS_LTEE);
1661 wmove(view->win, lineno, col + 2);
1668 if (type == LINE_CURSOR)
1670 else if (commit->refs[i]->tag)
1671 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1673 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1674 waddstr(view->win, "[");
1675 waddstr(view->win, commit->refs[i]->name);
1676 waddstr(view->win, "]");
1677 if (type != LINE_CURSOR)
1678 wattrset(view->win, A_NORMAL);
1679 waddstr(view->win, " ");
1680 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
1681 } while (commit->refs[i++]->next);
1684 if (type != LINE_CURSOR)
1685 wattrset(view->win, get_line_attr(type));
1688 int titlelen = strlen(commit->title);
1690 if (col + titlelen > view->width)
1691 titlelen = view->width - col;
1693 waddnstr(view->win, commit->title, titlelen);
1699 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1701 main_read(struct view *view, char *line)
1703 enum line_type type = get_line_type(line);
1704 struct commit *commit;
1708 commit = calloc(1, sizeof(struct commit));
1712 line += STRING_SIZE("commit ");
1714 view->line[view->lines++] = commit;
1715 string_copy(commit->id, line);
1716 commit->refs = get_refs(commit->id);
1721 char *ident = line + STRING_SIZE("author ");
1722 char *end = strchr(ident, '<');
1725 for (; end > ident && isspace(end[-1]); end--) ;
1729 commit = view->line[view->lines - 1];
1730 string_copy(commit->author, ident);
1732 /* Parse epoch and timezone */
1734 char *secs = strchr(end + 1, '>');
1738 if (!secs || secs[1] != ' ')
1742 time = (time_t) atol(secs);
1743 zone = strchr(secs, ' ');
1744 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1748 tz = ('0' - zone[1]) * 60 * 60 * 10;
1749 tz += ('0' - zone[2]) * 60 * 60;
1750 tz += ('0' - zone[3]) * 60;
1751 tz += ('0' - zone[4]) * 60;
1758 gmtime_r(&time, &commit->time);
1763 /* We should only ever end up here if there has already been a
1764 * commit line, however, be safe. */
1765 if (view->lines == 0)
1768 /* Fill in the commit title if it has not already been set. */
1769 commit = view->line[view->lines - 1];
1770 if (commit->title[0])
1773 /* Require titles to start with a non-space character at the
1774 * offset used by git log. */
1775 /* FIXME: More gracefull handling of titles; append "..." to
1776 * shortened titles, etc. */
1777 if (strncmp(line, " ", 4) ||
1781 string_copy(commit->title, line + 4);
1788 main_enter(struct view *view)
1790 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1794 static struct view_ops main_ops = {
1806 /* Whether or not the curses interface has been initialized. */
1807 bool cursed = FALSE;
1809 /* The status window is used for polling keystrokes. */
1810 static WINDOW *status_win;
1812 /* Update status and title window. */
1814 report(const char *msg, ...)
1816 static bool empty = TRUE;
1817 struct view *view = display[current_view];
1819 if (!empty || *msg) {
1822 va_start(args, msg);
1825 wmove(status_win, 0, 0);
1827 vwprintw(status_win, msg, args);
1832 wrefresh(status_win);
1837 update_view_title(view);
1839 /* Move the cursor to the right-most column of the cursor line.
1841 * XXX: This could turn out to be a bit expensive, but it ensures that
1842 * the cursor does not jump around. */
1844 wmove(view->win, view->lineno - view->offset, view->width - 1);
1845 wrefresh(view->win);
1849 /* Controls when nodelay should be in effect when polling user input. */
1851 set_nonblocking_input(bool loading)
1853 static unsigned int loading_views;
1855 if ((loading == FALSE && loading_views-- == 1) ||
1856 (loading == TRUE && loading_views++ == 0))
1857 nodelay(status_win, loading);
1865 /* Initialize the curses library */
1866 if (isatty(STDIN_FILENO)) {
1867 cursed = !!initscr();
1869 /* Leave stdin and stdout alone when acting as a pager. */
1870 FILE *io = fopen("/dev/tty", "r+");
1872 cursed = !!newterm(NULL, io, io);
1876 die("Failed to initialize curses");
1878 nonl(); /* Tell curses not to do NL->CR/NL on output */
1879 cbreak(); /* Take input chars one at a time, no wait for \n */
1880 noecho(); /* Don't echo input */
1881 leaveok(stdscr, TRUE);
1886 getmaxyx(stdscr, y, x);
1887 status_win = newwin(1, 0, y - 1, 0);
1889 die("Failed to create status window");
1891 /* Enable keyboard mapping */
1892 keypad(status_win, TRUE);
1893 wbkgdset(status_win, get_line_attr(LINE_STATUS));
1898 * Repository references
1901 static struct ref *refs;
1904 static struct ref **
1907 struct ref **id_refs = NULL;
1908 size_t id_refs_size = 0;
1911 for (i = 0; i < refs_size; i++) {
1914 if (strcmp(id, refs[i].id))
1917 tmp = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
1925 if (id_refs_size > 0)
1926 id_refs[id_refs_size - 1]->next = 1;
1927 id_refs[id_refs_size] = &refs[i];
1929 /* XXX: The properties of the commit chains ensures that we can
1930 * safely modify the shared ref. The repo references will
1931 * always be similar for the same id. */
1932 id_refs[id_refs_size]->next = 0;
1942 char *cmd_env = getenv("TIG_LS_REMOTE");
1943 char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
1944 FILE *pipe = popen(cmd, "r");
1945 char buffer[BUFSIZ];
1951 while ((line = fgets(buffer, sizeof(buffer), pipe))) {
1952 char *name = strchr(line, '\t');
1956 bool tag_commit = FALSE;
1962 namelen = strlen(name) - 1;
1964 /* Commits referenced by tags has "^{}" appended. */
1965 if (name[namelen - 1] == '}') {
1966 while (namelen > 0 && name[namelen] != '^')
1973 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
1976 name += STRING_SIZE("refs/tags/");
1979 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
1980 name += STRING_SIZE("refs/heads/");
1982 } else if (!strcmp(name, "HEAD")) {
1986 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
1990 ref = &refs[refs_size++];
1992 ref->name = strdup(name);
1996 string_copy(ref->id, line);
2014 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2020 static void die(const char *err, ...)
2026 va_start(args, err);
2027 fputs("tig: ", stderr);
2028 vfprintf(stderr, err, args);
2029 fputs("\n", stderr);
2036 main(int argc, char *argv[])
2039 enum request request;
2042 signal(SIGINT, quit);
2044 if (!parse_options(argc, argv))
2047 if (load_refs() == ERR)
2048 die("Failed to load refs.");
2050 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2051 view->cmd_env = getenv(view->cmd_env);
2053 request = opt_request;
2057 while (view_driver(display[current_view], request)) {
2061 foreach_view (view, i)
2064 /* Refresh, accept single keystroke of input */
2065 key = wgetch(status_win);
2066 request = get_request(key);
2068 /* Some low-level request handling. This keeps access to
2069 * status_win restricted. */
2073 /* Temporarily switch to line-oriented and echoed
2078 if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
2079 memcpy(opt_cmd, "git ", 4);
2080 opt_request = REQ_VIEW_PAGER;
2089 case REQ_SCREEN_RESIZE:
2093 getmaxyx(stdscr, height, width);
2095 /* Resize the status view and let the view driver take
2096 * care of resizing the displayed views. */
2097 wresize(status_win, 1, width);
2098 mvwin(status_win, height - 1, 0);
2099 wrefresh(status_win);
2115 * Known bugs and problems:
2117 * - If the screen width is very small the main view can draw
2118 * outside the current view causing bad wrapping.
2122 * Features that should be explored.
2130 * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
2132 * This program is free software; you can redistribute it and/or modify
2133 * it under the terms of the GNU General Public License as published by
2134 * the Free Software Foundation; either version 2 of the License, or
2135 * (at your option) any later version.
2140 * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
2141 * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
2142 * gitk(1): git repository browser written using tcl/tk,
2143 * gitview(1): git repository browser written using python/gtk.