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.
27 #define VERSION "tig-0.1"
47 static void die(const char *err, ...);
48 static void report(const char *msg, ...);
49 static void set_nonblocking_input(bool loading);
51 #define ABS(x) ((x) >= 0 ? (x) : -(x))
52 #define MIN(x, y) ((x) < (y) ? (x) : (y))
54 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
55 #define STRING_SIZE(x) (sizeof(x) - 1)
57 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
58 #define SIZEOF_CMD 1024 /* Size of command buffer. */
60 /* This color name can be used to refer to the default term colors. */
61 #define COLOR_DEFAULT (-1)
63 /* The format and size of the date column in the main view. */
64 #define DATE_FORMAT "%Y-%m-%d %H:%M"
65 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
67 /* The default interval between line numbers. */
68 #define NUMBER_INTERVAL 1
70 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
72 /* Some ascii-shorthands fitted into the ncurses namespace. */
74 #define KEY_RETURN '\r'
77 /* User action requests. */
79 /* Offset all requests to avoid conflicts with ncurses getch values. */
80 REQ_OFFSET = KEY_MAX + 1,
82 /* XXX: Keep the view request first and in sync with views[]. */
96 REQ_TOGGLE_LINE_NUMBERS,
107 REQ_SCROLL_LINE_DOWN,
109 REQ_SCROLL_PAGE_DOWN,
113 char id[41]; /* SHA1 ID. */
114 char title[75]; /* The first line of the commit message. */
115 char author[75]; /* The author of the commit. */
116 struct tm time; /* Date from the author ident. */
124 string_ncopy(char *dst, char *src, int dstlen)
126 strncpy(dst, src, dstlen - 1);
131 /* Shorthand for safely copying into a fixed buffer. */
132 #define string_copy(dst, src) \
133 string_ncopy(dst, src, sizeof(dst))
137 * NOTE: The following is a slightly modified copy of the git project's shell
138 * quoting routines found in the quote.c file.
140 * Help to copy the thing properly quoted for the shell safety. any single
141 * quote is replaced with '\'', any exclamation point is replaced with '\!',
142 * and the whole thing is enclosed in a
145 * original sq_quote result
146 * name ==> name ==> 'name'
147 * a b ==> a b ==> 'a b'
148 * a'b ==> a'\''b ==> 'a'\''b'
149 * a!b ==> a'\!'b ==> 'a'\!'b'
153 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
157 #define BUFPUT(x) ( (bufsize < SIZEOF_CMD) && (buf[bufsize++] = (x)) )
160 while ((c = *src++)) {
161 if (c == '\'' || c == '!') {
181 static int opt_line_number = FALSE;
182 static int opt_num_interval = NUMBER_INTERVAL;
183 static enum request opt_request = REQ_VIEW_MAIN;
184 static char opt_cmd[SIZEOF_CMD] = "";
185 static FILE *opt_pipe = NULL;
187 /* Returns the index of log or diff command or -1 to exit. */
189 parse_options(int argc, char *argv[])
193 for (i = 1; i < argc; i++) {
198 * Start up in log view using the internal log command.
200 if (!strcmp(opt, "-l")) {
201 opt_request = REQ_VIEW_LOG;
207 * Start up in diff view using the internal diff command.
209 if (!strcmp(opt, "-d")) {
210 opt_request = REQ_VIEW_DIFF;
215 * -n[INTERVAL], --line-number[=INTERVAL]::
216 * Prefix line numbers in log and diff view.
217 * Optionally, with interval different than each line.
219 if (!strncmp(opt, "-n", 2) ||
220 !strncmp(opt, "--line-number", 13)) {
226 } else if (opt[STRING_SIZE("--line-number")] == '=') {
227 num = opt + STRING_SIZE("--line-number=");
231 opt_num_interval = atoi(num);
233 opt_line_number = TRUE;
239 * Show version and exit.
241 if (!strcmp(opt, "-v") ||
242 !strcmp(opt, "--version")) {
243 printf("tig version %s\n", VERSION);
249 * End of tig(1) options. Useful when specifying commands
250 * for the main view. Example:
252 * $ tig -- --since=1.month
254 if (!strcmp(opt, "--")) {
261 * Open log view using the given git log options.
264 * Open diff view using the given git diff options.
267 * Open diff view using the given git show options.
269 if (!strcmp(opt, "log") ||
270 !strcmp(opt, "diff") ||
271 !strcmp(opt, "show")) {
272 opt_request = opt[0] == 'l'
273 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
279 * $ tig tag-1.0..HEAD
282 if (opt[0] && opt[0] != '-')
285 die("unknown command '%s'", opt);
288 if (!isatty(STDIN_FILENO)) {
292 * If stdin is a pipe, any log or diff options will be ignored and the
293 * pager view will be opened loading data from stdin. The pager mode
294 * can be used for colorizing output from various git commands.
296 * Example on how to colorize the output of git-show(1):
300 opt_request = REQ_VIEW_PAGER;
303 } else if (i < argc) {
307 * Git command options
308 * ~~~~~~~~~~~~~~~~~~~
309 * All git command options specified on the command line will
310 * be passed to the given command and all will be shell quoted
313 * NOTE: It is possible to specify options even for the main
314 * view. If doing this you should not touch the `--pretty`
317 * Example on how to open the log view and show both author and
318 * committer information:
320 * $ tig log --pretty=fuller
323 if (opt_request == REQ_VIEW_MAIN)
324 /* XXX: This is vulnerable to the user overriding
325 * options required for the main view parser. */
326 string_copy(opt_cmd, "git log --stat --pretty=raw");
328 string_copy(opt_cmd, "git");
329 buf_size = strlen(opt_cmd);
331 while (buf_size < sizeof(opt_cmd) && i < argc) {
332 opt_cmd[buf_size++] = ' ';
333 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
336 if (buf_size >= sizeof(opt_cmd))
337 die("command too long");
339 opt_cmd[buf_size] = 0;
352 #define HELP "(d)iff, (l)og, (m)ain, (q)uit, (v)ersion, (h)elp"
359 struct keymap keymap[] = {
364 * Switch to diff view.
366 * Switch to log view.
368 * Switch to main view.
370 * Switch to pager view.
374 * If in main view split the view
375 * and show the diff in the bottom view.
377 * Switch to next view.
379 { 'm', REQ_VIEW_MAIN },
380 { 'd', REQ_VIEW_DIFF },
381 { 'l', REQ_VIEW_LOG },
382 { 'p', REQ_VIEW_PAGER },
383 { 'h', REQ_VIEW_HELP },
385 { KEY_TAB, REQ_VIEW_NEXT },
386 { KEY_RETURN, REQ_ENTER },
392 * Move curser one line up.
394 * Move cursor one line down.
396 * Move curser one page up.
398 * Move cursor one page down.
400 * Jump to first line.
404 { KEY_UP, REQ_MOVE_UP },
405 { 'k', REQ_MOVE_UP },
406 { KEY_DOWN, REQ_MOVE_DOWN },
407 { 'j', REQ_MOVE_DOWN },
408 { KEY_HOME, REQ_MOVE_FIRST_LINE },
409 { KEY_END, REQ_MOVE_LAST_LINE },
410 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
411 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
417 * Scroll view one line up.
419 * Scroll view one line down.
421 * Scroll view one page up.
423 * Scroll view one page down.
425 { KEY_IC, REQ_SCROLL_LINE_UP },
426 { KEY_DC, REQ_SCROLL_LINE_DOWN },
427 { 'w', REQ_SCROLL_PAGE_UP },
428 { 's', REQ_SCROLL_PAGE_DOWN },
438 * Stop all background loading.
442 * Toggle line numbers on/off.
444 * Open prompt. This allows you to specify what git command to run.
450 { KEY_ESC, REQ_QUIT },
452 { 'z', REQ_STOP_LOADING },
453 { 'v', REQ_SHOW_VERSION },
454 { 'r', REQ_SCREEN_REDRAW },
455 { 'n', REQ_TOGGLE_LINE_NUMBERS },
458 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
459 { ERR, REQ_SCREEN_UPDATE },
467 for (i = 0; i < ARRAY_SIZE(keymap); i++)
468 if (keymap[i].alias == key)
469 return keymap[i].request;
471 return (enum request) key;
476 * Line-oriented content detection.
480 /* Line type String to match Foreground Background Attributes
481 * --------- --------------- ---------- ---------- ---------- */ \
483 LINE(DIFF, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
484 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
485 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
486 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
487 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
488 LINE(DIFF_OLDMODE, "old mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
489 LINE(DIFF_NEWMODE, "new mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
490 LINE(DIFF_COPY, "copy ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
491 LINE(DIFF_RENAME, "rename ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
492 LINE(DIFF_SIM, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
493 LINE(DIFF_DISSIM, "dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
494 /* Pretty print commit header */ \
495 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
496 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
497 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
498 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
499 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
500 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 /* Raw commit header */ \
502 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
503 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
504 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
505 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
506 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
508 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
509 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
511 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
512 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
513 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
514 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
515 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
516 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
517 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
518 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
519 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0),
522 #define LINE(type, line, fg, bg, attr) \
529 char *line; /* The start of line to match. */
530 int linelen; /* Size of string to match. */
531 int fg, bg, attr; /* Color and text attributes for the lines. */
534 static struct line_info line_info[] = {
535 #define LINE(type, line, fg, bg, attr) \
536 { (line), STRING_SIZE(line), (fg), (bg), (attr) }
541 static enum line_type
542 get_line_type(char *line)
544 int linelen = strlen(line);
547 for (type = 0; type < ARRAY_SIZE(line_info); type++)
548 /* Case insensitive search matches Signed-off-by lines better. */
549 if (linelen >= line_info[type].linelen &&
550 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
557 get_line_attr(enum line_type type)
559 assert(type < ARRAY_SIZE(line_info));
560 return COLOR_PAIR(type) | line_info[type].attr;
566 int default_bg = COLOR_BLACK;
567 int default_fg = COLOR_WHITE;
572 if (use_default_colors() != ERR) {
577 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
578 struct line_info *info = &line_info[type];
579 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
580 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
582 init_pair(type, fg, bg);
588 * ENVIRONMENT VARIABLES
589 * ---------------------
590 * It is possible to alter which commands are used for the different views.
591 * If for example you prefer commits in the main to be sorted by date and
592 * only show 500 commits, use:
594 * $ TIG_MAIN_CMD="git log --date-order -n500 --pretty=raw %s" tig
596 * Or set the variable permanently in your environment.
598 * Notice, how `%s` is used to specify the commit reference. There can
599 * be a maximum of 5 `%s` ref specifications.
602 * The command used for the diff view. By default, git show is used
606 * The command used for the log view.
609 * The command used for the main view. Note, you must always specify
610 * the option: `--pretty=raw` since the main view parser expects to
614 #define TIG_DIFF_CMD \
615 "git show --patch-with-stat --find-copies-harder -B -C %s"
617 #define TIG_LOG_CMD \
618 "git log --cc --stat -n100 %s"
620 #define TIG_MAIN_CMD \
621 "git log --topo-order --stat --pretty=raw %s"
623 /* We silently ignore that the following are also exported. */
625 #define TIG_HELP_CMD \
626 "man tig 2> /dev/null"
628 #define TIG_PAGER_CMD \
637 const char *name; /* View name */
638 char *cmd_fmt; /* Default command line format */
639 char *cmd_env; /* Command line set via environment */
640 char *id; /* Points to either of ref_{head,commit} */
641 size_t objsize; /* Size of objects in the line index */
644 /* Draw one line; @lineno must be < view->height. */
645 bool (*draw)(struct view *view, unsigned int lineno);
646 /* Read one line; updates view->line. */
647 bool (*read)(struct view *view, char *line);
648 /* Depending on view, change display based on current line. */
649 bool (*enter)(struct view *view);
652 char cmd[SIZEOF_CMD]; /* Command buffer */
653 char ref[SIZEOF_REF]; /* Hovered commit reference */
654 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
656 int height, width; /* The width and height of the main window */
657 WINDOW *win; /* The main window */
658 WINDOW *title; /* The title window living below the main window */
661 unsigned long offset; /* Offset of the window top */
662 unsigned long lineno; /* Current line number */
665 unsigned long lines; /* Total number of lines */
666 void **line; /* Line index; each line contains user data */
667 unsigned int digits; /* Number of digits in the lines member. */
674 static struct view_ops pager_ops;
675 static struct view_ops main_ops;
677 char ref_head[SIZEOF_REF] = "HEAD";
678 char ref_commit[SIZEOF_REF] = "HEAD";
680 #define VIEW_STR(name, cmd, env, ref, objsize, ops) \
681 { name, cmd, #env, ref, objsize, ops }
683 #define VIEW_(id, name, ops, ref, objsize) \
684 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, objsize, ops)
686 static struct view views[] = {
687 VIEW_(MAIN, "main", &main_ops, ref_head, sizeof(struct commit)),
688 VIEW_(DIFF, "diff", &pager_ops, ref_commit, sizeof(char)),
689 VIEW_(LOG, "log", &pager_ops, ref_head, sizeof(char)),
690 VIEW_(HELP, "help", &pager_ops, ref_head, sizeof(char)),
691 VIEW_(PAGER, "pager", &pager_ops, "static", sizeof(char)),
694 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
696 /* The display array of active views and the index of the current view. */
697 static struct view *display[2];
698 static unsigned int current_view;
700 #define foreach_view(view, i) \
701 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
705 redraw_view_from(struct view *view, int lineno)
707 assert(0 <= lineno && lineno < view->height);
709 for (; lineno < view->height; lineno++) {
710 if (!view->ops->draw(view, lineno))
714 redrawwin(view->win);
719 redraw_view(struct view *view)
722 redraw_view_from(view, 0);
729 struct view *base = display[0];
730 struct view *view = display[1] ? display[1] : display[0];
732 /* Setup window dimensions */
734 getmaxyx(stdscr, base->height, base->width);
736 /* Make room for the status window. */
740 /* Horizontal split. */
741 view->width = base->width;
742 view->height = SCALE_SPLIT_VIEW(base->height);
743 base->height -= view->height;
745 /* Make room for the title bar. */
749 /* Make room for the title bar. */
754 foreach_view (view, i) {
756 view->win = newwin(view->height, 0, offset, 0);
758 die("Failed to create %s view", view->name);
760 scrollok(view->win, TRUE);
762 view->title = newwin(1, 0, offset + view->height, 0);
764 die("Failed to create title window");
767 wresize(view->win, view->height, view->width);
768 mvwin(view->win, offset, 0);
769 mvwin(view->title, offset + view->height, 0);
773 offset += view->height + 1;
778 update_view_title(struct view *view)
780 if (view == display[current_view])
781 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
783 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
786 wmove(view->title, 0, 0);
788 /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
791 wprintw(view->title, "[%s] ref: %s", view->name, view->ref);
793 wprintw(view->title, "[%s]", view->name);
796 char *type = view == VIEW(REQ_VIEW_MAIN) ? "commit" : "line";
798 wprintw(view->title, " - %s %d of %d (%d%%)",
802 (view->lineno + 1) * 100 / view->lines);
805 wrefresh(view->title);
812 /* Scrolling backend */
814 do_scroll_view(struct view *view, int lines)
816 /* The rendering expects the new offset. */
817 view->offset += lines;
819 assert(0 <= view->offset && view->offset < view->lines);
822 /* Redraw the whole screen if scrolling is pointless. */
823 if (view->height < ABS(lines)) {
827 int line = lines > 0 ? view->height - lines : 0;
828 int end = line + ABS(lines);
830 wscrl(view->win, lines);
832 for (; line < end; line++) {
833 if (!view->ops->draw(view, line))
838 /* Move current line into the view. */
839 if (view->lineno < view->offset) {
840 view->lineno = view->offset;
841 view->ops->draw(view, 0);
843 } else if (view->lineno >= view->offset + view->height) {
844 view->lineno = view->offset + view->height - 1;
845 view->ops->draw(view, view->lineno - view->offset);
848 assert(view->offset <= view->lineno && view->lineno < view->lines);
850 redrawwin(view->win);
855 /* Scroll frontend */
857 scroll_view(struct view *view, enum request request)
862 case REQ_SCROLL_PAGE_DOWN:
863 lines = view->height;
864 case REQ_SCROLL_LINE_DOWN:
865 if (view->offset + lines > view->lines)
866 lines = view->lines - view->offset;
868 if (lines == 0 || view->offset + view->height >= view->lines) {
869 report("Cannot scroll beyond the last line");
874 case REQ_SCROLL_PAGE_UP:
875 lines = view->height;
876 case REQ_SCROLL_LINE_UP:
877 if (lines > view->offset)
878 lines = view->offset;
881 report("Cannot scroll beyond the first line");
889 die("request %d not handled in switch", request);
892 do_scroll_view(view, lines);
897 move_view(struct view *view, enum request request)
902 case REQ_MOVE_FIRST_LINE:
903 steps = -view->lineno;
906 case REQ_MOVE_LAST_LINE:
907 steps = view->lines - view->lineno - 1;
910 case REQ_MOVE_PAGE_UP:
911 steps = view->height > view->lineno
912 ? -view->lineno : -view->height;
915 case REQ_MOVE_PAGE_DOWN:
916 steps = view->lineno + view->height >= view->lines
917 ? view->lines - view->lineno - 1 : view->height;
929 die("request %d not handled in switch", request);
932 if (steps <= 0 && view->lineno == 0) {
933 report("Cannot move beyond the first line");
936 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
937 report("Cannot move beyond the last line");
941 /* Move the current line */
942 view->lineno += steps;
943 assert(0 <= view->lineno && view->lineno < view->lines);
945 /* Repaint the old "current" line if we be scrolling */
946 if (ABS(steps) < view->height) {
947 int prev_lineno = view->lineno - steps - view->offset;
949 wmove(view->win, prev_lineno, 0);
950 wclrtoeol(view->win);
951 view->ops->draw(view, prev_lineno);
954 /* Check whether the view needs to be scrolled */
955 if (view->lineno < view->offset ||
956 view->lineno >= view->offset + view->height) {
957 if (steps < 0 && -steps > view->offset) {
958 steps = -view->offset;
960 } else if (steps > 0) {
961 if (view->lineno == view->lines - 1 &&
962 view->lines > view->height) {
963 steps = view->lines - view->offset - 1;
964 if (steps >= view->height)
965 steps -= view->height - 1;
969 do_scroll_view(view, steps);
973 /* Draw the current line */
974 view->ops->draw(view, view->lineno - view->offset);
976 redrawwin(view->win);
983 * Incremental updating
987 begin_update(struct view *view)
992 string_copy(view->cmd, opt_cmd);
994 /* When running random commands, the view ref could have become
995 * invalid so clear it. */
998 char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1000 if (snprintf(view->cmd, sizeof(view->cmd), format,
1001 id, id, id, id, id) >= sizeof(view->cmd))
1005 /* Special case for the pager view. */
1007 view->pipe = opt_pipe;
1010 view->pipe = popen(view->cmd, "r");
1016 set_nonblocking_input(TRUE);
1021 string_copy(view->vid, id);
1026 for (i = 0; i < view->lines; i++)
1028 free(view->line[i]);
1034 view->start_time = time(NULL);
1040 end_update(struct view *view)
1044 set_nonblocking_input(FALSE);
1045 if (view->pipe == stdin)
1053 update_view(struct view *view)
1055 char buffer[BUFSIZ];
1058 /* The number of lines to read. If too low it will cause too much
1059 * redrawing (and possible flickering), if too high responsiveness
1061 unsigned long lines = view->height;
1062 int redraw_from = -1;
1067 /* Only redraw if lines are visible. */
1068 if (view->offset + view->height >= view->lines)
1069 redraw_from = view->lines - view->offset;
1071 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1077 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1080 linelen = strlen(line);
1082 line[linelen - 1] = 0;
1084 if (!view->ops->read(view, line))
1094 lines = view->lines;
1095 for (digits = 0; lines; digits++)
1098 /* Keep the displayed view in sync with line number scaling. */
1099 if (digits != view->digits) {
1100 view->digits = digits;
1105 if (redraw_from >= 0) {
1106 /* If this is an incremental update, redraw the previous line
1107 * since for commits some members could have changed when
1108 * loading the main view. */
1109 if (redraw_from > 0)
1112 /* Incrementally draw avoids flickering. */
1113 redraw_view_from(view, redraw_from);
1116 /* Update the title _after_ the redraw so that if the redraw picks up a
1117 * commit reference in view->ref it'll be available here. */
1118 update_view_title(view);
1120 if (ferror(view->pipe)) {
1121 report("Failed to read: %s", strerror(errno));
1124 } else if (feof(view->pipe)) {
1125 time_t secs = time(NULL) - view->start_time;
1127 if (view == VIEW(REQ_VIEW_HELP)) {
1132 report("Loaded %d lines in %ld second%s", view->lines, secs,
1133 secs == 1 ? "" : "s");
1140 report("Allocation failure");
1148 OPEN_DEFAULT = 0, /* Use default view switching. */
1149 OPEN_SPLIT = 1, /* Split current view. */
1150 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1151 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1155 open_view(struct view *prev, enum request request, enum open_flags flags)
1157 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1158 bool split = !!(flags & OPEN_SPLIT);
1159 bool reload = !!(flags & OPEN_RELOAD);
1160 struct view *view = VIEW(request);
1161 struct view *displayed;
1164 /* Cycle between displayed views and count the views. */
1165 foreach_view (displayed, nviews) {
1167 view == displayed &&
1168 !strcmp(view->vid, prev->vid)) {
1169 current_view = nviews;
1170 /* Blur out the title of the previous view. */
1171 update_view_title(prev);
1172 report("Switching to %s view", view->name);
1177 if (view == prev && nviews == 1 && !reload) {
1178 report("Already in %s view", view->name);
1182 if ((reload || strcmp(view->vid, view->id)) &&
1183 !begin_update(view)) {
1184 report("Failed to load %s view", view->name);
1189 display[current_view + 1] = view;
1193 /* Maximize the current view. */
1194 memset(display, 0, sizeof(display));
1196 display[current_view] = view;
1201 if (split && prev->lineno - prev->offset >= prev->height) {
1202 /* Take the title line into account. */
1203 int lines = prev->lineno - prev->offset - prev->height + 1;
1205 /* Scroll the view that was split if the current line is
1206 * outside the new limited view. */
1207 do_scroll_view(prev, lines);
1210 if (prev && view != prev) {
1211 /* "Blur" the previous view. */
1212 update_view_title(prev);
1214 /* Continue loading split views in the background. */
1220 /* Clear the old view and let the incremental updating refill
1223 report("Loading...");
1232 * User request switch noodle
1236 view_driver(struct view *view, enum request request)
1243 case REQ_MOVE_PAGE_UP:
1244 case REQ_MOVE_PAGE_DOWN:
1245 case REQ_MOVE_FIRST_LINE:
1246 case REQ_MOVE_LAST_LINE:
1247 move_view(view, request);
1250 case REQ_SCROLL_LINE_DOWN:
1251 case REQ_SCROLL_LINE_UP:
1252 case REQ_SCROLL_PAGE_DOWN:
1253 case REQ_SCROLL_PAGE_UP:
1254 scroll_view(view, request);
1261 case REQ_VIEW_PAGER:
1262 open_view(view, request, OPEN_DEFAULT);
1267 report("Nothing to enter");
1270 return view->ops->enter(view);
1274 int nviews = display[1] ? 2 : 1;
1275 int next_view = (current_view + 1) % nviews;
1277 if (next_view == current_view) {
1278 report("Only one view is displayed");
1282 current_view = next_view;
1283 /* Blur out the title of the previous view. */
1284 update_view_title(view);
1285 report("Switching to %s view", display[current_view]->name);
1288 case REQ_TOGGLE_LINE_NUMBERS:
1289 opt_line_number = !opt_line_number;
1294 /* Always reload^Wrerun commands from the prompt. */
1295 open_view(view, opt_request, OPEN_RELOAD);
1298 case REQ_STOP_LOADING:
1299 foreach_view (view, i) {
1301 report("Stopped loaded of %s view", view->name),
1306 case REQ_SHOW_VERSION:
1307 report("Version: %s", VERSION);
1310 case REQ_SCREEN_REDRAW:
1311 foreach_view (view, i) {
1313 update_view_title(view);
1317 case REQ_SCREEN_UPDATE:
1325 /* An unknown key will show most commonly used commands. */
1335 * View backend handlers
1339 pager_draw(struct view *view, unsigned int lineno)
1341 enum line_type type;
1346 if (view->offset + lineno >= view->lines)
1349 line = view->line[view->offset + lineno];
1350 type = get_line_type(line);
1352 if (view->offset + lineno == view->lineno) {
1353 if (type == LINE_COMMIT) {
1354 string_copy(view->ref, line + 7);
1355 string_copy(ref_commit, view->ref);
1361 attr = get_line_attr(type);
1362 wattrset(view->win, attr);
1364 linelen = strlen(line);
1365 linelen = MIN(linelen, view->width);
1367 if (opt_line_number) {
1368 static char indent[] = " ";
1369 unsigned long real_lineno = view->offset + lineno + 1;
1372 if (real_lineno == 1 || (real_lineno % opt_num_interval) == 0)
1373 mvwprintw(view->win, lineno, 0, "%.*d", view->digits, real_lineno);
1375 else if (view->digits < sizeof(indent))
1376 mvwaddnstr(view->win, lineno, 0, indent, view->digits);
1378 waddstr(view->win, ": ");
1381 if (*line == '\t') {
1382 waddnstr(view->win, " ", 8 - (col % 8));
1383 col += 8 - (col % 8);
1387 char *tab = strchr(line, '\t');
1390 waddnstr(view->win, line, tab - line);
1392 waddstr(view->win, line);
1397 waddstr(view->win, line);
1401 /* NOTE: Code for only highlighting the text on the cursor line.
1402 * Kept since I've not yet decided whether to highlight the
1403 * entire line or not. --fonseca */
1404 /* No empty lines makes cursor drawing and clearing implicit. */
1406 line = " ", linelen = 1;
1408 mvwaddnstr(view->win, lineno, 0, line, linelen);
1411 /* Paint the rest of the line if it's the cursor line. */
1412 if (type == LINE_CURSOR)
1413 wchgat(view->win, -1, 0, type, NULL);
1419 pager_read(struct view *view, char *line)
1421 /* For some reason the piped man page has many empty lines
1422 * so skip successive emptys lines to work around it. */
1423 if (view == VIEW(REQ_VIEW_HELP) &&
1426 !*((char *) view->line[view->lines - 1]))
1429 view->line[view->lines] = strdup(line);
1430 if (!view->line[view->lines])
1438 pager_enter(struct view *view)
1440 char *line = view->line[view->lineno];
1442 if (get_line_type(line) == LINE_COMMIT) {
1443 open_view(view, REQ_VIEW_DIFF, OPEN_DEFAULT);
1449 static struct view_ops pager_ops = {
1457 main_draw(struct view *view, unsigned int lineno)
1459 char buf[DATE_COLS + 1];
1460 struct commit *commit;
1461 enum line_type type;
1465 if (view->offset + lineno >= view->lines)
1468 commit = view->line[view->offset + lineno];
1469 if (!*commit->author)
1472 if (view->offset + lineno == view->lineno) {
1473 string_copy(view->ref, commit->id);
1474 string_copy(ref_commit, view->ref);
1477 type = LINE_MAIN_COMMIT;
1480 wmove(view->win, lineno, cols);
1481 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1483 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1484 waddnstr(view->win, buf, timelen);
1485 waddstr(view->win, " ");
1488 wmove(view->win, lineno, cols);
1489 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1491 if (strlen(commit->author) > 19) {
1492 waddnstr(view->win, commit->author, 18);
1493 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1494 waddch(view->win, '~');
1496 waddstr(view->win, commit->author);
1500 wattrset(view->win, A_NORMAL);
1501 mvwaddch(view->win, lineno, cols, ACS_LTEE);
1502 wattrset(view->win, get_line_attr(type));
1503 mvwaddstr(view->win, lineno, cols + 2, commit->title);
1504 wattrset(view->win, A_NORMAL);
1509 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1511 main_read(struct view *view, char *line)
1513 enum line_type type = get_line_type(line);
1514 struct commit *commit;
1518 commit = calloc(1, sizeof(struct commit));
1522 line += STRING_SIZE("commit ");
1524 view->line[view->lines++] = commit;
1525 string_copy(commit->id, line);
1530 char *ident = line + STRING_SIZE("author ");
1531 char *end = strchr(ident, '<');
1534 for (; end > ident && isspace(end[-1]); end--) ;
1538 commit = view->line[view->lines - 1];
1539 string_copy(commit->author, ident);
1541 /* Parse epoch and timezone */
1543 char *secs = strchr(end + 1, '>');
1547 if (!secs || secs[1] != ' ')
1551 time = (time_t) atol(secs);
1552 zone = strchr(secs, ' ');
1553 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1557 tz = ('0' - zone[1]) * 60 * 60 * 10;
1558 tz += ('0' - zone[2]) * 60 * 60;
1559 tz += ('0' - zone[3]) * 60;
1560 tz += ('0' - zone[4]) * 60;
1567 gmtime_r(&time, &commit->time);
1572 /* We should only ever end up here if there has already been a
1573 * commit line, however, be safe. */
1574 if (view->lines == 0)
1577 /* Fill in the commit title if it has not already been set. */
1578 commit = view->line[view->lines - 1];
1579 if (commit->title[0])
1582 /* Require titles to start with a non-space character at the
1583 * offset used by git log. */
1584 /* FIXME: More gracefull handling of titles; append "..." to
1585 * shortened titles, etc. */
1586 if (strncmp(line, " ", 4) ||
1590 string_copy(commit->title, line + 4);
1597 main_enter(struct view *view)
1599 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1603 static struct view_ops main_ops = {
1613 /* Whether or not the curses interface has been initialized. */
1614 bool cursed = FALSE;
1616 /* The status window is used for polling keystrokes. */
1617 static WINDOW *status_win;
1619 /* Update status and title window. */
1621 report(const char *msg, ...)
1625 va_start(args, msg);
1627 /* Update the title window first, so the cursor ends up in the status
1629 update_view_title(display[current_view]);
1632 wmove(status_win, 0, 0);
1633 vwprintw(status_win, msg, args);
1634 wrefresh(status_win);
1639 /* Controls when nodelay should be in effect when polling user input. */
1641 set_nonblocking_input(bool loading)
1643 /* The number of loading views. */
1644 static unsigned int nloading;
1646 if ((loading == FALSE && nloading-- == 1) ||
1647 (loading == TRUE && nloading++ == 0))
1648 nodelay(status_win, loading);
1656 /* Initialize the curses library */
1657 if (isatty(STDIN_FILENO)) {
1658 cursed = !!initscr();
1660 /* Leave stdin and stdout alone when acting as a pager. */
1661 FILE *io = fopen("/dev/tty", "r+");
1663 cursed = !!newterm(NULL, io, io);
1667 die("Failed to initialize curses");
1669 nonl(); /* Tell curses not to do NL->CR/NL on output */
1670 cbreak(); /* Take input chars one at a time, no wait for \n */
1671 noecho(); /* Don't echo input */
1672 leaveok(stdscr, TRUE);
1677 getmaxyx(stdscr, y, x);
1678 status_win = newwin(1, 0, y - 1, 0);
1680 die("Failed to create status window");
1682 /* Enable keyboard mapping */
1683 keypad(status_win, TRUE);
1684 wbkgdset(status_win, get_line_attr(LINE_STATUS));
1694 /* XXX: Restore tty modes and let the OS cleanup the rest! */
1700 static void die(const char *err, ...)
1706 va_start(args, err);
1707 fputs("tig: ", stderr);
1708 vfprintf(stderr, err, args);
1709 fputs("\n", stderr);
1716 main(int argc, char *argv[])
1719 enum request request;
1722 signal(SIGINT, quit);
1724 if (!parse_options(argc, argv))
1727 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1728 view->cmd_env = getenv(view->cmd_env);
1730 request = opt_request;
1734 while (view_driver(display[current_view], request)) {
1738 foreach_view (view, i)
1741 /* Refresh, accept single keystroke of input */
1742 key = wgetch(status_win);
1743 request = get_request(key);
1745 if (request == REQ_PROMPT) {
1747 /* Temporarily switch to line-oriented and echoed
1752 if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
1753 memcpy(opt_cmd, "git ", 4);
1754 opt_request = REQ_VIEW_PAGER;
1772 * Features that should be explored.
1774 * - Terminal resizing support. I am yet to figure out whether catching
1775 * SIGWINCH is preferred over using ncurses' built-in support for resizing.
1781 * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
1783 * This program is free software; you can redistribute it and/or modify
1784 * it under the terms of the GNU General Public License as published by
1785 * the Free Software Foundation; either version 2 of the License, or
1786 * (at your option) any later version.
1791 * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
1792 * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
1793 * gitk(1): git repository browser written using tcl/tk,
1794 * gitview(1): git repository browser written using python/gtk.