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.
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.
30 * Using tig(1) as a pager, it will display input from stdin and try
35 #define VERSION "tig-0.3"
55 static void die(const char *err, ...);
56 static void report(const char *msg, ...);
57 static void set_nonblocking_input(bool loading);
58 static size_t utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed);
60 #define ABS(x) ((x) >= 0 ? (x) : -(x))
61 #define MIN(x, y) ((x) < (y) ? (x) : (y))
63 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
64 #define STRING_SIZE(x) (sizeof(x) - 1)
66 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
67 #define SIZEOF_CMD 1024 /* Size of command buffer. */
69 /* This color name can be used to refer to the default term colors. */
70 #define COLOR_DEFAULT (-1)
72 #define TIG_HELP "(d)iff, (l)og, (m)ain, (q)uit, (h)elp"
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 ")
78 #define AUTHOR_COLS 20
80 /* The default interval between line numbers. */
81 #define NUMBER_INTERVAL 1
85 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
87 /* Some ascii-shorthands fitted into the ncurses namespace. */
89 #define KEY_RETURN '\r'
93 /* User action requests. */
95 /* Offset all requests to avoid conflicts with ncurses getch values. */
96 REQ_OFFSET = KEY_MAX + 1,
98 /* XXX: Keep the view request first and in sync with views[]. */
113 REQ_TOGGLE_LINE_NUMBERS,
127 REQ_SCROLL_LINE_DOWN,
129 REQ_SCROLL_PAGE_DOWN,
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? */
139 static struct ref **get_refs(char *id);
147 string_ncopy(char *dst, const char *src, int dstlen)
149 strncpy(dst, src, dstlen - 1);
154 /* Shorthand for safely copying into a fixed buffer. */
155 #define string_copy(dst, src) \
156 string_ncopy(dst, src, sizeof(dst))
161 * NOTE: The following is a slightly modified copy of the git project's shell
162 * quoting routines found in the quote.c file.
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
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'
177 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
181 #define BUFPUT(x) do { if (bufsize < SIZEOF_CMD) buf[bufsize++] = (x); } while (0)
184 while ((c = *src++)) {
185 if (c == '\'' || c == '!') {
205 static const char usage[] =
206 VERSION " (" __DATE__ ")\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"
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";
224 /* Option and state variables. */
225 static bool opt_line_number = FALSE;
226 static int opt_num_interval = NUMBER_INTERVAL;
227 static int opt_tab_size = TABSIZE;
228 static enum request opt_request = REQ_VIEW_MAIN;
229 static char opt_cmd[SIZEOF_CMD] = "";
230 static FILE *opt_pipe = NULL;
232 /* Returns the index of log or diff command or -1 to exit. */
234 parse_options(int argc, char *argv[])
238 for (i = 1; i < argc; i++) {
243 * Start up in log view using the internal log command.
245 if (!strcmp(opt, "-l")) {
246 opt_request = REQ_VIEW_LOG;
252 * Start up in diff view using the internal diff command.
254 if (!strcmp(opt, "-d")) {
255 opt_request = REQ_VIEW_DIFF;
260 * -n[INTERVAL], --line-number[=INTERVAL]::
261 * Prefix line numbers in log and diff view.
262 * Optionally, with interval different than each line.
264 if (!strncmp(opt, "-n", 2) ||
265 !strncmp(opt, "--line-number", 13)) {
271 } else if (opt[STRING_SIZE("--line-number")] == '=') {
272 num = opt + STRING_SIZE("--line-number=");
276 opt_num_interval = atoi(num);
278 opt_line_number = TRUE;
283 * -t[NSPACES], --tab-size[=NSPACES]::
284 * Set the number of spaces tabs should be expanded to.
286 if (!strncmp(opt, "-t", 2) ||
287 !strncmp(opt, "--tab-size", 10)) {
293 } else if (opt[STRING_SIZE("--tab-size")] == '=') {
294 num = opt + STRING_SIZE("--tab-size=");
298 opt_tab_size = MIN(atoi(num), TABSIZE);
304 * Show version and exit.
306 if (!strcmp(opt, "-v") ||
307 !strcmp(opt, "--version")) {
308 printf("tig version %s\n", VERSION);
314 * Show help message and exit.
316 if (!strcmp(opt, "-h") ||
317 !strcmp(opt, "--help")) {
324 * End of tig(1) options. Useful when specifying command
325 * options for the main view. Example:
327 * $ tig -- --since=1.month
329 if (!strcmp(opt, "--")) {
335 * log [git log options]::
336 * Open log view using the given git log options.
338 * diff [git diff options]::
339 * Open diff view using the given git diff options.
341 * show [git show options]::
342 * Open diff view using the given git show options.
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;
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:
360 * $ tig tag-1.0..HEAD
362 if (opt[0] && opt[0] != '-')
365 die("unknown command '%s'", opt);
368 if (!isatty(STDIN_FILENO)) {
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.
376 * Example on how to colorize the output of git-show(1):
380 opt_request = REQ_VIEW_PAGER;
383 } else if (i < argc) {
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.
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.
397 * Example on how to open the log view and show both author and
398 * committer information:
400 * $ tig log --pretty=fuller
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.
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");
413 string_copy(opt_cmd, "git");
414 buf_size = strlen(opt_cmd);
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++]);
421 if (buf_size >= sizeof(opt_cmd))
422 die("command too long");
424 opt_cmd[buf_size] = 0;
433 * Line-oriented content detection.
437 /* Line type String to match Foreground Background Attributes
438 * --------- --------------- ---------- ---------- ---------- */ \
440 LINE(DIFF, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
441 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
442 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
443 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
444 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
445 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
446 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
447 LINE(DIFF_COPY, "copy ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
448 LINE(DIFF_RENAME, "rename ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
449 LINE(DIFF_SIM, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(DIFF_DISSIM, "dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
451 /* Pretty print commit header */ \
452 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
453 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
454 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
455 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
456 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
457 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
458 /* Raw commit header */ \
459 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
460 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
461 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
462 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
463 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
465 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
466 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
468 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
469 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
470 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
471 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
472 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
473 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
474 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
475 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
476 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
477 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
478 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD),
481 #define LINE(type, line, fg, bg, attr) \
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. */
493 static struct line_info line_info[] = {
494 #define LINE(type, line, fg, bg, attr) \
495 { (line), STRING_SIZE(line), (fg), (bg), (attr) }
500 static enum line_type
501 get_line_type(char *line)
503 int linelen = strlen(line);
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))
516 get_line_attr(enum line_type type)
518 assert(type < ARRAY_SIZE(line_info));
519 return COLOR_PAIR(type) | line_info[type].attr;
525 int default_bg = COLOR_BLACK;
526 int default_fg = COLOR_WHITE;
531 if (use_default_colors() != ERR) {
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;
541 init_pair(type, fg, bg);
547 * ENVIRONMENT VARIABLES
548 * ---------------------
549 * Several options related to the interface with git can be configured
550 * via environment options.
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 ']':
557 * 2006-03-26 19:42 Petr Baudis | [cogito-0.17.1] Cogito 0.17.1
559 * If you want to filter out certain directories under `.git/refs/`, say
560 * `tmp` you can do it by setting the following variable:
562 * $ TIG_LS_REMOTE="git ls-remote . | sed /\/tmp\//d" tig
564 * Or set the variable permanently in your environment.
567 * Set command for retrieving all repository references. The command
568 * should output data in the same format as git-ls-remote(1).
571 #define TIG_LS_REMOTE \
572 "git ls-remote . 2>/dev/null"
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:
582 * $ TIG_MAIN_CMD="git log --date-order -n500 --pretty=raw %s" tig
584 * Or set the variable permanently in your environment.
586 * Notice, how `%s` is used to specify the commit reference. There can
587 * be a maximum of 5 `%s` ref specifications.
590 * The command used for the diff view. By default, git show is used
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.
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
604 #define TIG_DIFF_CMD \
605 "git show --patch-with-stat --find-copies-harder -B -C %s"
607 #define TIG_LOG_CMD \
608 "git log --cc --stat -n100 %s"
610 #define TIG_MAIN_CMD \
611 "git log --topo-order --stat --pretty=raw %s"
613 /* ... silently ignore that the following are also exported. */
615 #define TIG_HELP_CMD \
616 "man tig 2>/dev/null"
618 #define TIG_PAGER_CMD \
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
630 * If you are in the log view and press 'Enter' when the current line is a
631 * commit line, such as:
633 * commit 4d55caff4cc89335192f3e566004b4ceef572521
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'.
642 /* The display array of active views and the index of the current view. */
643 static struct view *display[2];
644 static unsigned int current_view;
646 #define foreach_view(view, i) \
647 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
649 #define displayed_views() (display[1] != NULL ? 2 : 1)
652 * Current head and commit ID
653 * ~~~~~~~~~~~~~~~~~~~~~~~~~~
654 * The viewer keeps track of both what head and commit ID you are currently
655 * viewing. The commit ID will follow the cursor line and change everytime time
656 * you highlight a different commit. Whenever you reopen the diff view it
657 * will be reloaded, if the commit ID changed.
659 * The head ID is used when opening the main and log view to indicate from
660 * what revision to show history.
663 static char ref_commit[SIZEOF_REF] = "HEAD";
664 static char ref_head[SIZEOF_REF] = "HEAD";
668 const char *name; /* View name */
669 const char *cmd_fmt; /* Default command line format */
670 const char *cmd_env; /* Command line set via environment */
671 const char *id; /* Points to either of ref_{head,commit} */
674 /* What type of content being displayed. Used in the
677 /* Draw one line; @lineno must be < view->height. */
678 bool (*draw)(struct view *view, unsigned int lineno);
679 /* Read one line; updates view->line. */
680 bool (*read)(struct view *view, char *line);
681 /* Depending on view, change display based on current line. */
682 bool (*enter)(struct view *view);
685 char cmd[SIZEOF_CMD]; /* Command buffer */
686 char ref[SIZEOF_REF]; /* Hovered commit reference */
687 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
689 int height, width; /* The width and height of the main window */
690 WINDOW *win; /* The main window */
691 WINDOW *title; /* The title window living below the main window */
694 unsigned long offset; /* Offset of the window top */
695 unsigned long lineno; /* Current line number */
697 /* If non-NULL, points to the view that opened this view. If this view
698 * is closed tig will switch back to the parent view. */
702 unsigned long lines; /* Total number of lines */
703 void **line; /* Line index; each line contains user data */
704 unsigned int digits; /* Number of digits in the lines member. */
711 static struct view_ops pager_ops;
712 static struct view_ops main_ops;
714 #define VIEW_STR(name, cmd, env, ref, ops) \
715 { name, cmd, #env, ref, ops }
717 #define VIEW_(id, name, ops, ref) \
718 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, ops)
723 * tig(1) presents various 'views' of a repository. Each view is based on output
724 * from an external command, most often 'git log', 'git diff', or 'git show'.
727 * Is the default view, and it shows a one line summary of each commit
728 * in the chosen list of revisions. The summary includes commit date,
729 * author, and the first line of the log message. Additionally, any
730 * repository references, such as tags, will be shown.
733 * Presents a more rich view of the revision log showing the whole log
734 * message and the diffstat.
737 * Shows either the diff of the current working tree, that is, what
738 * has changed since the last commit, or the commit diff complete
739 * with log message, diffstat and diff.
742 * Is used for displaying both input from stdin and output from git
743 * commands entered in the internal prompt.
746 * Displays the information from the tig(1) man page. For the help view
747 * to work you need to have the tig(1) man page installed.
750 static struct view views[] = {
751 VIEW_(MAIN, "main", &main_ops, ref_head),
752 VIEW_(DIFF, "diff", &pager_ops, ref_commit),
753 VIEW_(LOG, "log", &pager_ops, ref_head),
754 VIEW_(HELP, "help", &pager_ops, "static"),
755 VIEW_(PAGER, "pager", &pager_ops, "static"),
758 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
762 redraw_view_from(struct view *view, int lineno)
764 assert(0 <= lineno && lineno < view->height);
766 for (; lineno < view->height; lineno++) {
767 if (!view->ops->draw(view, lineno))
771 redrawwin(view->win);
776 redraw_view(struct view *view)
779 redraw_view_from(view, 0);
786 * Each view has a title window which shows the name of the view, current
787 * commit ID if available, and where the view is positioned:
789 * [main] c622eefaa485995320bc743431bae0d497b1d875 - commit 1 of 61 (1%)
791 * By default, the title of the current view is highlighted using bold font.
795 update_view_title(struct view *view)
797 if (view == display[current_view])
798 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
800 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
803 wmove(view->title, 0, 0);
806 wprintw(view->title, "[%s] %s", view->name, view->ref);
808 wprintw(view->title, "[%s]", view->name);
811 wprintw(view->title, " - %s %d of %d (%d%%)",
815 (view->lineno + 1) * 100 / view->lines);
818 wrefresh(view->title);
825 struct view *base = display[0];
826 struct view *view = display[1] ? display[1] : display[0];
828 /* Setup window dimensions */
830 getmaxyx(stdscr, base->height, base->width);
832 /* Make room for the status window. */
836 /* Horizontal split. */
837 view->width = base->width;
838 view->height = SCALE_SPLIT_VIEW(base->height);
839 base->height -= view->height;
841 /* Make room for the title bar. */
845 /* Make room for the title bar. */
850 foreach_view (view, i) {
851 /* Keep the height of all view->win windows one larger than is
852 * required so that the cursor can wrap-around on the last line
853 * without scrolling the window. */
855 view->win = newwin(view->height + 1, 0, offset, 0);
857 die("Failed to create %s view", view->name);
859 scrollok(view->win, TRUE);
861 view->title = newwin(1, 0, offset + view->height, 0);
863 die("Failed to create title window");
866 wresize(view->win, view->height + 1, view->width);
867 mvwin(view->win, offset, 0);
868 mvwin(view->title, offset + view->height, 0);
872 offset += view->height + 1;
882 foreach_view (view, i) {
884 update_view_title(view);
893 /* Scrolling backend */
895 do_scroll_view(struct view *view, int lines, bool redraw)
897 /* The rendering expects the new offset. */
898 view->offset += lines;
900 assert(0 <= view->offset && view->offset < view->lines);
903 /* Redraw the whole screen if scrolling is pointless. */
904 if (view->height < ABS(lines)) {
908 int line = lines > 0 ? view->height - lines : 0;
909 int end = line + ABS(lines);
911 wscrl(view->win, lines);
913 for (; line < end; line++) {
914 if (!view->ops->draw(view, line))
919 /* Move current line into the view. */
920 if (view->lineno < view->offset) {
921 view->lineno = view->offset;
922 view->ops->draw(view, 0);
924 } else if (view->lineno >= view->offset + view->height) {
925 if (view->lineno == view->offset + view->height) {
926 /* Clear the hidden line so it doesn't show if the view
928 wmove(view->win, view->height, 0);
929 wclrtoeol(view->win);
931 view->lineno = view->offset + view->height - 1;
932 view->ops->draw(view, view->lineno - view->offset);
935 assert(view->offset <= view->lineno && view->lineno < view->lines);
940 redrawwin(view->win);
945 /* Scroll frontend */
947 scroll_view(struct view *view, enum request request)
952 case REQ_SCROLL_PAGE_DOWN:
953 lines = view->height;
954 case REQ_SCROLL_LINE_DOWN:
955 if (view->offset + lines > view->lines)
956 lines = view->lines - view->offset;
958 if (lines == 0 || view->offset + view->height >= view->lines) {
959 report("Cannot scroll beyond the last line");
964 case REQ_SCROLL_PAGE_UP:
965 lines = view->height;
966 case REQ_SCROLL_LINE_UP:
967 if (lines > view->offset)
968 lines = view->offset;
971 report("Cannot scroll beyond the first line");
979 die("request %d not handled in switch", request);
982 do_scroll_view(view, lines, TRUE);
987 move_view(struct view *view, enum request request, bool redraw)
992 case REQ_MOVE_FIRST_LINE:
993 steps = -view->lineno;
996 case REQ_MOVE_LAST_LINE:
997 steps = view->lines - view->lineno - 1;
1000 case REQ_MOVE_PAGE_UP:
1001 steps = view->height > view->lineno
1002 ? -view->lineno : -view->height;
1005 case REQ_MOVE_PAGE_DOWN:
1006 steps = view->lineno + view->height >= view->lines
1007 ? view->lines - view->lineno - 1 : view->height;
1019 die("request %d not handled in switch", request);
1022 if (steps <= 0 && view->lineno == 0) {
1023 report("Cannot move beyond the first line");
1026 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
1027 report("Cannot move beyond the last line");
1031 /* Move the current line */
1032 view->lineno += steps;
1033 assert(0 <= view->lineno && view->lineno < view->lines);
1035 /* Repaint the old "current" line if we be scrolling */
1036 if (ABS(steps) < view->height) {
1037 int prev_lineno = view->lineno - steps - view->offset;
1039 wmove(view->win, prev_lineno, 0);
1040 wclrtoeol(view->win);
1041 view->ops->draw(view, prev_lineno);
1044 /* Check whether the view needs to be scrolled */
1045 if (view->lineno < view->offset ||
1046 view->lineno >= view->offset + view->height) {
1047 if (steps < 0 && -steps > view->offset) {
1048 steps = -view->offset;
1050 } else if (steps > 0) {
1051 if (view->lineno == view->lines - 1 &&
1052 view->lines > view->height) {
1053 steps = view->lines - view->offset - 1;
1054 if (steps >= view->height)
1055 steps -= view->height - 1;
1059 do_scroll_view(view, steps, redraw);
1063 /* Draw the current line */
1064 view->ops->draw(view, view->lineno - view->offset);
1069 redrawwin(view->win);
1070 wrefresh(view->win);
1076 * Incremental updating
1080 end_update(struct view *view)
1084 set_nonblocking_input(FALSE);
1085 if (view->pipe == stdin)
1093 begin_update(struct view *view)
1095 const char *id = view->id;
1101 string_copy(view->cmd, opt_cmd);
1103 /* When running random commands, the view ref could have become
1104 * invalid so clear it. */
1107 const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1109 if (snprintf(view->cmd, sizeof(view->cmd), format,
1110 id, id, id, id, id) >= sizeof(view->cmd))
1114 /* Special case for the pager view. */
1116 view->pipe = opt_pipe;
1119 view->pipe = popen(view->cmd, "r");
1125 set_nonblocking_input(TRUE);
1130 string_copy(view->vid, id);
1135 for (i = 0; i < view->lines; i++)
1137 free(view->line[i]);
1143 view->start_time = time(NULL);
1149 update_view(struct view *view)
1151 char buffer[BUFSIZ];
1154 /* The number of lines to read. If too low it will cause too much
1155 * redrawing (and possible flickering), if too high responsiveness
1157 unsigned long lines = view->height;
1158 int redraw_from = -1;
1163 /* Only redraw if lines are visible. */
1164 if (view->offset + view->height >= view->lines)
1165 redraw_from = view->lines - view->offset;
1167 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1173 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1174 int linelen = strlen(line);
1177 line[linelen - 1] = 0;
1179 if (!view->ops->read(view, line))
1189 lines = view->lines;
1190 for (digits = 0; lines; digits++)
1193 /* Keep the displayed view in sync with line number scaling. */
1194 if (digits != view->digits) {
1195 view->digits = digits;
1200 if (redraw_from >= 0) {
1201 /* If this is an incremental update, redraw the previous line
1202 * since for commits some members could have changed when
1203 * loading the main view. */
1204 if (redraw_from > 0)
1207 /* Incrementally draw avoids flickering. */
1208 redraw_view_from(view, redraw_from);
1211 /* Update the title _after_ the redraw so that if the redraw picks up a
1212 * commit reference in view->ref it'll be available here. */
1213 update_view_title(view);
1215 if (ferror(view->pipe)) {
1216 report("Failed to read: %s", strerror(errno));
1219 } else if (feof(view->pipe)) {
1220 time_t secs = time(NULL) - view->start_time;
1222 if (view == VIEW(REQ_VIEW_HELP)) {
1223 const char *msg = TIG_HELP;
1225 if (view->lines == 0) {
1226 /* Slightly ugly, but abusing view->ref keeps
1227 * the error message. */
1228 string_copy(view->ref, "No help available");
1229 msg = "The tig(1) manpage is not installed";
1236 report("Loaded %d lines in %ld second%s", view->lines, secs,
1237 secs == 1 ? "" : "s");
1244 report("Allocation failure");
1252 OPEN_DEFAULT = 0, /* Use default view switching. */
1253 OPEN_SPLIT = 1, /* Split current view. */
1254 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1255 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1259 open_view(struct view *prev, enum request request, enum open_flags flags)
1261 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1262 bool split = !!(flags & OPEN_SPLIT);
1263 bool reload = !!(flags & OPEN_RELOAD);
1264 struct view *view = VIEW(request);
1265 int nviews = displayed_views();
1266 struct view *base_view = display[0];
1268 if (view == prev && nviews == 1 && !reload) {
1269 report("Already in %s view", view->name);
1273 if ((reload || strcmp(view->vid, view->id)) &&
1274 !begin_update(view)) {
1275 report("Failed to load %s view", view->name);
1280 display[current_view + 1] = view;
1284 /* Maximize the current view. */
1285 memset(display, 0, sizeof(display));
1287 display[current_view] = view;
1290 /* Resize the view when switching between split- and full-screen,
1291 * or when switching between two different full-screen views. */
1292 if (nviews != displayed_views() ||
1293 (nviews == 1 && base_view != display[0]))
1296 if (split && prev->lineno - prev->offset >= prev->height) {
1297 /* Take the title line into account. */
1298 int lines = prev->lineno - prev->offset - prev->height + 1;
1300 /* Scroll the view that was split if the current line is
1301 * outside the new limited view. */
1302 do_scroll_view(prev, lines, TRUE);
1305 if (prev && view != prev) {
1306 /* Continue loading split views in the background. */
1309 else if (!backgrounded)
1310 /* "Blur" the previous view. */
1311 update_view_title(prev);
1313 view->parent = prev;
1317 /* Clear the old view and let the incremental updating refill
1320 report("Loading...");
1323 if (view == VIEW(REQ_VIEW_HELP))
1324 report("%s", TIG_HELP);
1329 /* If the view is backgrounded the above calls to report()
1330 * won't redraw the view title. */
1332 update_view_title(view);
1337 * User request switch noodle
1341 view_driver(struct view *view, enum request request)
1348 case REQ_MOVE_PAGE_UP:
1349 case REQ_MOVE_PAGE_DOWN:
1350 case REQ_MOVE_FIRST_LINE:
1351 case REQ_MOVE_LAST_LINE:
1352 move_view(view, request, TRUE);
1355 case REQ_SCROLL_LINE_DOWN:
1356 case REQ_SCROLL_LINE_UP:
1357 case REQ_SCROLL_PAGE_DOWN:
1358 case REQ_SCROLL_PAGE_UP:
1359 scroll_view(view, request);
1366 case REQ_VIEW_PAGER:
1367 open_view(view, request, OPEN_DEFAULT);
1372 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
1374 if (view == VIEW(REQ_VIEW_DIFF) &&
1375 view->parent == VIEW(REQ_VIEW_MAIN)) {
1376 bool redraw = display[1] == view;
1378 view = view->parent;
1379 move_view(view, request, redraw);
1381 update_view_title(view);
1383 move_view(view, request, TRUE);
1390 report("Nothing to enter");
1393 return view->ops->enter(view);
1397 int nviews = displayed_views();
1398 int next_view = (current_view + 1) % nviews;
1400 if (next_view == current_view) {
1401 report("Only one view is displayed");
1405 current_view = next_view;
1406 /* Blur out the title of the previous view. */
1407 update_view_title(view);
1411 case REQ_TOGGLE_LINE_NUMBERS:
1412 opt_line_number = !opt_line_number;
1417 /* Always reload^Wrerun commands from the prompt. */
1418 open_view(view, opt_request, OPEN_RELOAD);
1421 case REQ_STOP_LOADING:
1422 foreach_view (view, i) {
1424 report("Stopped loaded the %s view", view->name),
1429 case REQ_SHOW_VERSION:
1430 report("%s (built %s)", VERSION, __DATE__);
1433 case REQ_SCREEN_RESIZE:
1436 case REQ_SCREEN_REDRAW:
1440 case REQ_SCREEN_UPDATE:
1444 case REQ_VIEW_CLOSE:
1446 memset(display, 0, sizeof(display));
1448 display[current_view] = view->parent;
1449 view->parent = NULL;
1459 /* An unknown key will show most commonly used commands. */
1460 report("Unknown key, press 'h' for help");
1473 pager_draw(struct view *view, unsigned int lineno)
1475 enum line_type type;
1480 if (view->offset + lineno >= view->lines)
1483 line = view->line[view->offset + lineno];
1484 type = get_line_type(line);
1486 wmove(view->win, lineno, 0);
1488 if (view->offset + lineno == view->lineno) {
1489 if (type == LINE_COMMIT) {
1490 string_copy(view->ref, line + 7);
1491 string_copy(ref_commit, view->ref);
1495 wchgat(view->win, -1, 0, type, NULL);
1498 attr = get_line_attr(type);
1499 wattrset(view->win, attr);
1501 linelen = strlen(line);
1503 if (opt_line_number || opt_tab_size < TABSIZE) {
1504 static char spaces[] = " ";
1505 int col_offset = 0, col = 0;
1507 if (opt_line_number) {
1508 unsigned long real_lineno = view->offset + lineno + 1;
1510 if (real_lineno == 1 ||
1511 (real_lineno % opt_num_interval) == 0) {
1512 wprintw(view->win, "%.*d", view->digits, real_lineno);
1515 waddnstr(view->win, spaces,
1516 MIN(view->digits, STRING_SIZE(spaces)));
1518 waddstr(view->win, ": ");
1519 col_offset = view->digits + 2;
1522 while (line && col_offset + col < view->width) {
1523 int cols_max = view->width - col_offset - col;
1527 if (*line == '\t') {
1528 assert(sizeof(spaces) > TABSIZE);
1531 cols = opt_tab_size - (col % opt_tab_size);
1534 line = strchr(line, '\t');
1535 cols = line ? line - text : strlen(text);
1538 waddnstr(view->win, text, MIN(cols, cols_max));
1543 int col = 0, pos = 0;
1545 for (; pos < linelen && col < view->width; pos++, col++)
1546 if (line[pos] == '\t')
1547 col += TABSIZE - (col % TABSIZE) - 1;
1549 waddnstr(view->win, line, pos);
1556 pager_read(struct view *view, char *line)
1558 /* Compress empty lines in the help view. */
1559 if (view == VIEW(REQ_VIEW_HELP) &&
1562 !*((char *) view->line[view->lines - 1]))
1565 view->line[view->lines] = strdup(line);
1566 if (!view->line[view->lines])
1574 pager_enter(struct view *view)
1576 char *line = view->line[view->lineno];
1579 if ((view == VIEW(REQ_VIEW_LOG) ||
1580 view == VIEW(REQ_VIEW_PAGER)) &&
1581 get_line_type(line) == LINE_COMMIT) {
1582 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
1586 /* Always scroll the view even if it was split. That way
1587 * you can use Enter to scroll through the log view and
1588 * split open each commit diff. */
1589 scroll_view(view, REQ_SCROLL_LINE_DOWN);
1591 /* FIXME: A minor workaround. Scrolling the view will call report("")
1592 * but if we are scolling a non-current view this won't properly update
1593 * the view title. */
1595 update_view_title(view);
1600 static struct view_ops pager_ops = {
1613 char id[41]; /* SHA1 ID. */
1614 char title[75]; /* The first line of the commit message. */
1615 char author[75]; /* The author of the commit. */
1616 struct tm time; /* Date from the author ident. */
1617 struct ref **refs; /* Repository references; tags & branch heads. */
1621 main_draw(struct view *view, unsigned int lineno)
1623 char buf[DATE_COLS + 1];
1624 struct commit *commit;
1625 enum line_type type;
1631 if (view->offset + lineno >= view->lines)
1634 commit = view->line[view->offset + lineno];
1635 if (!*commit->author)
1638 wmove(view->win, lineno, col);
1640 if (view->offset + lineno == view->lineno) {
1641 string_copy(view->ref, commit->id);
1642 string_copy(ref_commit, view->ref);
1644 wattrset(view->win, get_line_attr(type));
1645 wchgat(view->win, -1, 0, type, NULL);
1648 type = LINE_MAIN_COMMIT;
1649 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1652 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1653 waddnstr(view->win, buf, timelen);
1654 waddstr(view->win, " ");
1657 wmove(view->win, lineno, col);
1658 if (type != LINE_CURSOR)
1659 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1661 /* FIXME: Make this optional, and add i18n.commitEncoding support. */
1662 authorlen = utf8_length(commit->author, AUTHOR_COLS - 2, &col, &trimmed);
1665 waddnstr(view->win, commit->author, authorlen);
1666 if (type != LINE_CURSOR)
1667 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1668 waddch(view->win, '~');
1670 waddstr(view->win, commit->author);
1674 if (type != LINE_CURSOR)
1675 wattrset(view->win, A_NORMAL);
1677 mvwaddch(view->win, lineno, col, ACS_LTEE);
1678 wmove(view->win, lineno, col + 2);
1685 if (type == LINE_CURSOR)
1687 else if (commit->refs[i]->tag)
1688 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1690 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1691 waddstr(view->win, "[");
1692 waddstr(view->win, commit->refs[i]->name);
1693 waddstr(view->win, "]");
1694 if (type != LINE_CURSOR)
1695 wattrset(view->win, A_NORMAL);
1696 waddstr(view->win, " ");
1697 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
1698 } while (commit->refs[i++]->next);
1701 if (type != LINE_CURSOR)
1702 wattrset(view->win, get_line_attr(type));
1705 int titlelen = strlen(commit->title);
1707 if (col + titlelen > view->width)
1708 titlelen = view->width - col;
1710 waddnstr(view->win, commit->title, titlelen);
1716 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1718 main_read(struct view *view, char *line)
1720 enum line_type type = get_line_type(line);
1721 struct commit *commit;
1725 commit = calloc(1, sizeof(struct commit));
1729 line += STRING_SIZE("commit ");
1731 view->line[view->lines++] = commit;
1732 string_copy(commit->id, line);
1733 commit->refs = get_refs(commit->id);
1738 char *ident = line + STRING_SIZE("author ");
1739 char *end = strchr(ident, '<');
1742 for (; end > ident && isspace(end[-1]); end--) ;
1746 commit = view->line[view->lines - 1];
1747 string_copy(commit->author, ident);
1749 /* Parse epoch and timezone */
1751 char *secs = strchr(end + 1, '>');
1755 if (!secs || secs[1] != ' ')
1759 time = (time_t) atol(secs);
1760 zone = strchr(secs, ' ');
1761 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1765 tz = ('0' - zone[1]) * 60 * 60 * 10;
1766 tz += ('0' - zone[2]) * 60 * 60;
1767 tz += ('0' - zone[3]) * 60;
1768 tz += ('0' - zone[4]) * 60;
1775 gmtime_r(&time, &commit->time);
1780 /* We should only ever end up here if there has already been a
1781 * commit line, however, be safe. */
1782 if (view->lines == 0)
1785 /* Fill in the commit title if it has not already been set. */
1786 commit = view->line[view->lines - 1];
1787 if (commit->title[0])
1790 /* Require titles to start with a non-space character at the
1791 * offset used by git log. */
1792 /* FIXME: More gracefull handling of titles; append "..." to
1793 * shortened titles, etc. */
1794 if (strncmp(line, " ", 4) ||
1798 string_copy(commit->title, line + 4);
1805 main_enter(struct view *view)
1807 enum open_flags flags = display[0] == view ? OPEN_SPLIT : OPEN_DEFAULT;
1809 open_view(view, REQ_VIEW_DIFF, flags);
1813 static struct view_ops main_ops = {
1824 * Below the default key bindings are shown.
1832 static struct keymap keymap[] = {
1837 * Switch to main view.
1839 * Switch to diff view.
1841 * Switch to log view.
1843 * Switch to pager view.
1847 { 'm', REQ_VIEW_MAIN },
1848 { 'd', REQ_VIEW_DIFF },
1849 { 'l', REQ_VIEW_LOG },
1850 { 'p', REQ_VIEW_PAGER },
1851 { 'h', REQ_VIEW_HELP },
1857 * Close view, if multiple views are open it will jump back to the
1858 * previous view in the view stack. If it is the last open view it
1859 * will quit. Use 'Q' to quit all views at once.
1861 * This key is "context sensitive" depending on what view you are
1862 * currently in. When in log view on a commit line or in the main
1863 * view, split the view and show the commit diff. In the diff view
1864 * pressing Enter will simply scroll the view one line down.
1866 * Switch to next view.
1868 * This key is "context sensitive" and will move the cursor one
1869 * line up. However, uf you opened a diff view from the main view
1870 * (split- or full-screen) it will change the cursor to point to
1871 * the previous commit in the main view and update the diff view
1874 * Similar to 'Up' but will move down.
1876 { 'q', REQ_VIEW_CLOSE },
1877 { KEY_TAB, REQ_VIEW_NEXT },
1878 { KEY_RETURN, REQ_ENTER },
1879 { KEY_UP, REQ_PREVIOUS },
1880 { KEY_DOWN, REQ_NEXT },
1886 * Move cursor one line up.
1888 * Move cursor one line down.
1892 * Move cursor one page up.
1895 * Move cursor one page down.
1897 * Jump to first line.
1899 * Jump to last line.
1901 { 'k', REQ_MOVE_UP },
1902 { 'j', REQ_MOVE_DOWN },
1903 { KEY_HOME, REQ_MOVE_FIRST_LINE },
1904 { KEY_END, REQ_MOVE_LAST_LINE },
1905 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
1906 { ' ', REQ_MOVE_PAGE_DOWN },
1907 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
1908 { 'b', REQ_MOVE_PAGE_UP },
1909 { '-', REQ_MOVE_PAGE_UP },
1915 * Scroll view one line up.
1917 * Scroll view one line down.
1919 * Scroll view one page up.
1921 * Scroll view one page down.
1923 { KEY_IC, REQ_SCROLL_LINE_UP },
1924 { KEY_DC, REQ_SCROLL_LINE_DOWN },
1925 { 'w', REQ_SCROLL_PAGE_UP },
1926 { 's', REQ_SCROLL_PAGE_DOWN },
1936 * Stop all background loading. This can be useful if you use
1937 * tig(1) in a repository with a long history without limiting
1942 * Toggle line numbers on/off.
1944 * Open prompt. This allows you to specify what git command
1950 { 'z', REQ_STOP_LOADING },
1951 { 'v', REQ_SHOW_VERSION },
1952 { 'r', REQ_SCREEN_REDRAW },
1953 { 'n', REQ_TOGGLE_LINE_NUMBERS },
1954 { ':', REQ_PROMPT },
1956 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
1957 { ERR, REQ_SCREEN_UPDATE },
1959 /* Use the ncurses SIGWINCH handler. */
1960 { KEY_RESIZE, REQ_SCREEN_RESIZE },
1964 get_request(int key)
1968 for (i = 0; i < ARRAY_SIZE(keymap); i++)
1969 if (keymap[i].alias == key)
1970 return keymap[i].request;
1972 return (enum request) key;
1977 * Unicode / UTF-8 handling
1979 * NOTE: Much of the following code for dealing with unicode is derived from
1980 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
1981 * src/intl/charset.c from the utf8 branch commit elinks-0.11.0-g31f2c28.
1984 /* I've (over)annotated a lot of code snippets because I am not entirely
1985 * confident that the approach taken by this small UTF-8 interface is correct.
1989 unicode_width(unsigned long c)
1992 (c <= 0x115f /* Hangul Jamo */
1995 || (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f)
1997 || (c >= 0xac00 && c <= 0xd7a3) /* Hangul Syllables */
1998 || (c >= 0xf900 && c <= 0xfaff) /* CJK Compatibility Ideographs */
1999 || (c >= 0xfe30 && c <= 0xfe6f) /* CJK Compatibility Forms */
2000 || (c >= 0xff00 && c <= 0xff60) /* Fullwidth Forms */
2001 || (c >= 0xffe0 && c <= 0xffe6)
2002 || (c >= 0x20000 && c <= 0x2fffd)
2003 || (c >= 0x30000 && c <= 0x3fffd)))
2009 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
2010 * Illegal bytes are set one. */
2011 static const unsigned char utf8_bytes[256] = {
2012 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,
2013 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,
2014 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,
2015 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,
2016 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,
2017 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,
2018 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,
2019 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,
2022 /* Decode UTF-8 multi-byte representation into a unicode character. */
2023 static inline unsigned long
2024 utf8_to_unicode(const char *string, size_t length)
2026 unsigned long unicode;
2030 unicode = string[0];
2033 unicode = (string[0] & 0x1f) << 6;
2034 unicode += (string[1] & 0x3f);
2037 unicode = (string[0] & 0x0f) << 12;
2038 unicode += ((string[1] & 0x3f) << 6);
2039 unicode += (string[2] & 0x3f);
2042 unicode = (string[0] & 0x0f) << 18;
2043 unicode += ((string[1] & 0x3f) << 12);
2044 unicode += ((string[2] & 0x3f) << 6);
2045 unicode += (string[3] & 0x3f);
2048 unicode = (string[0] & 0x0f) << 24;
2049 unicode += ((string[1] & 0x3f) << 18);
2050 unicode += ((string[2] & 0x3f) << 12);
2051 unicode += ((string[3] & 0x3f) << 6);
2052 unicode += (string[4] & 0x3f);
2055 unicode = (string[0] & 0x01) << 30;
2056 unicode += ((string[1] & 0x3f) << 24);
2057 unicode += ((string[2] & 0x3f) << 18);
2058 unicode += ((string[3] & 0x3f) << 12);
2059 unicode += ((string[4] & 0x3f) << 6);
2060 unicode += (string[5] & 0x3f);
2063 die("Invalid unicode length");
2066 /* Invalid characters could return the special 0xfffd value but NUL
2067 * should be just as good. */
2068 return unicode > 0xffff ? 0 : unicode;
2071 /* Calculates how much of string can be shown within the given maximum width
2072 * and sets trimmed parameter to non-zero value if all of string could not be
2075 * Additionally, adds to coloffset how many many columns to move to align with
2076 * the expected position. Takes into account how multi-byte and double-width
2077 * characters will effect the cursor position.
2079 * Returns the number of bytes to output from string to satisfy max_width. */
2081 utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed)
2083 const char *start = string;
2084 const char *end = strchr(string, '\0');
2090 while (string < end) {
2091 int c = *(unsigned char *) string;
2092 unsigned char bytes = utf8_bytes[c];
2094 unsigned long unicode;
2096 if (string + bytes > end)
2099 /* Change representation to figure out whether
2100 * it is a single- or double-width character. */
2102 unicode = utf8_to_unicode(string, bytes);
2103 /* FIXME: Graceful handling of invalid unicode character. */
2107 ucwidth = unicode_width(unicode);
2109 if (width > max_width) {
2114 /* The column offset collects the differences between the
2115 * number of bytes encoding a character and the number of
2116 * columns will be used for rendering said character.
2118 * So if some character A is encoded in 2 bytes, but will be
2119 * represented on the screen using only 1 byte this will and up
2120 * adding 1 to the multi-byte column offset.
2122 * Assumes that no double-width character can be encoding in
2123 * less than two bytes. */
2124 if (bytes > ucwidth)
2125 mbwidth += bytes - ucwidth;
2130 *coloffset += mbwidth;
2132 return string - start;
2140 /* Whether or not the curses interface has been initialized. */
2141 static bool cursed = FALSE;
2143 /* The status window is used for polling keystrokes. */
2144 static WINDOW *status_win;
2146 /* Update status and title window. */
2148 report(const char *msg, ...)
2150 static bool empty = TRUE;
2151 struct view *view = display[current_view];
2153 if (!empty || *msg) {
2156 va_start(args, msg);
2159 wmove(status_win, 0, 0);
2161 vwprintw(status_win, msg, args);
2166 wrefresh(status_win);
2171 update_view_title(view);
2173 /* Move the cursor to the right-most column of the cursor line.
2175 * XXX: This could turn out to be a bit expensive, but it ensures that
2176 * the cursor does not jump around. */
2178 wmove(view->win, view->lineno - view->offset, view->width - 1);
2179 wrefresh(view->win);
2183 /* Controls when nodelay should be in effect when polling user input. */
2185 set_nonblocking_input(bool loading)
2187 static unsigned int loading_views;
2189 if ((loading == FALSE && loading_views-- == 1) ||
2190 (loading == TRUE && loading_views++ == 0))
2191 nodelay(status_win, loading);
2199 /* Initialize the curses library */
2200 if (isatty(STDIN_FILENO)) {
2201 cursed = !!initscr();
2203 /* Leave stdin and stdout alone when acting as a pager. */
2204 FILE *io = fopen("/dev/tty", "r+");
2206 cursed = !!newterm(NULL, io, io);
2210 die("Failed to initialize curses");
2212 nonl(); /* Tell curses not to do NL->CR/NL on output */
2213 cbreak(); /* Take input chars one at a time, no wait for \n */
2214 noecho(); /* Don't echo input */
2215 leaveok(stdscr, TRUE);
2220 getmaxyx(stdscr, y, x);
2221 status_win = newwin(1, 0, y - 1, 0);
2223 die("Failed to create status window");
2225 /* Enable keyboard mapping */
2226 keypad(status_win, TRUE);
2227 wbkgdset(status_win, get_line_attr(LINE_STATUS));
2232 * Repository references
2235 static struct ref *refs;
2236 static size_t refs_size;
2238 /* Id <-> ref store */
2239 static struct ref ***id_refs;
2240 static size_t id_refs_size;
2242 static struct ref **
2245 struct ref ***tmp_id_refs;
2246 struct ref **ref_list = NULL;
2247 size_t ref_list_size = 0;
2250 for (i = 0; i < id_refs_size; i++)
2251 if (!strcmp(id, id_refs[i][0]->id))
2254 tmp_id_refs = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
2258 id_refs = tmp_id_refs;
2260 for (i = 0; i < refs_size; i++) {
2263 if (strcmp(id, refs[i].id))
2266 tmp = realloc(ref_list, (ref_list_size + 1) * sizeof(*ref_list));
2274 if (ref_list_size > 0)
2275 ref_list[ref_list_size - 1]->next = 1;
2276 ref_list[ref_list_size] = &refs[i];
2278 /* XXX: The properties of the commit chains ensures that we can
2279 * safely modify the shared ref. The repo references will
2280 * always be similar for the same id. */
2281 ref_list[ref_list_size]->next = 0;
2286 id_refs[id_refs_size++] = ref_list;
2294 const char *cmd_env = getenv("TIG_LS_REMOTE");
2295 const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
2296 FILE *pipe = popen(cmd, "r");
2297 char buffer[BUFSIZ];
2303 while ((line = fgets(buffer, sizeof(buffer), pipe))) {
2304 char *name = strchr(line, '\t');
2308 bool tag_commit = FALSE;
2314 namelen = strlen(name) - 1;
2316 /* Commits referenced by tags has "^{}" appended. */
2317 if (name[namelen - 1] == '}') {
2318 while (namelen > 0 && name[namelen] != '^')
2325 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
2328 name += STRING_SIZE("refs/tags/");
2331 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
2332 name += STRING_SIZE("refs/heads/");
2334 } else if (!strcmp(name, "HEAD")) {
2338 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2342 ref = &refs[refs_size++];
2344 ref->name = strdup(name);
2348 string_copy(ref->id, line);
2364 #define __NORETURN __attribute__((__noreturn__))
2369 static void __NORETURN
2372 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2378 static void __NORETURN
2379 die(const char *err, ...)
2385 va_start(args, err);
2386 fputs("tig: ", stderr);
2387 vfprintf(stderr, err, args);
2388 fputs("\n", stderr);
2395 main(int argc, char *argv[])
2398 enum request request;
2401 signal(SIGINT, quit);
2403 if (!parse_options(argc, argv))
2406 if (load_refs() == ERR)
2407 die("Failed to load refs.");
2409 /* Require a git repository unless when running in pager mode. */
2410 if (refs_size == 0 && opt_request != REQ_VIEW_PAGER)
2411 die("Not a git repository");
2413 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2414 view->cmd_env = getenv(view->cmd_env);
2416 request = opt_request;
2420 while (view_driver(display[current_view], request)) {
2424 foreach_view (view, i)
2427 /* Refresh, accept single keystroke of input */
2428 key = wgetch(status_win);
2429 request = get_request(key);
2431 /* Some low-level request handling. This keeps access to
2432 * status_win restricted. */
2436 /* Temporarily switch to line-oriented and echoed
2441 if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
2442 memcpy(opt_cmd, "git ", 4);
2443 opt_request = REQ_VIEW_PAGER;
2452 case REQ_SCREEN_RESIZE:
2456 getmaxyx(stdscr, height, width);
2458 /* Resize the status view and let the view driver take
2459 * care of resizing the displayed views. */
2460 wresize(status_win, 1, width);
2461 mvwin(status_win, height - 1, 0);
2462 wrefresh(status_win);
2477 * Revision specification
2478 * ----------------------
2479 * This section describes various ways to specify what revisions to display
2480 * or otherwise limit the view to. tig(1) does not itself parse the described
2481 * revision options so refer to the relevant git man pages for futher
2482 * information. Relevant man pages besides git-log(1) are git-diff(1) and
2485 * You can tune the interaction with git by making use of the options
2486 * explained in this section. For example, by configuring the environment
2487 * variables described in the <<view-commands, "View commands">> section.
2489 * Limit by path name
2490 * ~~~~~~~~~~~~~~~~~~
2491 * If you are interested only in those revisions that made changes to a
2492 * specific file (or even several files) list the files like this:
2494 * $ tig log Makefile README
2496 * To avoid ambiguity with repository references such as tag name, be sure
2497 * to separate file names from other git options using "\--". So if you
2498 * have a file named 'master' it will clash with the reference named
2499 * 'master', and thus you will have to use:
2501 * $ tig log -- master
2503 * NOTE: For the main view, avoiding ambiguity will in some cases require
2504 * you to specify two "\--" options. The first will make tig(1) stop
2505 * option processing and the latter will be passed to git log.
2507 * Limit by date or number
2508 * ~~~~~~~~~~~~~~~~~~~~~~~
2509 * To speed up interaction with git, you can limit the amount of commits
2510 * to show both for the log and main view. Either limit by date using
2511 * e.g. `--since=1.month` or limit by the number of commits using `-n400`.
2513 * If you are only interested in changed that happened between two dates
2516 * $ tig -- --after="May 5th" --before="2006-05-16 15:44"
2518 * NOTE: If you want to avoid having to quote dates containing spaces you
2519 * can use "." instead, e.g. `--after=May.5th`.
2521 * Limiting by commit ranges
2522 * ~~~~~~~~~~~~~~~~~~~~~~~~~
2523 * Alternatively, commits can be limited to a specific range, such as
2524 * "all commits between 'tag-1.0' and 'tag-2.0'". For example:
2526 * $ tig log tag-1.0..tag-2.0
2528 * This way of commit limiting makes it trivial to only browse the commits
2529 * which haven't been pushed to a remote branch. Assuming 'origin' is your
2530 * upstream remote branch, using:
2532 * $ tig log origin..HEAD
2534 * will list what will be pushed to the remote branch. Optionally, the ending
2535 * 'HEAD' can be left out since it is implied.
2537 * Limiting by reachability
2538 * ~~~~~~~~~~~~~~~~~~~~~~~~
2539 * Git interprets the range specifier "tag-1.0..tag-2.0" as
2540 * "all commits reachable from 'tag-2.0' but not from 'tag-1.0'".
2541 * Where reachability refers to what commits are ancestors (or part of the
2542 * history) of the branch or tagged revision in question.
2544 * If you prefer to specify which commit to preview in this way use the
2547 * $ tig log tag-2.0 ^tag-1.0
2549 * You can think of '^' as a negation operator. Using this alternate syntax,
2550 * it is possible to further prune commits by specifying multiple branch
2553 * Combining revisions specification
2554 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2555 * Revisions options can to some degree be combined, which makes it possible
2556 * to say "show at most 20 commits from within the last month that changed
2557 * files under the Documentation/ directory."
2559 * $ tig -- --since=1.month -n20 -- Documentation/
2561 * Examining all repository references
2562 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2563 * In some cases, it can be useful to query changes across all references
2564 * in a repository. An example is to ask "did any line of development in
2565 * this repository change a particular file within the last week". This
2566 * can be accomplished using:
2568 * $ tig -- --all --since=1.week -- Makefile
2572 * Known bugs and problems:
2574 * - In it's current state tig is pretty much UTF-8 only.
2576 * - If the screen width is very small the main view can draw
2577 * outside the current view causing bad wrapping. Same goes
2578 * for title and status windows.
2582 * Features that should be explored.
2590 * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
2592 * This program is free software; you can redistribute it and/or modify
2593 * it under the terms of the GNU General Public License as published by
2594 * the Free Software Foundation; either version 2 of the License, or
2595 * (at your option) any later version.
2600 * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
2601 * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
2602 * gitk(1): git repository browser written using tcl/tk,
2603 * qgit(1): git repository browser written using c++/Qt,
2604 * gitview(1): git repository browser written using python/gtk.