1 /* Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
19 * tig - text-mode interface for git
25 * tig [options] [--] [git log options]
26 * tig [options] log [git log options]
27 * tig [options] diff [git diff options]
28 * tig [options] show [git show options]
29 * tig [options] < [git command output]
33 * Browse changes in a git repository. Additionally, tig(1) can also act
34 * as a pager for output of various git commands.
36 * When browsing repositories, tig(1) uses the underlying git commands
37 * to present the user with various views, such as summarized commit log
38 * and showing the commit with the log message, diffstat, and the diff.
40 * Using tig(1) as a pager, it will display input from stdin and try
45 #define VERSION "tig-0.3"
65 static void die(const char *err, ...);
66 static void report(const char *msg, ...);
67 static int read_properties(FILE *pipe, const char *separators, int (*read)(char *, int, char *, int));
68 static void set_nonblocking_input(bool loading);
69 static size_t utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed);
71 #define ABS(x) ((x) >= 0 ? (x) : -(x))
72 #define MIN(x, y) ((x) < (y) ? (x) : (y))
74 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
75 #define STRING_SIZE(x) (sizeof(x) - 1)
77 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
78 #define SIZEOF_CMD 1024 /* Size of command buffer. */
80 /* This color name can be used to refer to the default term colors. */
81 #define COLOR_DEFAULT (-1)
83 #define TIG_HELP "(d)iff, (l)og, (m)ain, (q)uit, (h)elp"
85 /* The format and size of the date column in the main view. */
86 #define DATE_FORMAT "%Y-%m-%d %H:%M"
87 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
89 #define AUTHOR_COLS 20
91 /* The default interval between line numbers. */
92 #define NUMBER_INTERVAL 1
96 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
98 /* Some ascii-shorthands fitted into the ncurses namespace. */
100 #define KEY_RETURN '\r'
104 /* User action requests. */
106 /* Offset all requests to avoid conflicts with ncurses getch values. */
107 REQ_OFFSET = KEY_MAX + 1,
109 /* XXX: Keep the view request first and in sync with views[]. */
124 REQ_TOGGLE_LINE_NUMBERS,
138 REQ_SCROLL_LINE_DOWN,
140 REQ_SCROLL_PAGE_DOWN,
144 char *name; /* Ref name; tag or head names are shortened. */
145 char id[41]; /* Commit SHA1 ID */
146 unsigned int tag:1; /* Is it a tag? */
147 unsigned int next:1; /* For ref lists: are there more refs? */
150 static struct ref **get_refs(char *id);
159 set_from_int_map(struct int_map *map, size_t map_size,
160 int *value, const char *name, int namelen)
165 for (i = 0; i < map_size; i++)
166 if (namelen == map[i].namelen &&
167 !strncasecmp(name, map[i].name, namelen)) {
168 *value = map[i].value;
181 string_ncopy(char *dst, const char *src, int dstlen)
183 strncpy(dst, src, dstlen - 1);
188 /* Shorthand for safely copying into a fixed buffer. */
189 #define string_copy(dst, src) \
190 string_ncopy(dst, src, sizeof(dst))
193 chomp_string(char *name)
197 while (isspace(*name))
200 namelen = strlen(name) - 1;
201 while (namelen > 0 && isspace(name[namelen]))
210 * NOTE: The following is a slightly modified copy of the git project's shell
211 * quoting routines found in the quote.c file.
213 * Help to copy the thing properly quoted for the shell safety. any single
214 * quote is replaced with '\'', any exclamation point is replaced with '\!',
215 * and the whole thing is enclosed in a
218 * original sq_quote result
219 * name ==> name ==> 'name'
220 * a b ==> a b ==> 'a b'
221 * a'b ==> a'\''b ==> 'a'\''b'
222 * a!b ==> a'\!'b ==> 'a'\!'b'
226 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
230 #define BUFPUT(x) do { if (bufsize < SIZEOF_CMD) buf[bufsize++] = (x); } while (0)
233 while ((c = *src++)) {
234 if (c == '\'' || c == '!') {
254 static const char usage[] =
255 VERSION " (" __DATE__ ")\n"
257 "Usage: tig [options]\n"
258 " or: tig [options] [--] [git log options]\n"
259 " or: tig [options] log [git log options]\n"
260 " or: tig [options] diff [git diff options]\n"
261 " or: tig [options] show [git show options]\n"
262 " or: tig [options] < [git command output]\n"
265 " -l Start up in log view\n"
266 " -d Start up in diff view\n"
267 " -n[I], --line-number[=I] Show line numbers with given interval\n"
268 " -b[N], --tab-size[=N] Set number of spaces for tab expansion\n"
269 " -- Mark end of tig options\n"
270 " -v, --version Show version and exit\n"
271 " -h, --help Show help message and exit\n";
273 /* Option and state variables. */
274 static bool opt_line_number = FALSE;
275 static int opt_num_interval = NUMBER_INTERVAL;
276 static int opt_tab_size = TABSIZE;
277 static enum request opt_request = REQ_VIEW_MAIN;
278 static char opt_cmd[SIZEOF_CMD] = "";
279 static char opt_encoding[20] = "";
280 static bool opt_utf8 = TRUE;
281 static FILE *opt_pipe = NULL;
283 /* Returns the index of log or diff command or -1 to exit. */
285 parse_options(int argc, char *argv[])
289 for (i = 1; i < argc; i++) {
294 * Start up in log view using the internal log command.
296 if (!strcmp(opt, "-l")) {
297 opt_request = REQ_VIEW_LOG;
303 * Start up in diff view using the internal diff command.
305 if (!strcmp(opt, "-d")) {
306 opt_request = REQ_VIEW_DIFF;
311 * -n[INTERVAL], --line-number[=INTERVAL]::
312 * Prefix line numbers in log and diff view.
313 * Optionally, with interval different than each line.
315 if (!strncmp(opt, "-n", 2) ||
316 !strncmp(opt, "--line-number", 13)) {
322 } else if (opt[STRING_SIZE("--line-number")] == '=') {
323 num = opt + STRING_SIZE("--line-number=");
327 opt_num_interval = atoi(num);
329 opt_line_number = TRUE;
334 * -b[NSPACES], --tab-size[=NSPACES]::
335 * Set the number of spaces tabs should be expanded to.
337 if (!strncmp(opt, "-b", 2) ||
338 !strncmp(opt, "--tab-size", 10)) {
344 } else if (opt[STRING_SIZE("--tab-size")] == '=') {
345 num = opt + STRING_SIZE("--tab-size=");
349 opt_tab_size = MIN(atoi(num), TABSIZE);
355 * Show version and exit.
357 if (!strcmp(opt, "-v") ||
358 !strcmp(opt, "--version")) {
359 printf("tig version %s\n", VERSION);
365 * Show help message and exit.
367 if (!strcmp(opt, "-h") ||
368 !strcmp(opt, "--help")) {
375 * End of tig(1) options. Useful when specifying command
376 * options for the main view. Example:
378 * $ tig -- --since=1.month
380 if (!strcmp(opt, "--")) {
386 * log [git log options]::
387 * Open log view using the given git log options.
389 * diff [git diff options]::
390 * Open diff view using the given git diff options.
392 * show [git show options]::
393 * Open diff view using the given git show options.
395 if (!strcmp(opt, "log") ||
396 !strcmp(opt, "diff") ||
397 !strcmp(opt, "show")) {
398 opt_request = opt[0] == 'l'
399 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
404 * [git log options]::
405 * tig(1) will stop the option parsing when the first
406 * command line parameter not starting with "-" is
407 * encountered. All options including this one will be
408 * passed to git log when loading the main view.
409 * This makes it possible to say:
411 * $ tig tag-1.0..HEAD
413 if (opt[0] && opt[0] != '-')
416 die("unknown command '%s'", opt);
419 if (!isatty(STDIN_FILENO)) {
420 opt_request = REQ_VIEW_PAGER;
423 } else if (i < argc) {
426 if (opt_request == REQ_VIEW_MAIN)
427 /* XXX: This is vulnerable to the user overriding
428 * options required for the main view parser. */
429 string_copy(opt_cmd, "git log --stat --pretty=raw");
431 string_copy(opt_cmd, "git");
432 buf_size = strlen(opt_cmd);
434 while (buf_size < sizeof(opt_cmd) && i < argc) {
435 opt_cmd[buf_size++] = ' ';
436 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
439 if (buf_size >= sizeof(opt_cmd))
440 die("command too long");
442 opt_cmd[buf_size] = 0;
446 if (*opt_encoding && strcasecmp(opt_encoding, "UTF-8"))
454 * ENVIRONMENT VARIABLES
455 * ---------------------
457 * Set command for retrieving all repository references. The command
458 * should output data in the same format as git-ls-remote(1).
461 #define TIG_LS_REMOTE \
462 "git ls-remote . 2>/dev/null"
466 * The command used for the diff view. By default, git show is used
470 * The command used for the log view. If you prefer to have both
471 * author and committer shown in the log view be sure to pass
472 * `--pretty=fuller` to git log.
475 * The command used for the main view. Note, you must always specify
476 * the option: `--pretty=raw` since the main view parser expects to
480 #define TIG_DIFF_CMD \
481 "git show --patch-with-stat --find-copies-harder -B -C %s"
483 #define TIG_LOG_CMD \
484 "git log --cc --stat -n100 %s"
486 #define TIG_MAIN_CMD \
487 "git log --topo-order --stat --pretty=raw %s"
489 /* ... silently ignore that the following are also exported. */
491 #define TIG_HELP_CMD \
492 "man tig 2>/dev/null"
494 #define TIG_PAGER_CMD \
502 * User configuration file. See tigrc(5) for examples.
505 * Repository config file. Read on startup with the help of
506 * git-repo-config(1).
509 static struct int_map color_map[] = {
510 #define COLOR_MAP(name) { #name, STRING_SIZE(#name), COLOR_##name }
522 static struct int_map attr_map[] = {
523 #define ATTR_MAP(name) { #name, STRING_SIZE(#name), A_##name }
534 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
536 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
537 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
538 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
539 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
540 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
541 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
542 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
543 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
544 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
545 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
546 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
547 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
548 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
549 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
550 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
551 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
552 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
553 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
554 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
555 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
556 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
557 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
558 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
559 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
560 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
561 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
562 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
563 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
564 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
565 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
566 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
567 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
568 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
569 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
570 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
574 * Line-oriented content detection.
578 #define LINE(type, line, fg, bg, attr) \
585 const char *name; /* Option name. */
586 int namelen; /* Size of option name. */
587 const char *line; /* The start of line to match. */
588 int linelen; /* Size of string to match. */
589 int fg, bg, attr; /* Color and text attributes for the lines. */
592 static struct line_info line_info[] = {
593 #define LINE(type, line, fg, bg, attr) \
594 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
599 static enum line_type
600 get_line_type(char *line)
602 int linelen = strlen(line);
605 for (type = 0; type < ARRAY_SIZE(line_info); type++)
606 /* Case insensitive search matches Signed-off-by lines better. */
607 if (linelen >= line_info[type].linelen &&
608 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
615 get_line_attr(enum line_type type)
617 assert(type < ARRAY_SIZE(line_info));
618 return COLOR_PAIR(type) | line_info[type].attr;
621 static struct line_info *
622 get_line_info(char *name, int namelen)
627 /* Diff-Header -> DIFF_HEADER */
628 for (i = 0; i < namelen; i++) {
631 else if (name[i] == '.')
635 for (type = 0; type < ARRAY_SIZE(line_info); type++)
636 if (namelen == line_info[type].namelen &&
637 !strncasecmp(line_info[type].name, name, namelen))
638 return &line_info[type];
646 int default_bg = COLOR_BLACK;
647 int default_fg = COLOR_WHITE;
652 if (use_default_colors() != ERR) {
657 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
658 struct line_info *info = &line_info[type];
659 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
660 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
662 init_pair(type, fg, bg);
668 void *data; /* User data */
673 * User config file handling.
676 #define set_color(color, name, namelen) \
677 set_from_int_map(color_map, ARRAY_SIZE(color_map), color, name, namelen)
679 #define set_attribute(attr, name, namelen) \
680 set_from_int_map(attr_map, ARRAY_SIZE(attr_map), attr, name, namelen)
682 static int config_lineno;
683 static bool config_errors;
684 static char *config_msg;
687 set_option(char *opt, int optlen, char *value, int valuelen)
689 /* Reads: "color" object fgcolor bgcolor [attr] */
690 if (!strcmp(opt, "color")) {
691 struct line_info *info;
693 value = chomp_string(value);
694 valuelen = strcspn(value, " \t");
695 info = get_line_info(value, valuelen);
697 config_msg = "Unknown color name";
701 value = chomp_string(value + valuelen);
702 valuelen = strcspn(value, " \t");
703 if (set_color(&info->fg, value, valuelen) == ERR) {
704 config_msg = "Unknown color";
708 value = chomp_string(value + valuelen);
709 valuelen = strcspn(value, " \t");
710 if (set_color(&info->bg, value, valuelen) == ERR) {
711 config_msg = "Unknown color";
715 value = chomp_string(value + valuelen);
717 set_attribute(&info->attr, value, strlen(value)) == ERR) {
718 config_msg = "Unknown attribute";
729 read_option(char *opt, int optlen, char *value, int valuelen)
732 config_msg = "Internal error";
734 optlen = strcspn(opt, "#;");
736 /* The whole line is a commend or empty. */
739 } else if (opt[optlen] != 0) {
740 /* Part of the option name is a comment, so the value part
741 * should be ignored. */
743 opt[optlen] = value[valuelen] = 0;
745 /* Else look for comment endings in the value. */
746 valuelen = strcspn(value, "#;");
750 if (set_option(opt, optlen, value, valuelen) == ERR) {
751 fprintf(stderr, "Error on line %d, near '%.*s' option: %s\n",
752 config_lineno, optlen, opt, config_msg);
753 config_errors = TRUE;
756 /* Always keep going if errors are encountered. */
763 char *home = getenv("HOME");
768 config_errors = FALSE;
771 snprintf(buf, sizeof(buf), "%s/.tigrc", home) >= sizeof(buf))
774 /* It's ok that the file doesn't exist. */
775 file = fopen(buf, "r");
779 if (read_properties(file, " \t", read_option) == ERR ||
780 config_errors == TRUE)
781 fprintf(stderr, "Errors while loading %s.\n", buf);
794 /* The display array of active views and the index of the current view. */
795 static struct view *display[2];
796 static unsigned int current_view;
798 #define foreach_view(view, i) \
799 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
801 #define displayed_views() (display[1] != NULL ? 2 : 1)
803 /* Current head and commit ID */
804 static char ref_commit[SIZEOF_REF] = "HEAD";
805 static char ref_head[SIZEOF_REF] = "HEAD";
808 const char *name; /* View name */
809 const char *cmd_fmt; /* Default command line format */
810 const char *cmd_env; /* Command line set via environment */
811 const char *id; /* Points to either of ref_{head,commit} */
813 struct view_ops *ops; /* View operations */
815 char cmd[SIZEOF_CMD]; /* Command buffer */
816 char ref[SIZEOF_REF]; /* Hovered commit reference */
817 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
819 int height, width; /* The width and height of the main window */
820 WINDOW *win; /* The main window */
821 WINDOW *title; /* The title window living below the main window */
824 unsigned long offset; /* Offset of the window top */
825 unsigned long lineno; /* Current line number */
827 /* If non-NULL, points to the view that opened this view. If this view
828 * is closed tig will switch back to the parent view. */
832 unsigned long lines; /* Total number of lines */
833 struct line *line; /* Line index */
834 unsigned int digits; /* Number of digits in the lines member. */
842 /* What type of content being displayed. Used in the title bar. */
844 /* Draw one line; @lineno must be < view->height. */
845 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
846 /* Read one line; updates view->line. */
847 bool (*read)(struct view *view, struct line *prev, char *data);
848 /* Depending on view, change display based on current line. */
849 bool (*enter)(struct view *view, struct line *line);
852 static struct view_ops pager_ops;
853 static struct view_ops main_ops;
855 #define VIEW_STR(name, cmd, env, ref, ops) \
856 { name, cmd, #env, ref, ops }
858 #define VIEW_(id, name, ops, ref) \
859 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, ops)
862 static struct view views[] = {
863 VIEW_(MAIN, "main", &main_ops, ref_head),
864 VIEW_(DIFF, "diff", &pager_ops, ref_commit),
865 VIEW_(LOG, "log", &pager_ops, ref_head),
866 VIEW_(HELP, "help", &pager_ops, "static"),
867 VIEW_(PAGER, "pager", &pager_ops, "static"),
870 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
874 draw_view_line(struct view *view, unsigned int lineno)
876 if (view->offset + lineno >= view->lines)
879 return view->ops->draw(view, &view->line[view->offset + lineno], lineno);
883 redraw_view_from(struct view *view, int lineno)
885 assert(0 <= lineno && lineno < view->height);
887 for (; lineno < view->height; lineno++) {
888 if (!draw_view_line(view, lineno))
892 redrawwin(view->win);
897 redraw_view(struct view *view)
900 redraw_view_from(view, 0);
905 update_view_title(struct view *view)
907 if (view == display[current_view])
908 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
910 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
913 wmove(view->title, 0, 0);
916 wprintw(view->title, "[%s] %s", view->name, view->ref);
918 wprintw(view->title, "[%s]", view->name);
920 if (view->lines || view->pipe) {
921 unsigned int lines = view->lines
922 ? (view->lineno + 1) * 100 / view->lines
925 wprintw(view->title, " - %s %d of %d (%d%%)",
933 time_t secs = time(NULL) - view->start_time;
935 /* Three git seconds are a long time ... */
937 wprintw(view->title, " %lds", secs);
940 wmove(view->title, 0, view->width - 1);
941 wrefresh(view->title);
948 struct view *base = display[0];
949 struct view *view = display[1] ? display[1] : display[0];
951 /* Setup window dimensions */
953 getmaxyx(stdscr, base->height, base->width);
955 /* Make room for the status window. */
959 /* Horizontal split. */
960 view->width = base->width;
961 view->height = SCALE_SPLIT_VIEW(base->height);
962 base->height -= view->height;
964 /* Make room for the title bar. */
968 /* Make room for the title bar. */
973 foreach_view (view, i) {
975 view->win = newwin(view->height, 0, offset, 0);
977 die("Failed to create %s view", view->name);
979 scrollok(view->win, TRUE);
981 view->title = newwin(1, 0, offset + view->height, 0);
983 die("Failed to create title window");
986 wresize(view->win, view->height, view->width);
987 mvwin(view->win, offset, 0);
988 mvwin(view->title, offset + view->height, 0);
991 offset += view->height + 1;
1001 foreach_view (view, i) {
1003 update_view_title(view);
1008 update_display_cursor(void)
1010 struct view *view = display[current_view];
1012 /* Move the cursor to the right-most column of the cursor line.
1014 * XXX: This could turn out to be a bit expensive, but it ensures that
1015 * the cursor does not jump around. */
1017 wmove(view->win, view->lineno - view->offset, view->width - 1);
1018 wrefresh(view->win);
1026 /* Scrolling backend */
1028 do_scroll_view(struct view *view, int lines, bool redraw)
1030 /* The rendering expects the new offset. */
1031 view->offset += lines;
1033 assert(0 <= view->offset && view->offset < view->lines);
1036 /* Redraw the whole screen if scrolling is pointless. */
1037 if (view->height < ABS(lines)) {
1041 int line = lines > 0 ? view->height - lines : 0;
1042 int end = line + ABS(lines);
1044 wscrl(view->win, lines);
1046 for (; line < end; line++) {
1047 if (!draw_view_line(view, line))
1052 /* Move current line into the view. */
1053 if (view->lineno < view->offset) {
1054 view->lineno = view->offset;
1055 draw_view_line(view, 0);
1057 } else if (view->lineno >= view->offset + view->height) {
1058 if (view->lineno == view->offset + view->height) {
1059 /* Clear the hidden line so it doesn't show if the view
1060 * is scrolled up. */
1061 wmove(view->win, view->height, 0);
1062 wclrtoeol(view->win);
1064 view->lineno = view->offset + view->height - 1;
1065 draw_view_line(view, view->lineno - view->offset);
1068 assert(view->offset <= view->lineno && view->lineno < view->lines);
1073 redrawwin(view->win);
1074 wrefresh(view->win);
1078 /* Scroll frontend */
1080 scroll_view(struct view *view, enum request request)
1085 case REQ_SCROLL_PAGE_DOWN:
1086 lines = view->height;
1087 case REQ_SCROLL_LINE_DOWN:
1088 if (view->offset + lines > view->lines)
1089 lines = view->lines - view->offset;
1091 if (lines == 0 || view->offset + view->height >= view->lines) {
1092 report("Cannot scroll beyond the last line");
1097 case REQ_SCROLL_PAGE_UP:
1098 lines = view->height;
1099 case REQ_SCROLL_LINE_UP:
1100 if (lines > view->offset)
1101 lines = view->offset;
1104 report("Cannot scroll beyond the first line");
1112 die("request %d not handled in switch", request);
1115 do_scroll_view(view, lines, TRUE);
1120 move_view(struct view *view, enum request request, bool redraw)
1125 case REQ_MOVE_FIRST_LINE:
1126 steps = -view->lineno;
1129 case REQ_MOVE_LAST_LINE:
1130 steps = view->lines - view->lineno - 1;
1133 case REQ_MOVE_PAGE_UP:
1134 steps = view->height > view->lineno
1135 ? -view->lineno : -view->height;
1138 case REQ_MOVE_PAGE_DOWN:
1139 steps = view->lineno + view->height >= view->lines
1140 ? view->lines - view->lineno - 1 : view->height;
1152 die("request %d not handled in switch", request);
1155 if (steps <= 0 && view->lineno == 0) {
1156 report("Cannot move beyond the first line");
1159 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
1160 report("Cannot move beyond the last line");
1164 /* Move the current line */
1165 view->lineno += steps;
1166 assert(0 <= view->lineno && view->lineno < view->lines);
1168 /* Repaint the old "current" line if we be scrolling */
1169 if (ABS(steps) < view->height) {
1170 int prev_lineno = view->lineno - steps - view->offset;
1172 wmove(view->win, prev_lineno, 0);
1173 wclrtoeol(view->win);
1174 draw_view_line(view, prev_lineno);
1177 /* Check whether the view needs to be scrolled */
1178 if (view->lineno < view->offset ||
1179 view->lineno >= view->offset + view->height) {
1180 if (steps < 0 && -steps > view->offset) {
1181 steps = -view->offset;
1183 } else if (steps > 0) {
1184 if (view->lineno == view->lines - 1 &&
1185 view->lines > view->height) {
1186 steps = view->lines - view->offset - 1;
1187 if (steps >= view->height)
1188 steps -= view->height - 1;
1192 do_scroll_view(view, steps, redraw);
1196 /* Draw the current line */
1197 draw_view_line(view, view->lineno - view->offset);
1202 redrawwin(view->win);
1203 wrefresh(view->win);
1209 * Incremental updating
1213 end_update(struct view *view)
1217 set_nonblocking_input(FALSE);
1218 if (view->pipe == stdin)
1226 begin_update(struct view *view)
1228 const char *id = view->id;
1234 string_copy(view->cmd, opt_cmd);
1236 /* When running random commands, the view ref could have become
1237 * invalid so clear it. */
1240 const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1242 if (snprintf(view->cmd, sizeof(view->cmd), format,
1243 id, id, id, id, id) >= sizeof(view->cmd))
1247 /* Special case for the pager view. */
1249 view->pipe = opt_pipe;
1252 view->pipe = popen(view->cmd, "r");
1258 set_nonblocking_input(TRUE);
1263 string_copy(view->vid, id);
1268 for (i = 0; i < view->lines; i++)
1269 if (view->line[i].data)
1270 free(view->line[i].data);
1276 view->start_time = time(NULL);
1282 update_view(struct view *view)
1284 char buffer[BUFSIZ];
1287 /* The number of lines to read. If too low it will cause too much
1288 * redrawing (and possible flickering), if too high responsiveness
1290 unsigned long lines = view->height;
1291 int redraw_from = -1;
1296 /* Only redraw if lines are visible. */
1297 if (view->offset + view->height >= view->lines)
1298 redraw_from = view->lines - view->offset;
1300 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1306 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1307 int linelen = strlen(line);
1309 struct line *prev = view->lines
1310 ? &view->line[view->lines - 1]
1314 line[linelen - 1] = 0;
1316 if (!view->ops->read(view, prev, line))
1326 lines = view->lines;
1327 for (digits = 0; lines; digits++)
1330 /* Keep the displayed view in sync with line number scaling. */
1331 if (digits != view->digits) {
1332 view->digits = digits;
1337 if (redraw_from >= 0) {
1338 /* If this is an incremental update, redraw the previous line
1339 * since for commits some members could have changed when
1340 * loading the main view. */
1341 if (redraw_from > 0)
1344 /* Incrementally draw avoids flickering. */
1345 redraw_view_from(view, redraw_from);
1348 /* Update the title _after_ the redraw so that if the redraw picks up a
1349 * commit reference in view->ref it'll be available here. */
1350 update_view_title(view);
1352 if (ferror(view->pipe)) {
1353 report("Failed to read: %s", strerror(errno));
1356 } else if (feof(view->pipe)) {
1357 if (view == VIEW(REQ_VIEW_HELP)) {
1358 const char *msg = TIG_HELP;
1360 if (view->lines == 0) {
1361 /* Slightly ugly, but abusing view->ref keeps
1362 * the error message. */
1363 string_copy(view->ref, "No help available");
1364 msg = "The tig(1) manpage is not installed";
1378 report("Allocation failure");
1386 OPEN_DEFAULT = 0, /* Use default view switching. */
1387 OPEN_SPLIT = 1, /* Split current view. */
1388 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1389 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1393 open_view(struct view *prev, enum request request, enum open_flags flags)
1395 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1396 bool split = !!(flags & OPEN_SPLIT);
1397 bool reload = !!(flags & OPEN_RELOAD);
1398 struct view *view = VIEW(request);
1399 int nviews = displayed_views();
1400 struct view *base_view = display[0];
1402 if (view == prev && nviews == 1 && !reload) {
1403 report("Already in %s view", view->name);
1407 if ((reload || strcmp(view->vid, view->id)) &&
1408 !begin_update(view)) {
1409 report("Failed to load %s view", view->name);
1418 /* Maximize the current view. */
1419 memset(display, 0, sizeof(display));
1421 display[current_view] = view;
1424 /* Resize the view when switching between split- and full-screen,
1425 * or when switching between two different full-screen views. */
1426 if (nviews != displayed_views() ||
1427 (nviews == 1 && base_view != display[0]))
1430 if (split && prev->lineno - prev->offset >= prev->height) {
1431 /* Take the title line into account. */
1432 int lines = prev->lineno - prev->offset - prev->height + 1;
1434 /* Scroll the view that was split if the current line is
1435 * outside the new limited view. */
1436 do_scroll_view(prev, lines, TRUE);
1439 if (prev && view != prev) {
1440 if (split && !backgrounded) {
1441 /* "Blur" the previous view. */
1442 update_view_title(prev);
1445 view->parent = prev;
1448 if (view->pipe && view->lines == 0) {
1449 /* Clear the old view and let the incremental updating refill
1455 if (view == VIEW(REQ_VIEW_HELP))
1456 report("%s", TIG_HELP);
1461 /* If the view is backgrounded the above calls to report()
1462 * won't redraw the view title. */
1464 update_view_title(view);
1469 * User request switch noodle
1473 view_driver(struct view *view, enum request request)
1480 case REQ_MOVE_PAGE_UP:
1481 case REQ_MOVE_PAGE_DOWN:
1482 case REQ_MOVE_FIRST_LINE:
1483 case REQ_MOVE_LAST_LINE:
1484 move_view(view, request, TRUE);
1487 case REQ_SCROLL_LINE_DOWN:
1488 case REQ_SCROLL_LINE_UP:
1489 case REQ_SCROLL_PAGE_DOWN:
1490 case REQ_SCROLL_PAGE_UP:
1491 scroll_view(view, request);
1498 case REQ_VIEW_PAGER:
1499 open_view(view, request, OPEN_DEFAULT);
1504 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
1506 if (view == VIEW(REQ_VIEW_DIFF) &&
1507 view->parent == VIEW(REQ_VIEW_MAIN)) {
1508 bool redraw = display[1] == view;
1510 view = view->parent;
1511 move_view(view, request, redraw);
1513 update_view_title(view);
1515 move_view(view, request, TRUE);
1522 report("Nothing to enter");
1525 return view->ops->enter(view, &view->line[view->lineno]);
1529 int nviews = displayed_views();
1530 int next_view = (current_view + 1) % nviews;
1532 if (next_view == current_view) {
1533 report("Only one view is displayed");
1537 current_view = next_view;
1538 /* Blur out the title of the previous view. */
1539 update_view_title(view);
1543 case REQ_TOGGLE_LINE_NUMBERS:
1544 opt_line_number = !opt_line_number;
1549 /* Always reload^Wrerun commands from the prompt. */
1550 open_view(view, opt_request, OPEN_RELOAD);
1553 case REQ_STOP_LOADING:
1554 for (i = 0; i < ARRAY_SIZE(views); i++) {
1557 report("Stopped loading the %s view", view->name),
1562 case REQ_SHOW_VERSION:
1563 report("%s (built %s)", VERSION, __DATE__);
1566 case REQ_SCREEN_RESIZE:
1569 case REQ_SCREEN_REDRAW:
1573 case REQ_SCREEN_UPDATE:
1577 case REQ_VIEW_CLOSE:
1578 /* XXX: Mark closed views by letting view->parent point to the
1579 * view itself. Parents to closed view should never be
1582 view->parent->parent != view->parent) {
1583 memset(display, 0, sizeof(display));
1585 display[current_view] = view->parent;
1586 view->parent = view;
1596 /* An unknown key will show most commonly used commands. */
1597 report("Unknown key, press 'h' for help");
1610 pager_draw(struct view *view, struct line *line, unsigned int lineno)
1612 char *text = line->data;
1613 enum line_type type = line->type;
1614 int textlen = strlen(text);
1617 wmove(view->win, lineno, 0);
1619 if (view->offset + lineno == view->lineno) {
1620 if (type == LINE_COMMIT) {
1621 string_copy(view->ref, text + 7);
1622 string_copy(ref_commit, view->ref);
1626 wchgat(view->win, -1, 0, type, NULL);
1629 attr = get_line_attr(type);
1630 wattrset(view->win, attr);
1632 if (opt_line_number || opt_tab_size < TABSIZE) {
1633 static char spaces[] = " ";
1634 int col_offset = 0, col = 0;
1636 if (opt_line_number) {
1637 unsigned long real_lineno = view->offset + lineno + 1;
1639 if (real_lineno == 1 ||
1640 (real_lineno % opt_num_interval) == 0) {
1641 wprintw(view->win, "%.*d", view->digits, real_lineno);
1644 waddnstr(view->win, spaces,
1645 MIN(view->digits, STRING_SIZE(spaces)));
1647 waddstr(view->win, ": ");
1648 col_offset = view->digits + 2;
1651 while (text && col_offset + col < view->width) {
1652 int cols_max = view->width - col_offset - col;
1656 if (*text == '\t') {
1658 assert(sizeof(spaces) > TABSIZE);
1660 cols = opt_tab_size - (col % opt_tab_size);
1663 text = strchr(text, '\t');
1664 cols = line ? text - pos : strlen(pos);
1667 waddnstr(view->win, pos, MIN(cols, cols_max));
1672 int col = 0, pos = 0;
1674 for (; pos < textlen && col < view->width; pos++, col++)
1675 if (text[pos] == '\t')
1676 col += TABSIZE - (col % TABSIZE) - 1;
1678 waddnstr(view->win, text, pos);
1685 pager_read(struct view *view, struct line *prev, char *line)
1687 /* Compress empty lines in the help view. */
1688 if (view == VIEW(REQ_VIEW_HELP) &&
1689 !*line && prev && !*((char *) prev->data))
1692 view->line[view->lines].data = strdup(line);
1693 if (!view->line[view->lines].data)
1696 view->line[view->lines].type = get_line_type(line);
1703 pager_enter(struct view *view, struct line *line)
1707 if (line->type == LINE_COMMIT &&
1708 (view == VIEW(REQ_VIEW_LOG) ||
1709 view == VIEW(REQ_VIEW_PAGER))) {
1710 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
1714 /* Always scroll the view even if it was split. That way
1715 * you can use Enter to scroll through the log view and
1716 * split open each commit diff. */
1717 scroll_view(view, REQ_SCROLL_LINE_DOWN);
1719 /* FIXME: A minor workaround. Scrolling the view will call report("")
1720 * but if we are scrolling a non-current view this won't properly
1721 * update the view title. */
1723 update_view_title(view);
1728 static struct view_ops pager_ops = {
1741 char id[41]; /* SHA1 ID. */
1742 char title[75]; /* The first line of the commit message. */
1743 char author[75]; /* The author of the commit. */
1744 struct tm time; /* Date from the author ident. */
1745 struct ref **refs; /* Repository references; tags & branch heads. */
1749 main_draw(struct view *view, struct line *line, unsigned int lineno)
1751 char buf[DATE_COLS + 1];
1752 struct commit *commit = line->data;
1753 enum line_type type;
1759 if (!*commit->author)
1762 wmove(view->win, lineno, col);
1764 if (view->offset + lineno == view->lineno) {
1765 string_copy(view->ref, commit->id);
1766 string_copy(ref_commit, view->ref);
1768 wattrset(view->win, get_line_attr(type));
1769 wchgat(view->win, -1, 0, type, NULL);
1772 type = LINE_MAIN_COMMIT;
1773 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1776 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1777 waddnstr(view->win, buf, timelen);
1778 waddstr(view->win, " ");
1781 wmove(view->win, lineno, col);
1782 if (type != LINE_CURSOR)
1783 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1786 authorlen = utf8_length(commit->author, AUTHOR_COLS - 2, &col, &trimmed);
1788 authorlen = strlen(commit->author);
1789 if (authorlen > AUTHOR_COLS - 2) {
1790 authorlen = AUTHOR_COLS - 2;
1796 waddnstr(view->win, commit->author, authorlen);
1797 if (type != LINE_CURSOR)
1798 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1799 waddch(view->win, '~');
1801 waddstr(view->win, commit->author);
1805 if (type != LINE_CURSOR)
1806 wattrset(view->win, A_NORMAL);
1808 mvwaddch(view->win, lineno, col, ACS_LTEE);
1809 wmove(view->win, lineno, col + 2);
1816 if (type == LINE_CURSOR)
1818 else if (commit->refs[i]->tag)
1819 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1821 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1822 waddstr(view->win, "[");
1823 waddstr(view->win, commit->refs[i]->name);
1824 waddstr(view->win, "]");
1825 if (type != LINE_CURSOR)
1826 wattrset(view->win, A_NORMAL);
1827 waddstr(view->win, " ");
1828 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
1829 } while (commit->refs[i++]->next);
1832 if (type != LINE_CURSOR)
1833 wattrset(view->win, get_line_attr(type));
1836 int titlelen = strlen(commit->title);
1838 if (col + titlelen > view->width)
1839 titlelen = view->width - col;
1841 waddnstr(view->win, commit->title, titlelen);
1847 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1849 main_read(struct view *view, struct line *prev, char *line)
1851 enum line_type type = get_line_type(line);
1852 struct commit *commit;
1856 commit = calloc(1, sizeof(struct commit));
1860 line += STRING_SIZE("commit ");
1862 view->line[view->lines++].data = commit;
1863 string_copy(commit->id, line);
1864 commit->refs = get_refs(commit->id);
1869 char *ident = line + STRING_SIZE("author ");
1870 char *end = strchr(ident, '<');
1875 commit = prev->data;
1878 for (; end > ident && isspace(end[-1]); end--) ;
1882 string_copy(commit->author, ident);
1884 /* Parse epoch and timezone */
1886 char *secs = strchr(end + 1, '>');
1890 if (!secs || secs[1] != ' ')
1894 time = (time_t) atol(secs);
1895 zone = strchr(secs, ' ');
1896 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1900 tz = ('0' - zone[1]) * 60 * 60 * 10;
1901 tz += ('0' - zone[2]) * 60 * 60;
1902 tz += ('0' - zone[3]) * 60;
1903 tz += ('0' - zone[4]) * 60;
1910 gmtime_r(&time, &commit->time);
1918 commit = prev->data;
1920 /* Fill in the commit title if it has not already been set. */
1921 if (commit->title[0])
1924 /* Require titles to start with a non-space character at the
1925 * offset used by git log. */
1926 /* FIXME: More gracefull handling of titles; append "..." to
1927 * shortened titles, etc. */
1928 if (strncmp(line, " ", 4) ||
1932 string_copy(commit->title, line + 4);
1939 main_enter(struct view *view, struct line *line)
1941 enum open_flags flags = display[0] == view ? OPEN_SPLIT : OPEN_DEFAULT;
1943 open_view(view, REQ_VIEW_DIFF, flags);
1947 static struct view_ops main_ops = {
1964 static struct keymap keymap[] = {
1965 /* View switching */
1966 { 'm', REQ_VIEW_MAIN },
1967 { 'd', REQ_VIEW_DIFF },
1968 { 'l', REQ_VIEW_LOG },
1969 { 'p', REQ_VIEW_PAGER },
1970 { 'h', REQ_VIEW_HELP },
1972 /* View manipulation */
1973 { 'q', REQ_VIEW_CLOSE },
1974 { KEY_TAB, REQ_VIEW_NEXT },
1975 { KEY_RETURN, REQ_ENTER },
1976 { KEY_UP, REQ_PREVIOUS },
1977 { KEY_DOWN, REQ_NEXT },
1979 /* Cursor navigation */
1980 { 'k', REQ_MOVE_UP },
1981 { 'j', REQ_MOVE_DOWN },
1982 { KEY_HOME, REQ_MOVE_FIRST_LINE },
1983 { KEY_END, REQ_MOVE_LAST_LINE },
1984 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
1985 { ' ', REQ_MOVE_PAGE_DOWN },
1986 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
1987 { 'b', REQ_MOVE_PAGE_UP },
1988 { '-', REQ_MOVE_PAGE_UP },
1991 { KEY_IC, REQ_SCROLL_LINE_UP },
1992 { KEY_DC, REQ_SCROLL_LINE_DOWN },
1993 { 'w', REQ_SCROLL_PAGE_UP },
1994 { 's', REQ_SCROLL_PAGE_DOWN },
1998 { 'z', REQ_STOP_LOADING },
1999 { 'v', REQ_SHOW_VERSION },
2000 { 'r', REQ_SCREEN_REDRAW },
2001 { 'n', REQ_TOGGLE_LINE_NUMBERS },
2002 { ':', REQ_PROMPT },
2004 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
2005 { ERR, REQ_SCREEN_UPDATE },
2007 /* Use the ncurses SIGWINCH handler. */
2008 { KEY_RESIZE, REQ_SCREEN_RESIZE },
2012 get_request(int key)
2016 for (i = 0; i < ARRAY_SIZE(keymap); i++)
2017 if (keymap[i].alias == key)
2018 return keymap[i].request;
2020 return (enum request) key;
2025 * Unicode / UTF-8 handling
2027 * NOTE: Much of the following code for dealing with unicode is derived from
2028 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
2029 * src/intl/charset.c from the utf8 branch commit elinks-0.11.0-g31f2c28.
2032 /* I've (over)annotated a lot of code snippets because I am not entirely
2033 * confident that the approach taken by this small UTF-8 interface is correct.
2037 unicode_width(unsigned long c)
2040 (c <= 0x115f /* Hangul Jamo */
2043 || (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f)
2045 || (c >= 0xac00 && c <= 0xd7a3) /* Hangul Syllables */
2046 || (c >= 0xf900 && c <= 0xfaff) /* CJK Compatibility Ideographs */
2047 || (c >= 0xfe30 && c <= 0xfe6f) /* CJK Compatibility Forms */
2048 || (c >= 0xff00 && c <= 0xff60) /* Fullwidth Forms */
2049 || (c >= 0xffe0 && c <= 0xffe6)
2050 || (c >= 0x20000 && c <= 0x2fffd)
2051 || (c >= 0x30000 && c <= 0x3fffd)))
2057 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
2058 * Illegal bytes are set one. */
2059 static const unsigned char utf8_bytes[256] = {
2060 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,
2061 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,
2062 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,
2063 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,
2064 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,
2065 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,
2066 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,
2067 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,
2070 /* Decode UTF-8 multi-byte representation into a unicode character. */
2071 static inline unsigned long
2072 utf8_to_unicode(const char *string, size_t length)
2074 unsigned long unicode;
2078 unicode = string[0];
2081 unicode = (string[0] & 0x1f) << 6;
2082 unicode += (string[1] & 0x3f);
2085 unicode = (string[0] & 0x0f) << 12;
2086 unicode += ((string[1] & 0x3f) << 6);
2087 unicode += (string[2] & 0x3f);
2090 unicode = (string[0] & 0x0f) << 18;
2091 unicode += ((string[1] & 0x3f) << 12);
2092 unicode += ((string[2] & 0x3f) << 6);
2093 unicode += (string[3] & 0x3f);
2096 unicode = (string[0] & 0x0f) << 24;
2097 unicode += ((string[1] & 0x3f) << 18);
2098 unicode += ((string[2] & 0x3f) << 12);
2099 unicode += ((string[3] & 0x3f) << 6);
2100 unicode += (string[4] & 0x3f);
2103 unicode = (string[0] & 0x01) << 30;
2104 unicode += ((string[1] & 0x3f) << 24);
2105 unicode += ((string[2] & 0x3f) << 18);
2106 unicode += ((string[3] & 0x3f) << 12);
2107 unicode += ((string[4] & 0x3f) << 6);
2108 unicode += (string[5] & 0x3f);
2111 die("Invalid unicode length");
2114 /* Invalid characters could return the special 0xfffd value but NUL
2115 * should be just as good. */
2116 return unicode > 0xffff ? 0 : unicode;
2119 /* Calculates how much of string can be shown within the given maximum width
2120 * and sets trimmed parameter to non-zero value if all of string could not be
2123 * Additionally, adds to coloffset how many many columns to move to align with
2124 * the expected position. Takes into account how multi-byte and double-width
2125 * characters will effect the cursor position.
2127 * Returns the number of bytes to output from string to satisfy max_width. */
2129 utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed)
2131 const char *start = string;
2132 const char *end = strchr(string, '\0');
2138 while (string < end) {
2139 int c = *(unsigned char *) string;
2140 unsigned char bytes = utf8_bytes[c];
2142 unsigned long unicode;
2144 if (string + bytes > end)
2147 /* Change representation to figure out whether
2148 * it is a single- or double-width character. */
2150 unicode = utf8_to_unicode(string, bytes);
2151 /* FIXME: Graceful handling of invalid unicode character. */
2155 ucwidth = unicode_width(unicode);
2157 if (width > max_width) {
2162 /* The column offset collects the differences between the
2163 * number of bytes encoding a character and the number of
2164 * columns will be used for rendering said character.
2166 * So if some character A is encoded in 2 bytes, but will be
2167 * represented on the screen using only 1 byte this will and up
2168 * adding 1 to the multi-byte column offset.
2170 * Assumes that no double-width character can be encoding in
2171 * less than two bytes. */
2172 if (bytes > ucwidth)
2173 mbwidth += bytes - ucwidth;
2178 *coloffset += mbwidth;
2180 return string - start;
2188 /* Whether or not the curses interface has been initialized. */
2189 static bool cursed = FALSE;
2191 /* The status window is used for polling keystrokes. */
2192 static WINDOW *status_win;
2194 /* Update status and title window. */
2196 report(const char *msg, ...)
2198 static bool empty = TRUE;
2199 struct view *view = display[current_view];
2201 if (!empty || *msg) {
2204 va_start(args, msg);
2207 wmove(status_win, 0, 0);
2209 vwprintw(status_win, msg, args);
2214 wrefresh(status_win);
2219 update_view_title(view);
2220 update_display_cursor();
2223 /* Controls when nodelay should be in effect when polling user input. */
2225 set_nonblocking_input(bool loading)
2227 static unsigned int loading_views;
2229 if ((loading == FALSE && loading_views-- == 1) ||
2230 (loading == TRUE && loading_views++ == 0))
2231 nodelay(status_win, loading);
2239 /* Initialize the curses library */
2240 if (isatty(STDIN_FILENO)) {
2241 cursed = !!initscr();
2243 /* Leave stdin and stdout alone when acting as a pager. */
2244 FILE *io = fopen("/dev/tty", "r+");
2246 cursed = !!newterm(NULL, io, io);
2250 die("Failed to initialize curses");
2252 nonl(); /* Tell curses not to do NL->CR/NL on output */
2253 cbreak(); /* Take input chars one at a time, no wait for \n */
2254 noecho(); /* Don't echo input */
2255 leaveok(stdscr, TRUE);
2260 getmaxyx(stdscr, y, x);
2261 status_win = newwin(1, 0, y - 1, 0);
2263 die("Failed to create status window");
2265 /* Enable keyboard mapping */
2266 keypad(status_win, TRUE);
2267 wbkgdset(status_win, get_line_attr(LINE_STATUS));
2272 * Repository references
2275 static struct ref *refs;
2276 static size_t refs_size;
2278 /* Id <-> ref store */
2279 static struct ref ***id_refs;
2280 static size_t id_refs_size;
2282 static struct ref **
2285 struct ref ***tmp_id_refs;
2286 struct ref **ref_list = NULL;
2287 size_t ref_list_size = 0;
2290 for (i = 0; i < id_refs_size; i++)
2291 if (!strcmp(id, id_refs[i][0]->id))
2294 tmp_id_refs = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
2298 id_refs = tmp_id_refs;
2300 for (i = 0; i < refs_size; i++) {
2303 if (strcmp(id, refs[i].id))
2306 tmp = realloc(ref_list, (ref_list_size + 1) * sizeof(*ref_list));
2314 if (ref_list_size > 0)
2315 ref_list[ref_list_size - 1]->next = 1;
2316 ref_list[ref_list_size] = &refs[i];
2318 /* XXX: The properties of the commit chains ensures that we can
2319 * safely modify the shared ref. The repo references will
2320 * always be similar for the same id. */
2321 ref_list[ref_list_size]->next = 0;
2326 id_refs[id_refs_size++] = ref_list;
2332 read_ref(char *id, int idlen, char *name, int namelen)
2336 bool tag_commit = FALSE;
2338 /* Commits referenced by tags has "^{}" appended. */
2339 if (name[namelen - 1] == '}') {
2340 while (namelen > 0 && name[namelen] != '^')
2347 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
2350 name += STRING_SIZE("refs/tags/");
2353 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
2354 name += STRING_SIZE("refs/heads/");
2356 } else if (!strcmp(name, "HEAD")) {
2360 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2364 ref = &refs[refs_size++];
2365 ref->name = strdup(name);
2370 string_copy(ref->id, id);
2378 const char *cmd_env = getenv("TIG_LS_REMOTE");
2379 const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
2381 return read_properties(popen(cmd, "r"), "\t", read_ref);
2385 read_repo_config_option(char *name, int namelen, char *value, int valuelen)
2387 if (!strcmp(name, "i18n.commitencoding")) {
2388 string_copy(opt_encoding, value);
2395 load_repo_config(void)
2397 return read_properties(popen("git repo-config --list", "r"),
2398 "=", read_repo_config_option);
2402 read_properties(FILE *pipe, const char *separators,
2403 int (*read_property)(char *, int, char *, int))
2405 char buffer[BUFSIZ];
2412 while (state == OK && (name = fgets(buffer, sizeof(buffer), pipe))) {
2417 name = chomp_string(name);
2418 namelen = strcspn(name, separators);
2420 if (name[namelen]) {
2422 value = chomp_string(name + namelen + 1);
2423 valuelen = strlen(value);
2430 state = read_property(name, namelen, value, valuelen);
2433 if (state != ERR && ferror(pipe))
2447 #define __NORETURN __attribute__((__noreturn__))
2452 static void __NORETURN
2455 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2461 static void __NORETURN
2462 die(const char *err, ...)
2468 va_start(args, err);
2469 fputs("tig: ", stderr);
2470 vfprintf(stderr, err, args);
2471 fputs("\n", stderr);
2478 main(int argc, char *argv[])
2481 enum request request;
2484 signal(SIGINT, quit);
2486 if (load_options() == ERR)
2487 die("Failed to load user config.");
2489 /* Load the repo config file so options can be overwritten from
2490 * the command line. */
2491 if (load_repo_config() == ERR)
2492 die("Failed to load repo config.");
2494 if (!parse_options(argc, argv))
2497 if (load_refs() == ERR)
2498 die("Failed to load refs.");
2500 /* Require a git repository unless when running in pager mode. */
2501 if (refs_size == 0 && opt_request != REQ_VIEW_PAGER)
2502 die("Not a git repository");
2504 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2505 view->cmd_env = getenv(view->cmd_env);
2507 request = opt_request;
2511 while (view_driver(display[current_view], request)) {
2515 foreach_view (view, i)
2518 /* Refresh, accept single keystroke of input */
2519 key = wgetch(status_win);
2520 request = get_request(key);
2522 /* Some low-level request handling. This keeps access to
2523 * status_win restricted. */
2527 /* Temporarily switch to line-oriented and echoed
2532 if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
2533 memcpy(opt_cmd, "git ", 4);
2534 opt_request = REQ_VIEW_PAGER;
2536 report("Prompt interrupted by loading view, "
2537 "press 'z' to stop loading views");
2538 request = REQ_SCREEN_UPDATE;
2545 case REQ_SCREEN_RESIZE:
2549 getmaxyx(stdscr, height, width);
2551 /* Resize the status view and let the view driver take
2552 * care of resizing the displayed views. */
2553 wresize(status_win, 1, width);
2554 mvwin(status_win, height - 1, 0);
2555 wrefresh(status_win);
2573 * Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
2575 * This program is free software; you can redistribute it and/or modify
2576 * it under the terms of the GNU General Public License as published by
2577 * the Free Software Foundation; either version 2 of the License, or
2578 * (at your option) any later version.
2582 * - link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
2583 * - link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
2585 * Other git repository browsers: