Move refs helpers to refs module
[tig.git] / src / tig.c
blobc80efb29db88d3c5a17b419323df5740889d6f9c
1 /* Copyright (c) 2006-2013 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.
14 #define WARN_MISSING_CURSES_CONFIGURATION
16 #include "tig.h"
17 #include "types.h"
18 #include "util.h"
19 #include "io.h"
20 #include "refs.h"
21 #include "graph.h"
22 #include "git.h"
23 #include "request.h"
24 #include "line.h"
25 #include "keys.h"
26 #include "view.h"
27 #include "repo.h"
29 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
30 #define report_clear() report("%s", "")
33 enum input_status {
34 INPUT_OK,
35 INPUT_SKIP,
36 INPUT_STOP,
37 INPUT_CANCEL
40 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
42 static char *prompt_input(const char *prompt, input_handler handler, void *data);
43 static bool prompt_yesno(const char *prompt);
44 static char *read_prompt(const char *prompt);
46 struct menu_item {
47 int hotkey;
48 const char *text;
49 void *data;
52 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
55 * Options
58 /* Option variables. */
59 static enum graphic opt_line_graphics;
60 static enum date opt_date;
61 static enum author opt_author;
62 static enum filename opt_filename;
63 static enum file_size opt_file_size;
64 static bool opt_rev_graph;
65 static bool opt_line_number;
66 static bool opt_show_refs;
67 static bool opt_show_changes;
68 static bool opt_untracked_dirs_content;
69 static bool opt_read_git_colors;
70 static bool opt_wrap_lines;
71 static bool opt_ignore_case;
72 static bool opt_focus_child;
73 static int opt_diff_context;
74 static enum ignore_space opt_ignore_space;
75 static enum commit_order opt_commit_order;
76 static bool opt_notes;
77 static int opt_num_interval;
78 static double opt_hscroll;
79 static double opt_scale_split_view;
80 static double opt_scale_vsplit_view;
81 static enum vertical_split opt_vertical_split;
82 static int opt_tab_size;
83 static int opt_author_width;
84 static int opt_filename_width;
85 static bool opt_editor_lineno;
86 static bool opt_show_id;
87 static int opt_id_cols;
88 static bool opt_show_title_overflow;
89 static int opt_title_overflow;
90 static bool opt_mouse;
91 static int opt_scroll_wheel_lines;
93 /* State variables. */
94 static char opt_diff_context_arg[9] = "";
95 static char opt_ignore_space_arg[22] = "";
96 static char opt_commit_order_arg[22] = "";
97 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
98 static char opt_path[SIZEOF_STR] = "";
99 static char opt_file[SIZEOF_STR] = "";
100 static char opt_ref[SIZEOF_REF] = "";
101 static unsigned long opt_goto_line = 0;
102 static int opt_lineno = 0;
103 static bool opt_file_filter;
104 static iconv_t opt_iconv_out = ICONV_NONE;
105 static char opt_search[SIZEOF_STR] = "";
106 static char opt_editor[SIZEOF_STR] = "";
107 static FILE *opt_tty = NULL;
108 static const char **opt_cmdline_argv = NULL;
109 static const char **opt_diff_argv = NULL;
110 static const char **opt_rev_argv = NULL;
111 static const char **opt_file_argv = NULL;
112 static const char **opt_blame_argv = NULL;
113 static char opt_env_lines[64] = "";
114 static char opt_env_columns[64] = "";
115 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
117 static bool
118 vertical_split_is_enabled(void)
120 if (opt_vertical_split == VERTICAL_SPLIT_AUTO) {
121 int height, width;
123 getmaxyx(stdscr, height, width);
124 return width * opt_scale_vsplit_view > (height - 1) * 2;
127 return opt_vertical_split == VERTICAL_SPLIT_VERTICAL;
130 static inline void
131 update_diff_context_arg(int diff_context)
133 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
134 string_ncopy(opt_diff_context_arg, "-U3", 3);
137 #define ENUM_ARG(enum_name, arg_string) ENUM_MAP_ENTRY(arg_string, enum_name)
139 static const struct enum_map_entry ignore_space_arg_map[] = {
140 ENUM_ARG(IGNORE_SPACE_NO, ""),
141 ENUM_ARG(IGNORE_SPACE_ALL, "--ignore-all-space"),
142 ENUM_ARG(IGNORE_SPACE_SOME, "--ignore-space-change"),
143 ENUM_ARG(IGNORE_SPACE_AT_EOL, "--ignore-space-at-eol"),
146 static inline void
147 update_ignore_space_arg()
149 enum_copy_name(opt_ignore_space_arg, ignore_space_arg_map[opt_ignore_space]);
152 static const struct enum_map_entry commit_order_arg_map[] = {
153 ENUM_ARG(COMMIT_ORDER_DEFAULT, ""),
154 ENUM_ARG(COMMIT_ORDER_TOPO, "--topo-order"),
155 ENUM_ARG(COMMIT_ORDER_DATE, "--date-order"),
156 ENUM_ARG(COMMIT_ORDER_REVERSE, "--reverse"),
159 static inline void
160 update_commit_order_arg()
162 enum_copy_name(opt_commit_order_arg, commit_order_arg_map[opt_commit_order]);
165 static inline void
166 update_notes_arg()
168 if (opt_notes) {
169 string_copy(opt_notes_arg, "--show-notes");
170 } else {
171 /* Notes are disabled by default when passing --pretty args. */
172 string_copy(opt_notes_arg, "");
176 struct line {
177 enum line_type type;
178 unsigned int lineno:24;
180 /* State flags */
181 unsigned int selected:1;
182 unsigned int dirty:1;
183 unsigned int cleareol:1;
184 unsigned int wrapped:1;
186 unsigned int user_flags:6;
187 void *data; /* User data */
192 * User config file handling.
195 static const struct enum_map_entry color_map[] = {
196 #define COLOR_MAP(name) ENUM_MAP_ENTRY(#name, COLOR_##name)
197 COLOR_MAP(DEFAULT),
198 COLOR_MAP(BLACK),
199 COLOR_MAP(BLUE),
200 COLOR_MAP(CYAN),
201 COLOR_MAP(GREEN),
202 COLOR_MAP(MAGENTA),
203 COLOR_MAP(RED),
204 COLOR_MAP(WHITE),
205 COLOR_MAP(YELLOW),
208 static const struct enum_map_entry attr_map[] = {
209 #define ATTR_MAP(name) ENUM_MAP_ENTRY(#name, A_##name)
210 ATTR_MAP(NORMAL),
211 ATTR_MAP(BLINK),
212 ATTR_MAP(BOLD),
213 ATTR_MAP(DIM),
214 ATTR_MAP(REVERSE),
215 ATTR_MAP(STANDOUT),
216 ATTR_MAP(UNDERLINE),
219 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
221 static enum status_code
222 parse_step(double *opt, const char *arg)
224 *opt = atoi(arg);
225 if (!strchr(arg, '%'))
226 return SUCCESS;
228 /* "Shift down" so 100% and 1 does not conflict. */
229 *opt = (*opt - 1) / 100;
230 if (*opt >= 1.0) {
231 *opt = 0.99;
232 return ERROR_INVALID_STEP_VALUE;
234 if (*opt < 0.0) {
235 *opt = 1;
236 return ERROR_INVALID_STEP_VALUE;
238 return SUCCESS;
241 static enum status_code
242 parse_int(int *opt, const char *arg, int min, int max)
244 int value = atoi(arg);
246 if (min <= value && value <= max) {
247 *opt = value;
248 return SUCCESS;
251 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
254 #define parse_id(opt, arg) \
255 parse_int(opt, arg, 4, SIZEOF_REV - 1)
257 static bool
258 set_color(int *color, const char *name)
260 if (map_enum(color, color_map, name))
261 return TRUE;
262 if (!prefixcmp(name, "color"))
263 return parse_int(color, name + 5, 0, 255) == SUCCESS;
264 /* Used when reading git colors. Git expects a plain int w/o prefix. */
265 return parse_int(color, name, 0, 255) == SUCCESS;
268 /* Wants: object fgcolor bgcolor [attribute] */
269 static enum status_code
270 option_color_command(int argc, const char *argv[])
272 struct line_info *info;
274 if (argc < 3)
275 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
277 if (*argv[0] == '"' || *argv[0] == '\'') {
278 info = add_custom_color(argv[0]);
279 } else {
280 info = find_line_info(argv[0], strlen(argv[0]), FALSE);
282 if (!info) {
283 static const struct enum_map_entry obsolete[] = {
284 ENUM_MAP_ENTRY("main-delim", LINE_DELIMITER),
285 ENUM_MAP_ENTRY("main-date", LINE_DATE),
286 ENUM_MAP_ENTRY("main-author", LINE_AUTHOR),
287 ENUM_MAP_ENTRY("blame-id", LINE_ID),
289 int index;
291 if (!map_enum(&index, obsolete, argv[0]))
292 return ERROR_UNKNOWN_COLOR_NAME;
293 info = get_line_info(index);
296 if (!set_color(&info->fg, argv[1]) ||
297 !set_color(&info->bg, argv[2]))
298 return ERROR_UNKNOWN_COLOR;
300 info->attr = 0;
301 while (argc-- > 3) {
302 int attr;
304 if (!set_attribute(&attr, argv[argc]))
305 return ERROR_UNKNOWN_ATTRIBUTE;
306 info->attr |= attr;
309 return SUCCESS;
312 static enum status_code
313 parse_bool_matched(bool *opt, const char *arg, bool *matched)
315 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
316 ? TRUE : FALSE;
317 if (matched)
318 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
319 return SUCCESS;
322 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
324 static enum status_code
325 parse_enum(unsigned int *opt, const char *arg, const struct enum_map *map)
327 bool is_true;
329 assert(map->size > 1);
331 if (map_enum_do(map->entries, map->size, (int *) opt, arg))
332 return SUCCESS;
334 parse_bool(&is_true, arg);
335 *opt = is_true ? map->entries[1].value : map->entries[0].value;
336 return SUCCESS;
339 static enum status_code
340 parse_string(char *opt, const char *arg, size_t optsize)
342 int arglen = strlen(arg);
344 switch (arg[0]) {
345 case '\"':
346 case '\'':
347 if (arglen == 1 || arg[arglen - 1] != arg[0])
348 return ERROR_UNMATCHED_QUOTATION;
349 arg += 1; arglen -= 2;
350 default:
351 string_ncopy_do(opt, optsize, arg, arglen);
352 return SUCCESS;
356 static enum status_code
357 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
359 char buf[SIZEOF_STR];
360 enum status_code code = parse_string(buf, arg, sizeof(buf));
362 if (code == SUCCESS) {
363 struct encoding *encoding = *encoding_ref;
365 if (encoding && !priority)
366 return code;
367 encoding = encoding_open(buf);
368 if (encoding)
369 *encoding_ref = encoding;
372 return code;
375 static enum status_code
376 parse_args(const char ***args, const char *argv[])
378 if (!argv_copy(args, argv))
379 return ERROR_OUT_OF_MEMORY;
380 return SUCCESS;
383 /* Wants: name = value */
384 static enum status_code
385 option_set_command(int argc, const char *argv[])
387 if (argc < 3)
388 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
390 if (strcmp(argv[1], "="))
391 return ERROR_NO_VALUE_ASSIGNED;
393 if (!strcmp(argv[0], "blame-options"))
394 return parse_args(&opt_blame_argv, argv + 2);
396 if (!strcmp(argv[0], "diff-options"))
397 return parse_args(&opt_diff_argv, argv + 2);
399 if (argc != 3)
400 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
402 if (!strcmp(argv[0], "show-author"))
403 return parse_enum(&opt_author, argv[2], author_map);
405 if (!strcmp(argv[0], "show-date"))
406 return parse_enum(&opt_date, argv[2], date_map);
408 if (!strcmp(argv[0], "show-rev-graph"))
409 return parse_bool(&opt_rev_graph, argv[2]);
411 if (!strcmp(argv[0], "show-refs"))
412 return parse_bool(&opt_show_refs, argv[2]);
414 if (!strcmp(argv[0], "show-changes"))
415 return parse_bool(&opt_show_changes, argv[2]);
417 if (!strcmp(argv[0], "show-notes")) {
418 bool matched = FALSE;
419 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
421 if (res == SUCCESS && matched) {
422 update_notes_arg();
423 return res;
426 opt_notes = TRUE;
427 strcpy(opt_notes_arg, "--show-notes=");
428 res = parse_string(opt_notes_arg + 8, argv[2],
429 sizeof(opt_notes_arg) - 8);
430 if (res == SUCCESS && opt_notes_arg[8] == '\0')
431 opt_notes_arg[7] = '\0';
432 return res;
435 if (!strcmp(argv[0], "show-line-numbers"))
436 return parse_bool(&opt_line_number, argv[2]);
438 if (!strcmp(argv[0], "line-graphics"))
439 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
441 if (!strcmp(argv[0], "line-number-interval"))
442 return parse_int(&opt_num_interval, argv[2], 1, 1024);
444 if (!strcmp(argv[0], "author-width"))
445 return parse_int(&opt_author_width, argv[2], 0, 1024);
447 if (!strcmp(argv[0], "filename-width"))
448 return parse_int(&opt_filename_width, argv[2], 0, 1024);
450 if (!strcmp(argv[0], "show-filename"))
451 return parse_enum(&opt_filename, argv[2], filename_map);
453 if (!strcmp(argv[0], "show-file-size"))
454 return parse_enum(&opt_file_size, argv[2], file_size_map);
456 if (!strcmp(argv[0], "horizontal-scroll"))
457 return parse_step(&opt_hscroll, argv[2]);
459 if (!strcmp(argv[0], "split-view-height"))
460 return parse_step(&opt_scale_split_view, argv[2]);
462 if (!strcmp(argv[0], "vertical-split"))
463 return parse_enum(&opt_vertical_split, argv[2], vertical_split_map);
465 if (!strcmp(argv[0], "tab-size"))
466 return parse_int(&opt_tab_size, argv[2], 1, 1024);
468 if (!strcmp(argv[0], "diff-context") && !*opt_diff_context_arg) {
469 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
471 if (code == SUCCESS)
472 update_diff_context_arg(opt_diff_context);
473 return code;
476 if (!strcmp(argv[0], "ignore-space") && !*opt_ignore_space_arg) {
477 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
479 if (code == SUCCESS)
480 update_ignore_space_arg();
481 return code;
484 if (!strcmp(argv[0], "commit-order") && !*opt_commit_order_arg) {
485 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
487 if (code == SUCCESS)
488 update_commit_order_arg();
489 return code;
492 if (!strcmp(argv[0], "status-untracked-dirs"))
493 return parse_bool(&opt_untracked_dirs_content, argv[2]);
495 if (!strcmp(argv[0], "read-git-colors"))
496 return parse_bool(&opt_read_git_colors, argv[2]);
498 if (!strcmp(argv[0], "ignore-case"))
499 return parse_bool(&opt_ignore_case, argv[2]);
501 if (!strcmp(argv[0], "focus-child"))
502 return parse_bool(&opt_focus_child, argv[2]);
504 if (!strcmp(argv[0], "wrap-lines"))
505 return parse_bool(&opt_wrap_lines, argv[2]);
507 if (!strcmp(argv[0], "show-id"))
508 return parse_bool(&opt_show_id, argv[2]);
510 if (!strcmp(argv[0], "id-width"))
511 return parse_id(&opt_id_cols, argv[2]);
513 if (!strcmp(argv[0], "title-overflow")) {
514 bool matched;
515 enum status_code code;
518 * "title-overflow" is considered a boolint.
519 * We try to parse it as a boolean (and set the value to 50 if true),
520 * otherwise we parse it as an integer and use the given value.
522 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
523 if (code == SUCCESS && matched) {
524 if (opt_show_title_overflow)
525 opt_title_overflow = 50;
526 } else {
527 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
528 if (code == SUCCESS)
529 opt_show_title_overflow = TRUE;
532 return code;
535 if (!strcmp(argv[0], "editor-line-number"))
536 return parse_bool(&opt_editor_lineno, argv[2]);
538 if (!strcmp(argv[0], "mouse"))
539 return parse_bool(&opt_mouse, argv[2]);
541 if (!strcmp(argv[0], "mouse-scroll"))
542 return parse_int(&opt_scroll_wheel_lines, argv[2], 0, 1024);
544 return ERROR_UNKNOWN_VARIABLE_NAME;
547 /* Wants: mode request key */
548 static enum status_code
549 option_bind_command(int argc, const char *argv[])
551 enum request request;
552 struct keymap *keymap;
553 int key;
555 if (argc < 3)
556 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
558 if (!(keymap = get_keymap(argv[0])))
559 return ERROR_UNKNOWN_KEY_MAP;
561 key = get_key_value(argv[1]);
562 if (key == ERR)
563 return ERROR_UNKNOWN_KEY;
565 request = get_request(argv[2]);
566 if (request == REQ_UNKNOWN) {
567 static const struct enum_map_entry obsolete[] = {
568 ENUM_MAP_ENTRY("cherry-pick", REQ_NONE),
569 ENUM_MAP_ENTRY("screen-resize", REQ_NONE),
570 ENUM_MAP_ENTRY("tree-parent", REQ_PARENT),
572 int alias;
574 if (map_enum(&alias, obsolete, argv[2])) {
575 if (alias != REQ_NONE)
576 add_keybinding(keymap, alias, key);
577 return ERROR_OBSOLETE_REQUEST_NAME;
581 if (request == REQ_UNKNOWN) {
582 enum run_request_flag flags = RUN_REQUEST_FORCE;
584 if (strchr("!?@<", *argv[2])) {
585 while (*argv[2]) {
586 if (*argv[2] == '@') {
587 flags |= RUN_REQUEST_SILENT;
588 } else if (*argv[2] == '?') {
589 flags |= RUN_REQUEST_CONFIRM;
590 } else if (*argv[2] == '<') {
591 flags |= RUN_REQUEST_EXIT;
592 } else if (*argv[2] != '!') {
593 break;
595 argv[2]++;
598 } else if (*argv[2] == ':') {
599 argv[2]++;
600 flags |= RUN_REQUEST_INTERNAL;
602 } else {
603 return ERROR_UNKNOWN_REQUEST_NAME;
606 return add_run_request(keymap, key, argv + 2, flags)
607 ? SUCCESS : ERROR_OUT_OF_MEMORY;
610 add_keybinding(keymap, request, key);
612 return SUCCESS;
616 static enum status_code load_option_file(const char *path);
618 static enum status_code
619 option_source_command(int argc, const char *argv[])
621 if (argc < 1)
622 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
624 return load_option_file(argv[0]);
627 static enum status_code
628 set_option(const char *opt, char *value)
630 const char *argv[SIZEOF_ARG];
631 int argc = 0;
633 if (!argv_from_string(argv, &argc, value))
634 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
636 if (!strcmp(opt, "color"))
637 return option_color_command(argc, argv);
639 if (!strcmp(opt, "set"))
640 return option_set_command(argc, argv);
642 if (!strcmp(opt, "bind"))
643 return option_bind_command(argc, argv);
645 if (!strcmp(opt, "source"))
646 return option_source_command(argc, argv);
648 return ERROR_UNKNOWN_OPTION_COMMAND;
651 struct config_state {
652 const char *path;
653 int lineno;
654 bool errors;
657 static int
658 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
660 struct config_state *config = data;
661 enum status_code status = ERROR_NO_OPTION_VALUE;
663 config->lineno++;
665 /* Check for comment markers, since read_properties() will
666 * only ensure opt and value are split at first " \t". */
667 optlen = strcspn(opt, "#");
668 if (optlen == 0)
669 return OK;
671 if (opt[optlen] == 0) {
672 /* Look for comment endings in the value. */
673 size_t len = strcspn(value, "#");
675 if (len < valuelen) {
676 valuelen = len;
677 value[valuelen] = 0;
680 status = set_option(opt, value);
683 if (status != SUCCESS) {
684 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
685 get_status_message(status), (int) optlen, opt);
686 config->errors = TRUE;
689 /* Always keep going if errors are encountered. */
690 return OK;
693 static enum status_code
694 load_option_file(const char *path)
696 struct config_state config = { path, 0, FALSE };
697 struct io io;
698 char buf[SIZEOF_STR];
700 /* Do not read configuration from stdin if set to "" */
701 if (!path || !strlen(path))
702 return SUCCESS;
704 if (!prefixcmp(path, "~/")) {
705 const char *home = getenv("HOME");
707 if (!home || !string_format(buf, "%s/%s", home, path + 2))
708 return ERROR_HOME_UNRESOLVABLE;
709 path = buf;
712 /* It's OK that the file doesn't exist. */
713 if (!io_open(&io, "%s", path))
714 return ERROR_FILE_DOES_NOT_EXIST;
716 if (io_load(&io, " \t", read_option, &config) == ERR ||
717 config.errors == TRUE)
718 warn("Errors while loading %s.", path);
719 return SUCCESS;
722 extern const char *builtin_config;
724 static int
725 load_options(void)
727 const char *tigrc_user = getenv("TIGRC_USER");
728 const char *tigrc_system = getenv("TIGRC_SYSTEM");
729 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
730 const bool diff_opts_from_args = !!opt_diff_argv;
731 bool custom_tigrc_system = !!tigrc_system;
733 if (!custom_tigrc_system)
734 tigrc_system = SYSCONFDIR "/tigrc";
736 if (load_option_file(tigrc_system) == ERROR_FILE_DOES_NOT_EXIST && !custom_tigrc_system) {
737 struct config_state config = { "<built-in>", 0, FALSE };
738 struct io io;
740 if (!io_from_string(&io, builtin_config) ||
741 !io_load(&io, " \t", read_option, &config) == ERR ||
742 config.errors == TRUE)
743 die("Error in built-in config");
746 if (!tigrc_user)
747 tigrc_user = "~/.tigrc";
748 load_option_file(tigrc_user);
750 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
751 static const char *diff_opts[SIZEOF_ARG] = { NULL };
752 char buf[SIZEOF_STR];
753 int argc = 0;
755 if (!string_format(buf, "%s", tig_diff_opts) ||
756 !argv_from_string(diff_opts, &argc, buf))
757 die("TIG_DIFF_OPTS contains too many arguments");
758 else if (!argv_copy(&opt_diff_argv, diff_opts))
759 die("Failed to format TIG_DIFF_OPTS arguments");
762 return OK;
767 * The viewer
770 struct view;
771 struct view_ops;
773 /* The display array of active views and the index of the current view. */
774 static struct view *display[2];
775 static WINDOW *display_win[2];
776 static WINDOW *display_title[2];
777 static WINDOW *display_sep;
779 static unsigned int current_view;
781 #define foreach_displayed_view(view, i) \
782 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
784 #define displayed_views() (display[1] != NULL ? 2 : 1)
786 /* Current head and commit ID */
787 static char ref_blob[SIZEOF_REF] = "";
788 static char ref_commit[SIZEOF_REF] = "HEAD";
789 static char ref_head[SIZEOF_REF] = "HEAD";
790 static char ref_branch[SIZEOF_REF] = "";
791 static char ref_status[SIZEOF_STR] = "";
792 static char ref_stash[SIZEOF_REF] = "";
794 #define VIEW_OPS(id, name, ref) name##_ops
795 static struct view_ops VIEW_INFO(VIEW_OPS);
797 static struct view views[] = {
798 #define VIEW_DATA(id, name, ref) \
799 { #name, ref, &name##_ops }
800 VIEW_INFO(VIEW_DATA)
803 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
805 #define foreach_view(view, i) \
806 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
808 #define view_is_displayed(view) \
809 (view == display[0] || view == display[1])
811 #define view_has_line(view, line_) \
812 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
814 static bool
815 forward_request_to_child(struct view *child, enum request request)
817 return displayed_views() == 2 && view_is_displayed(child) &&
818 !strcmp(child->vid, child->id);
821 static enum request
822 view_request(struct view *view, enum request request)
824 if (!view || !view->lines)
825 return request;
827 if (request == REQ_ENTER && !opt_focus_child &&
828 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
829 struct view *child = display[1];
831 if (forward_request_to_child(child, request)) {
832 view_request(child, request);
833 return REQ_NONE;
837 if (request == REQ_REFRESH && view->unrefreshable) {
838 report("This view can not be refreshed");
839 return REQ_NONE;
842 return view->ops->request(view, request, &view->line[view->pos.lineno]);
846 * View drawing.
849 static inline void
850 set_view_attr(struct view *view, enum line_type type)
852 if (!view->curline->selected && view->curtype != type) {
853 (void) wattrset(view->win, get_line_attr(type));
854 wchgat(view->win, -1, 0, get_line_color(type), NULL);
855 view->curtype = type;
859 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
861 static bool
862 draw_chars(struct view *view, enum line_type type, const char *string,
863 int max_len, bool use_tilde)
865 int len = 0;
866 int col = 0;
867 int trimmed = FALSE;
868 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
870 if (max_len <= 0)
871 return VIEW_MAX_LEN(view) <= 0;
873 if (opt_iconv_out != ICONV_NONE) {
874 string = encoding_iconv(opt_iconv_out, string);
875 if (!string)
876 return VIEW_MAX_LEN(view) <= 0;
879 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
881 set_view_attr(view, type);
882 if (len > 0) {
883 waddnstr(view->win, string, len);
885 if (trimmed && use_tilde) {
886 set_view_attr(view, LINE_DELIMITER);
887 waddch(view->win, '~');
888 col++;
892 view->col += col;
893 return VIEW_MAX_LEN(view) <= 0;
896 static bool
897 draw_space(struct view *view, enum line_type type, int max, int spaces)
899 static char space[] = " ";
901 spaces = MIN(max, spaces);
903 while (spaces > 0) {
904 int len = MIN(spaces, sizeof(space) - 1);
906 if (draw_chars(view, type, space, len, FALSE))
907 return TRUE;
908 spaces -= len;
911 return VIEW_MAX_LEN(view) <= 0;
914 static bool
915 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
917 static char text[SIZEOF_STR];
919 do {
920 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
922 if (draw_chars(view, type, text, max_len, use_tilde))
923 return TRUE;
924 string += pos;
925 } while (*string);
927 return VIEW_MAX_LEN(view) <= 0;
930 static bool
931 draw_text(struct view *view, enum line_type type, const char *string)
933 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
936 static bool
937 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
939 if (on) {
940 int max = MIN(VIEW_MAX_LEN(view), overflow);
941 int len = strlen(text);
943 if (draw_text_expanded(view, type, text, max, max < overflow))
944 return TRUE;
946 text = len > overflow ? text + overflow : "";
947 type = LINE_OVERFLOW;
950 if (*text && draw_text(view, type, text))
951 return TRUE;
953 return VIEW_MAX_LEN(view) <= 0;
956 #define draw_commit_title(view, text, offset) \
957 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
959 static bool PRINTF_LIKE(3, 4)
960 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
962 char text[SIZEOF_STR];
963 int retval;
965 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
966 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
969 static bool
970 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
972 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
973 int max = VIEW_MAX_LEN(view);
974 int i;
976 if (max < size)
977 size = max;
979 set_view_attr(view, type);
980 /* Using waddch() instead of waddnstr() ensures that
981 * they'll be rendered correctly for the cursor line. */
982 for (i = skip; i < size; i++)
983 waddch(view->win, graphic[i]);
985 view->col += size;
986 if (separator) {
987 if (size < max && skip <= size)
988 waddch(view->win, ' ');
989 view->col++;
992 return VIEW_MAX_LEN(view) <= 0;
995 enum align {
996 ALIGN_LEFT,
997 ALIGN_RIGHT
1000 static bool
1001 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
1003 int max = MIN(VIEW_MAX_LEN(view), width + 1);
1004 int col = view->col;
1006 if (!text)
1007 return draw_space(view, type, max, max);
1009 if (align == ALIGN_RIGHT) {
1010 int textlen = strlen(text);
1011 int leftpad = max - textlen - 1;
1013 if (leftpad > 0) {
1014 if (draw_space(view, type, leftpad, leftpad))
1015 return TRUE;
1016 max -= leftpad;
1017 col += leftpad;;
1021 return draw_chars(view, type, text, max - 1, trim)
1022 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1025 static bool
1026 draw_date(struct view *view, struct time *time)
1028 const char *date = mkdate(time, opt_date);
1029 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
1031 if (opt_date == DATE_NO)
1032 return FALSE;
1034 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
1037 static bool
1038 draw_author(struct view *view, const struct ident *author)
1040 bool trim = author_trim(opt_author_width);
1041 const char *text = mkauthor(author, opt_author_width, opt_author);
1043 if (opt_author == AUTHOR_NO)
1044 return FALSE;
1046 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
1049 static bool
1050 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
1052 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
1055 static bool
1056 draw_id(struct view *view, const char *id)
1058 if (!opt_show_id)
1059 return FALSE;
1061 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
1064 static bool
1065 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1067 bool trim = filename && strlen(filename) >= opt_filename_width;
1069 if (opt_filename == FILENAME_NO)
1070 return FALSE;
1072 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1073 return FALSE;
1075 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
1078 static bool
1079 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
1081 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
1083 if (!width || opt_file_size == FILE_SIZE_NO)
1084 return FALSE;
1086 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
1089 static bool
1090 draw_mode(struct view *view, mode_t mode)
1092 const char *str = mkmode(mode);
1094 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
1097 static bool
1098 draw_lineno(struct view *view, unsigned int lineno)
1100 char number[10];
1101 int digits3 = view->digits < 3 ? 3 : view->digits;
1102 int max = MIN(VIEW_MAX_LEN(view), digits3);
1103 char *text = NULL;
1104 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1106 if (!opt_line_number)
1107 return FALSE;
1109 lineno += view->pos.offset + 1;
1110 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1111 static char fmt[] = "%1ld";
1113 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1114 if (string_format(number, fmt, lineno))
1115 text = number;
1117 if (text)
1118 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1119 else
1120 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1121 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1124 static bool
1125 draw_refs(struct view *view, struct ref_list *refs)
1127 size_t i;
1129 if (!opt_show_refs || !refs)
1130 return FALSE;
1132 for (i = 0; i < refs->size; i++) {
1133 struct ref *ref = refs->refs[i];
1134 enum line_type type = get_line_type_from_ref(ref);
1136 if (draw_formatted(view, type, "[%s]", ref->name))
1137 return TRUE;
1139 if (draw_text(view, LINE_DEFAULT, " "))
1140 return TRUE;
1143 return FALSE;
1146 static bool
1147 draw_view_line(struct view *view, unsigned int lineno)
1149 struct line *line;
1150 bool selected = (view->pos.offset + lineno == view->pos.lineno);
1152 assert(view_is_displayed(view));
1154 if (view->pos.offset + lineno >= view->lines)
1155 return FALSE;
1157 line = &view->line[view->pos.offset + lineno];
1159 wmove(view->win, lineno, 0);
1160 if (line->cleareol)
1161 wclrtoeol(view->win);
1162 view->col = 0;
1163 view->curline = line;
1164 view->curtype = LINE_NONE;
1165 line->selected = FALSE;
1166 line->dirty = line->cleareol = 0;
1168 if (selected) {
1169 set_view_attr(view, LINE_CURSOR);
1170 line->selected = TRUE;
1171 view->ops->select(view, line);
1174 return view->ops->draw(view, line, lineno);
1177 static void
1178 redraw_view_dirty(struct view *view)
1180 bool dirty = FALSE;
1181 int lineno;
1183 for (lineno = 0; lineno < view->height; lineno++) {
1184 if (view->pos.offset + lineno >= view->lines)
1185 break;
1186 if (!view->line[view->pos.offset + lineno].dirty)
1187 continue;
1188 dirty = TRUE;
1189 if (!draw_view_line(view, lineno))
1190 break;
1193 if (!dirty)
1194 return;
1195 wnoutrefresh(view->win);
1198 static void
1199 redraw_view_from(struct view *view, int lineno)
1201 assert(0 <= lineno && lineno < view->height);
1203 for (; lineno < view->height; lineno++) {
1204 if (!draw_view_line(view, lineno))
1205 break;
1208 wnoutrefresh(view->win);
1211 static void
1212 redraw_view(struct view *view)
1214 werase(view->win);
1215 redraw_view_from(view, 0);
1219 static void
1220 update_view_title(struct view *view)
1222 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1223 struct line *line = &view->line[view->pos.lineno];
1224 unsigned int view_lines, lines;
1226 assert(view_is_displayed(view));
1228 if (view == display[current_view])
1229 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1230 else
1231 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1233 werase(window);
1234 mvwprintw(window, 0, 0, "[%s]", view->name);
1236 if (*view->ref) {
1237 wprintw(window, " %s", view->ref);
1240 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
1241 line->lineno) {
1242 wprintw(window, " - %s %d of %zd",
1243 view->ops->type,
1244 line->lineno,
1245 view->lines - view->custom_lines);
1248 if (view->pipe) {
1249 time_t secs = time(NULL) - view->start_time;
1251 /* Three git seconds are a long time ... */
1252 if (secs > 2)
1253 wprintw(window, " loading %lds", secs);
1256 view_lines = view->pos.offset + view->height;
1257 lines = view->lines ? MIN(view_lines, view->lines) * 100 / view->lines : 0;
1258 mvwprintw(window, 0, view->width - count_digits(lines) - 1, "%d%%", lines);
1260 wnoutrefresh(window);
1263 static int
1264 apply_step(double step, int value)
1266 if (step >= 1)
1267 return (int) step;
1268 value *= step + 0.01;
1269 return value ? value : 1;
1272 static void
1273 apply_horizontal_split(struct view *base, struct view *view)
1275 view->width = base->width;
1276 view->height = apply_step(opt_scale_split_view, base->height);
1277 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1278 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1279 base->height -= view->height;
1282 static void
1283 apply_vertical_split(struct view *base, struct view *view)
1285 view->height = base->height;
1286 view->width = apply_step(opt_scale_vsplit_view, base->width);
1287 view->width = MAX(view->width, MIN_VIEW_WIDTH);
1288 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
1289 base->width -= view->width;
1292 static void
1293 redraw_display_separator(bool clear)
1295 if (displayed_views() > 1 && vertical_split_is_enabled()) {
1296 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1298 if (clear)
1299 wclear(display_sep);
1300 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
1301 wnoutrefresh(display_sep);
1305 static void
1306 resize_display(void)
1308 int x, y, i;
1309 struct view *base = display[0];
1310 struct view *view = display[1] ? display[1] : display[0];
1311 bool vsplit;
1313 /* Setup window dimensions */
1315 getmaxyx(stdscr, base->height, base->width);
1316 string_format(opt_env_columns, "COLUMNS=%d", base->width);
1317 string_format(opt_env_lines, "LINES=%d", base->height);
1319 /* Make room for the status window. */
1320 base->height -= 1;
1322 vsplit = vertical_split_is_enabled();
1324 if (view != base) {
1325 if (vsplit) {
1326 apply_vertical_split(base, view);
1328 /* Make room for the separator bar. */
1329 view->width -= 1;
1330 } else {
1331 apply_horizontal_split(base, view);
1334 /* Make room for the title bar. */
1335 view->height -= 1;
1338 /* Make room for the title bar. */
1339 base->height -= 1;
1341 x = y = 0;
1343 foreach_displayed_view (view, i) {
1344 if (!display_win[i]) {
1345 display_win[i] = newwin(view->height, view->width, y, x);
1346 if (!display_win[i])
1347 die("Failed to create %s view", view->name);
1349 scrollok(display_win[i], FALSE);
1351 display_title[i] = newwin(1, view->width, y + view->height, x);
1352 if (!display_title[i])
1353 die("Failed to create title window");
1355 } else {
1356 wresize(display_win[i], view->height, view->width);
1357 mvwin(display_win[i], y, x);
1358 wresize(display_title[i], 1, view->width);
1359 mvwin(display_title[i], y + view->height, x);
1362 if (i > 0 && vsplit) {
1363 if (!display_sep) {
1364 display_sep = newwin(view->height, 1, 0, x - 1);
1365 if (!display_sep)
1366 die("Failed to create separator window");
1368 } else {
1369 wresize(display_sep, view->height, 1);
1370 mvwin(display_sep, 0, x - 1);
1374 view->win = display_win[i];
1376 if (vsplit)
1377 x += view->width + 1;
1378 else
1379 y += view->height + 1;
1382 redraw_display_separator(FALSE);
1385 static void
1386 redraw_display(bool clear)
1388 struct view *view;
1389 int i;
1391 foreach_displayed_view (view, i) {
1392 if (clear)
1393 wclear(view->win);
1394 redraw_view(view);
1395 update_view_title(view);
1398 redraw_display_separator(clear);
1402 * Option management
1405 #define VIEW_FLAG_RESET_DISPLAY ((enum view_flag) -1)
1407 #define TOGGLE_MENU_INFO(_) \
1408 _(LINENO, '.', "line numbers", &opt_line_number, NULL, VIEW_NO_FLAGS), \
1409 _(DATE, 'D', "dates", &opt_date, date_map, VIEW_NO_FLAGS), \
1410 _(AUTHOR, 'A', "author", &opt_author, author_map, VIEW_NO_FLAGS), \
1411 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, VIEW_NO_FLAGS), \
1412 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, VIEW_LOG_LIKE), \
1413 _(FILENAME, '#', "file names", &opt_filename, filename_map, VIEW_NO_FLAGS), \
1414 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, VIEW_NO_FLAGS), \
1415 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, VIEW_DIFF_LIKE), \
1416 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, VIEW_LOG_LIKE), \
1417 _(REFS, 'F', "reference display", &opt_show_refs, NULL, VIEW_NO_FLAGS), \
1418 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, VIEW_NO_FLAGS), \
1419 _(ID, 'X', "commit ID display", &opt_show_id, NULL, VIEW_NO_FLAGS), \
1420 _(FILES, '%', "file filtering", &opt_file_filter, NULL, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
1421 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, VIEW_NO_FLAGS), \
1422 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, VIEW_STATUS_LIKE), \
1423 _(VERTICAL_SPLIT, '|', "view split", &opt_vertical_split, vertical_split_map, VIEW_FLAG_RESET_DISPLAY), \
1425 static enum view_flag
1426 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
1428 const struct {
1429 enum request request;
1430 const struct enum_map *map;
1431 enum view_flag reload_flags;
1432 } data[] = {
1433 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, vflags) { REQ_TOGGLE_ ## id, map, vflags }
1434 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
1436 const struct menu_item menu[] = {
1437 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, vflags) { key, help, value }
1438 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
1439 { 0 }
1441 int i = 0;
1443 if (request == REQ_OPTIONS) {
1444 if (!prompt_menu("Toggle option", menu, &i))
1445 return VIEW_NO_FLAGS;
1446 } else {
1447 while (i < ARRAY_SIZE(data) && data[i].request != request)
1448 i++;
1449 if (i >= ARRAY_SIZE(data))
1450 die("Invalid request (%d)", request);
1453 if (data[i].map != NULL) {
1454 unsigned int *opt = menu[i].data;
1456 *opt = (*opt + 1) % data[i].map->size;
1457 if (data[i].map == ignore_space_map) {
1458 update_ignore_space_arg();
1459 string_format_size(msg, SIZEOF_STR,
1460 "Ignoring %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
1462 } else if (data[i].map == commit_order_map) {
1463 update_commit_order_arg();
1464 string_format_size(msg, SIZEOF_STR,
1465 "Using %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
1467 } else {
1468 string_format_size(msg, SIZEOF_STR,
1469 "Displaying %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
1472 } else {
1473 bool *option = menu[i].data;
1475 *option = !*option;
1476 string_format_size(msg, SIZEOF_STR,
1477 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
1480 return data[i].reload_flags;
1485 * Navigation
1488 static bool
1489 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1491 if (lineno >= view->lines)
1492 lineno = view->lines > 0 ? view->lines - 1 : 0;
1494 if (offset > lineno || offset + view->height <= lineno) {
1495 unsigned long half = view->height / 2;
1497 if (lineno > half)
1498 offset = lineno - half;
1499 else
1500 offset = 0;
1503 if (offset != view->pos.offset || lineno != view->pos.lineno) {
1504 view->pos.offset = offset;
1505 view->pos.lineno = lineno;
1506 return TRUE;
1509 return FALSE;
1512 /* Scrolling backend */
1513 static void
1514 do_scroll_view(struct view *view, int lines)
1516 bool redraw_current_line = FALSE;
1518 /* The rendering expects the new offset. */
1519 view->pos.offset += lines;
1521 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
1522 assert(lines);
1524 /* Move current line into the view. */
1525 if (view->pos.lineno < view->pos.offset) {
1526 view->pos.lineno = view->pos.offset;
1527 redraw_current_line = TRUE;
1528 } else if (view->pos.lineno >= view->pos.offset + view->height) {
1529 view->pos.lineno = view->pos.offset + view->height - 1;
1530 redraw_current_line = TRUE;
1533 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
1535 /* Redraw the whole screen if scrolling is pointless. */
1536 if (view->height < ABS(lines)) {
1537 redraw_view(view);
1539 } else {
1540 int line = lines > 0 ? view->height - lines : 0;
1541 int end = line + ABS(lines);
1543 scrollok(view->win, TRUE);
1544 wscrl(view->win, lines);
1545 scrollok(view->win, FALSE);
1547 while (line < end && draw_view_line(view, line))
1548 line++;
1550 if (redraw_current_line)
1551 draw_view_line(view, view->pos.lineno - view->pos.offset);
1552 wnoutrefresh(view->win);
1555 view->has_scrolled = TRUE;
1556 report_clear();
1559 /* Scroll frontend */
1560 static void
1561 scroll_view(struct view *view, enum request request)
1563 int lines = 1;
1565 assert(view_is_displayed(view));
1567 if (request == REQ_SCROLL_WHEEL_DOWN || request == REQ_SCROLL_WHEEL_UP)
1568 lines = opt_scroll_wheel_lines;
1570 switch (request) {
1571 case REQ_SCROLL_FIRST_COL:
1572 view->pos.col = 0;
1573 redraw_view_from(view, 0);
1574 report_clear();
1575 return;
1576 case REQ_SCROLL_LEFT:
1577 if (view->pos.col == 0) {
1578 report("Cannot scroll beyond the first column");
1579 return;
1581 if (view->pos.col <= apply_step(opt_hscroll, view->width))
1582 view->pos.col = 0;
1583 else
1584 view->pos.col -= apply_step(opt_hscroll, view->width);
1585 redraw_view_from(view, 0);
1586 report_clear();
1587 return;
1588 case REQ_SCROLL_RIGHT:
1589 view->pos.col += apply_step(opt_hscroll, view->width);
1590 redraw_view(view);
1591 report_clear();
1592 return;
1593 case REQ_SCROLL_PAGE_DOWN:
1594 lines = view->height;
1595 case REQ_SCROLL_WHEEL_DOWN:
1596 case REQ_SCROLL_LINE_DOWN:
1597 if (view->pos.offset + lines > view->lines)
1598 lines = view->lines - view->pos.offset;
1600 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
1601 report("Cannot scroll beyond the last line");
1602 return;
1604 break;
1606 case REQ_SCROLL_PAGE_UP:
1607 lines = view->height;
1608 case REQ_SCROLL_LINE_UP:
1609 case REQ_SCROLL_WHEEL_UP:
1610 if (lines > view->pos.offset)
1611 lines = view->pos.offset;
1613 if (lines == 0) {
1614 report("Cannot scroll beyond the first line");
1615 return;
1618 lines = -lines;
1619 break;
1621 default:
1622 die("request %d not handled in switch", request);
1625 do_scroll_view(view, lines);
1628 /* Cursor moving */
1629 static void
1630 move_view(struct view *view, enum request request)
1632 int scroll_steps = 0;
1633 int steps;
1635 switch (request) {
1636 case REQ_MOVE_FIRST_LINE:
1637 steps = -view->pos.lineno;
1638 break;
1640 case REQ_MOVE_LAST_LINE:
1641 steps = view->lines - view->pos.lineno - 1;
1642 break;
1644 case REQ_MOVE_PAGE_UP:
1645 steps = view->height > view->pos.lineno
1646 ? -view->pos.lineno : -view->height;
1647 break;
1649 case REQ_MOVE_PAGE_DOWN:
1650 steps = view->pos.lineno + view->height >= view->lines
1651 ? view->lines - view->pos.lineno - 1 : view->height;
1652 break;
1654 case REQ_MOVE_UP:
1655 case REQ_PREVIOUS:
1656 steps = -1;
1657 break;
1659 case REQ_MOVE_DOWN:
1660 case REQ_NEXT:
1661 steps = 1;
1662 break;
1664 default:
1665 die("request %d not handled in switch", request);
1668 if (steps <= 0 && view->pos.lineno == 0) {
1669 report("Cannot move beyond the first line");
1670 return;
1672 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
1673 report("Cannot move beyond the last line");
1674 return;
1677 /* Move the current line */
1678 view->pos.lineno += steps;
1679 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
1681 /* Check whether the view needs to be scrolled */
1682 if (view->pos.lineno < view->pos.offset ||
1683 view->pos.lineno >= view->pos.offset + view->height) {
1684 scroll_steps = steps;
1685 if (steps < 0 && -steps > view->pos.offset) {
1686 scroll_steps = -view->pos.offset;
1688 } else if (steps > 0) {
1689 if (view->pos.lineno == view->lines - 1 &&
1690 view->lines > view->height) {
1691 scroll_steps = view->lines - view->pos.offset - 1;
1692 if (scroll_steps >= view->height)
1693 scroll_steps -= view->height - 1;
1698 if (!view_is_displayed(view)) {
1699 view->pos.offset += scroll_steps;
1700 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
1701 view->ops->select(view, &view->line[view->pos.lineno]);
1702 return;
1705 /* Repaint the old "current" line if we be scrolling */
1706 if (ABS(steps) < view->height)
1707 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
1709 if (scroll_steps) {
1710 do_scroll_view(view, scroll_steps);
1711 return;
1714 /* Draw the current line */
1715 draw_view_line(view, view->pos.lineno - view->pos.offset);
1717 wnoutrefresh(view->win);
1718 report_clear();
1723 * Searching
1726 static void search_view(struct view *view, enum request request);
1728 static bool
1729 grep_text(struct view *view, const char *text[])
1731 regmatch_t pmatch;
1732 size_t i;
1734 for (i = 0; text[i]; i++)
1735 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
1736 return TRUE;
1737 return FALSE;
1740 static void
1741 select_view_line(struct view *view, unsigned long lineno)
1743 struct position old = view->pos;
1745 if (goto_view_line(view, view->pos.offset, lineno)) {
1746 if (view_is_displayed(view)) {
1747 if (old.offset != view->pos.offset) {
1748 redraw_view(view);
1749 } else {
1750 draw_view_line(view, old.lineno - view->pos.offset);
1751 draw_view_line(view, view->pos.lineno - view->pos.offset);
1752 wnoutrefresh(view->win);
1754 } else {
1755 view->ops->select(view, &view->line[view->pos.lineno]);
1760 static void
1761 find_next(struct view *view, enum request request)
1763 unsigned long lineno = view->pos.lineno;
1764 int direction;
1766 if (!*view->grep) {
1767 if (!*opt_search)
1768 report("No previous search");
1769 else
1770 search_view(view, request);
1771 return;
1774 switch (request) {
1775 case REQ_SEARCH:
1776 case REQ_FIND_NEXT:
1777 direction = 1;
1778 break;
1780 case REQ_SEARCH_BACK:
1781 case REQ_FIND_PREV:
1782 direction = -1;
1783 break;
1785 default:
1786 return;
1789 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
1790 lineno += direction;
1792 /* Note, lineno is unsigned long so will wrap around in which case it
1793 * will become bigger than view->lines. */
1794 for (; lineno < view->lines; lineno += direction) {
1795 if (view->ops->grep(view, &view->line[lineno])) {
1796 select_view_line(view, lineno);
1797 report("Line %ld matches '%s'", lineno + 1, view->grep);
1798 return;
1802 report("No match found for '%s'", view->grep);
1805 static void
1806 search_view(struct view *view, enum request request)
1808 int regex_err;
1809 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
1811 if (view->regex) {
1812 regfree(view->regex);
1813 *view->grep = 0;
1814 } else {
1815 view->regex = calloc(1, sizeof(*view->regex));
1816 if (!view->regex)
1817 return;
1820 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
1821 if (regex_err != 0) {
1822 char buf[SIZEOF_STR] = "unknown error";
1824 regerror(regex_err, view->regex, buf, sizeof(buf));
1825 report("Search failed: %s", buf);
1826 return;
1829 string_copy(view->grep, opt_search);
1831 find_next(view, request);
1835 * Incremental updating
1838 static inline bool
1839 check_position(struct position *pos)
1841 return pos->lineno || pos->col || pos->offset;
1844 static inline void
1845 clear_position(struct position *pos)
1847 memset(pos, 0, sizeof(*pos));
1850 static void
1851 reset_view(struct view *view)
1853 int i;
1855 if (view->ops->done)
1856 view->ops->done(view);
1858 for (i = 0; i < view->lines; i++)
1859 free(view->line[i].data);
1860 free(view->line);
1862 view->prev_pos = view->pos;
1863 clear_position(&view->pos);
1865 view->line = NULL;
1866 view->lines = 0;
1867 view->vid[0] = 0;
1868 view->custom_lines = 0;
1869 view->update_secs = 0;
1872 struct format_context {
1873 struct view *view;
1874 char buf[SIZEOF_STR];
1875 size_t bufpos;
1876 bool file_filter;
1879 static bool
1880 format_expand_arg(struct format_context *format, const char *name, const char *end)
1882 static struct {
1883 const char *name;
1884 size_t namelen;
1885 const char *value;
1886 const char *value_if_empty;
1887 } vars[] = {
1888 #define FORMAT_VAR(name, value, value_if_empty) \
1889 { name, STRING_SIZE(name), value, value_if_empty }
1890 FORMAT_VAR("%(directory)", opt_path, "."),
1891 FORMAT_VAR("%(file)", opt_file, ""),
1892 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
1893 FORMAT_VAR("%(head)", ref_head, ""),
1894 FORMAT_VAR("%(commit)", ref_commit, ""),
1895 FORMAT_VAR("%(blob)", ref_blob, ""),
1896 FORMAT_VAR("%(branch)", ref_branch, ""),
1897 FORMAT_VAR("%(stash)", ref_stash, ""),
1899 int i;
1901 if (!prefixcmp(name, "%(prompt")) {
1902 const char *prompt = "Command argument: ";
1903 char msgbuf[SIZEOF_STR];
1904 const char *value;
1905 const char *msgstart = name + STRING_SIZE("%(prompt");
1906 int msglen = end - msgstart - 1;
1908 if (end && msglen > 0 && string_format(msgbuf, "%.*s", msglen, msgstart)) {
1909 const char *msg = msgbuf;
1911 while (isspace(*msg))
1912 msg++;
1913 if (*msg)
1914 prompt = msg;
1917 value = read_prompt(prompt);
1918 if (value == NULL)
1919 return FALSE;
1920 return string_format_from(format->buf, &format->bufpos, "%s", value);
1923 for (i = 0; i < ARRAY_SIZE(vars); i++) {
1924 const char *value;
1926 if (strncmp(name, vars[i].name, vars[i].namelen))
1927 continue;
1929 if (vars[i].value == opt_file && !format->file_filter)
1930 return TRUE;
1932 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
1933 if (!*value)
1934 return TRUE;
1936 return string_format_from(format->buf, &format->bufpos, "%s", value);
1939 report("Unknown replacement: `%s`", name);
1940 return FALSE;
1943 static bool
1944 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
1946 memset(format->buf, 0, sizeof(format->buf));
1947 format->bufpos = 0;
1949 while (arg) {
1950 char *var = strstr(arg, "%(");
1951 int len = var ? var - arg : strlen(arg);
1952 char *next = var ? strchr(var, ')') + 1 : NULL;
1954 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
1955 return FALSE;
1957 if (var && !format_expand_arg(format, var, next))
1958 return FALSE;
1960 arg = next;
1963 return argv_append(dst_argv, format->buf);
1966 static bool
1967 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
1969 int argc;
1971 if (!src_argv)
1972 return TRUE;
1974 for (argc = 0; src_argv[argc]; argc++)
1975 if (!format_append_arg(format, dst_argv, src_argv[argc]))
1976 return FALSE;
1978 return src_argv[argc] == NULL;
1981 static bool
1982 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
1984 struct format_context format = { view, "", 0, file_filter };
1985 int argc;
1987 argv_free(*dst_argv);
1989 for (argc = 0; src_argv[argc]; argc++) {
1990 const char *arg = src_argv[argc];
1992 if (!strcmp(arg, "%(fileargs)")) {
1993 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
1994 break;
1996 } else if (!strcmp(arg, "%(diffargs)")) {
1997 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
1998 break;
2000 } else if (!strcmp(arg, "%(blameargs)")) {
2001 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
2002 break;
2004 } else if (!strcmp(arg, "%(cmdlineargs)")) {
2005 if (!format_append_argv(&format, dst_argv, opt_cmdline_argv))
2006 break;
2008 } else if (!strcmp(arg, "%(revargs)") ||
2009 (first && !strcmp(arg, "%(commit)"))) {
2010 if (!argv_append_array(dst_argv, opt_rev_argv))
2011 break;
2013 } else if (!format_append_arg(&format, dst_argv, arg)) {
2014 break;
2018 return src_argv[argc] == NULL;
2021 static bool
2022 restore_view_position(struct view *view)
2024 /* A view without a previous view is the first view */
2025 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2026 select_view_line(view, opt_lineno - 1);
2027 opt_lineno = 0;
2030 /* Ensure that the view position is in a valid state. */
2031 if (!check_position(&view->prev_pos) ||
2032 (view->pipe && view->lines <= view->prev_pos.lineno))
2033 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2035 /* Changing the view position cancels the restoring. */
2036 /* FIXME: Changing back to the first line is not detected. */
2037 if (check_position(&view->pos)) {
2038 clear_position(&view->prev_pos);
2039 return FALSE;
2042 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2043 view_is_displayed(view))
2044 werase(view->win);
2046 view->pos.col = view->prev_pos.col;
2047 clear_position(&view->prev_pos);
2049 return TRUE;
2052 static void
2053 end_update(struct view *view, bool force)
2055 if (!view->pipe)
2056 return;
2057 while (!view->ops->read(view, NULL))
2058 if (!force)
2059 return;
2060 if (force)
2061 io_kill(view->pipe);
2062 io_done(view->pipe);
2063 view->pipe = NULL;
2066 static void
2067 setup_update(struct view *view, const char *vid)
2069 reset_view(view);
2070 /* XXX: Do not use string_copy_rev(), it copies until first space. */
2071 string_ncopy(view->vid, vid, strlen(vid));
2072 view->pipe = &view->io;
2073 view->start_time = time(NULL);
2076 static bool
2077 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2079 bool extra = !!(flags & (OPEN_EXTRA));
2080 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
2081 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
2082 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
2083 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
2085 if ((!reload && !strcmp(view->vid, view->id)) ||
2086 ((flags & OPEN_REFRESH) && view->unrefreshable))
2087 return TRUE;
2089 if (view->pipe) {
2090 if (extra)
2091 io_done(view->pipe);
2092 else
2093 end_update(view, TRUE);
2096 view->unrefreshable = open_in_pager_mode(flags);
2098 if (!refresh && argv) {
2099 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
2101 view->dir = dir;
2102 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
2103 report("Failed to format %s arguments", view->name);
2104 return FALSE;
2107 /* Put the current ref_* value to the view title ref
2108 * member. This is needed by the blob view. Most other
2109 * views sets it automatically after loading because the
2110 * first line is a commit line. */
2111 string_copy_rev(view->ref, view->id);
2114 if (view->argv && view->argv[0] &&
2115 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
2116 report("Failed to open %s view", view->name);
2117 return FALSE;
2120 if (open_from_stdin(flags)) {
2121 if (!io_open(&view->io, "%s", ""))
2122 die("Failed to open stdin");
2125 if (!extra)
2126 setup_update(view, view->id);
2128 return TRUE;
2131 static bool
2132 update_view(struct view *view)
2134 char *line;
2135 /* Clear the view and redraw everything since the tree sorting
2136 * might have rearranged things. */
2137 bool redraw = view->lines == 0;
2138 bool can_read = TRUE;
2139 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
2141 if (!view->pipe)
2142 return TRUE;
2144 if (!io_can_read(view->pipe, FALSE)) {
2145 if (view->lines == 0 && view_is_displayed(view)) {
2146 time_t secs = time(NULL) - view->start_time;
2148 if (secs > 1 && secs > view->update_secs) {
2149 if (view->update_secs == 0)
2150 redraw_view(view);
2151 update_view_title(view);
2152 view->update_secs = secs;
2155 return TRUE;
2158 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2159 if (encoding) {
2160 line = encoding_convert(encoding, line);
2163 if (!view->ops->read(view, line)) {
2164 report("Allocation failure");
2165 end_update(view, TRUE);
2166 return FALSE;
2171 int digits = count_digits(view->lines);
2173 /* Keep the displayed view in sync with line number scaling. */
2174 if (digits != view->digits) {
2175 view->digits = digits;
2176 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2177 redraw = TRUE;
2181 if (io_error(view->pipe)) {
2182 report("Failed to read: %s", io_strerror(view->pipe));
2183 end_update(view, TRUE);
2185 } else if (io_eof(view->pipe)) {
2186 end_update(view, FALSE);
2189 if (restore_view_position(view))
2190 redraw = TRUE;
2192 if (!view_is_displayed(view))
2193 return TRUE;
2195 if (redraw || view->force_redraw)
2196 redraw_view_from(view, 0);
2197 else
2198 redraw_view_dirty(view);
2199 view->force_redraw = FALSE;
2201 /* Update the title _after_ the redraw so that if the redraw picks up a
2202 * commit reference in view->ref it'll be available here. */
2203 update_view_title(view);
2204 return TRUE;
2207 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2209 static struct line *
2210 add_line_at(struct view *view, unsigned long pos, const void *data, enum line_type type, size_t data_size, bool custom)
2212 struct line *line;
2213 unsigned long lineno;
2215 if (!realloc_lines(&view->line, view->lines, 1))
2216 return NULL;
2218 if (data_size) {
2219 void *alloc_data = calloc(1, data_size);
2221 if (!alloc_data)
2222 return NULL;
2224 if (data)
2225 memcpy(alloc_data, data, data_size);
2226 data = alloc_data;
2229 if (pos < view->lines) {
2230 view->lines++;
2231 line = view->line + pos;
2232 lineno = line->lineno;
2234 memmove(line + 1, line, (view->lines - pos) * sizeof(*view->line));
2235 while (pos < view->lines) {
2236 view->line[pos].lineno++;
2237 view->line[pos++].dirty = 1;
2239 } else {
2240 line = &view->line[view->lines++];
2241 lineno = view->lines - view->custom_lines;
2244 memset(line, 0, sizeof(*line));
2245 line->type = type;
2246 line->data = (void *) data;
2247 line->dirty = 1;
2249 if (custom)
2250 view->custom_lines++;
2251 else
2252 line->lineno = lineno;
2254 return line;
2257 static struct line *
2258 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
2260 return add_line_at(view, view->lines, data, type, data_size, custom);
2263 static struct line *
2264 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
2266 struct line *line = add_line(view, NULL, type, data_size, custom);
2268 if (line)
2269 *ptr = line->data;
2270 return line;
2273 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
2274 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
2276 static struct line *
2277 add_line_nodata(struct view *view, enum line_type type)
2279 return add_line(view, NULL, type, 0, FALSE);
2282 static struct line *
2283 add_line_text(struct view *view, const char *text, enum line_type type)
2285 return add_line(view, text, type, strlen(text) + 1, FALSE);
2288 static struct line * PRINTF_LIKE(3, 4)
2289 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2291 char buf[SIZEOF_STR];
2292 int retval;
2294 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2295 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2299 * View opening
2302 static void
2303 split_view(struct view *prev, struct view *view)
2305 display[1] = view;
2306 current_view = opt_focus_child ? 1 : 0;
2307 view->parent = prev;
2308 resize_display();
2310 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
2311 /* Take the title line into account. */
2312 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
2314 /* Scroll the view that was split if the current line is
2315 * outside the new limited view. */
2316 do_scroll_view(prev, lines);
2319 if (view != prev && view_is_displayed(prev)) {
2320 /* "Blur" the previous view. */
2321 update_view_title(prev);
2325 static void
2326 maximize_view(struct view *view, bool redraw)
2328 memset(display, 0, sizeof(display));
2329 current_view = 0;
2330 display[current_view] = view;
2331 resize_display();
2332 if (redraw) {
2333 redraw_display(FALSE);
2334 report_clear();
2338 static void
2339 load_view(struct view *view, struct view *prev, enum open_flags flags)
2341 if (view->pipe)
2342 end_update(view, TRUE);
2343 if (view->ops->private_size) {
2344 if (!view->private)
2345 view->private = calloc(1, view->ops->private_size);
2346 else
2347 memset(view->private, 0, view->ops->private_size);
2350 /* When prev == view it means this is the first loaded view. */
2351 if (prev && view != prev) {
2352 view->prev = prev;
2355 if (!view->ops->open(view, flags))
2356 return;
2358 if (prev) {
2359 bool split = !!(flags & OPEN_SPLIT);
2361 if (split) {
2362 split_view(prev, view);
2363 } else {
2364 maximize_view(view, FALSE);
2368 restore_view_position(view);
2370 if (view->pipe && view->lines == 0) {
2371 /* Clear the old view and let the incremental updating refill
2372 * the screen. */
2373 werase(view->win);
2374 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
2375 clear_position(&view->prev_pos);
2376 report_clear();
2377 } else if (view_is_displayed(view)) {
2378 redraw_view(view);
2379 report_clear();
2383 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
2384 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
2386 static void
2387 open_view(struct view *prev, enum request request, enum open_flags flags)
2389 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2390 struct view *view = VIEW(request);
2391 int nviews = displayed_views();
2393 assert(flags ^ OPEN_REFRESH);
2395 if (view == prev && nviews == 1 && !reload) {
2396 report("Already in %s view", view->name);
2397 return;
2400 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !repo.git_dir[0]) {
2401 report("The %s view is disabled in pager view", view->name);
2402 return;
2405 load_view(view, prev ? prev : view, flags);
2408 static void
2409 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2411 enum request request = view - views + REQ_OFFSET + 1;
2413 if (view->pipe)
2414 end_update(view, TRUE);
2415 view->dir = dir;
2417 if (!argv_copy(&view->argv, argv)) {
2418 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2419 } else {
2420 open_view(prev, request, flags | OPEN_PREPARED);
2424 static bool
2425 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
2427 bool ok;
2429 def_prog_mode(); /* save current tty modes */
2430 endwin(); /* restore original tty modes */
2431 ok = io_run_fg(argv, dir);
2432 if (confirm) {
2433 if (!ok && *notice)
2434 fprintf(stderr, "%s", notice);
2435 fprintf(stderr, "Press Enter to continue");
2436 getc(opt_tty);
2438 reset_prog_mode();
2439 redraw_display(TRUE);
2440 return ok;
2443 static void
2444 open_mergetool(const char *file)
2446 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2448 open_external_viewer(mergetool_argv, repo.cdup, TRUE, "");
2451 #define EDITOR_LINENO_MSG \
2452 "*** Your editor reported an error while opening the file.\n" \
2453 "*** This is probably because it doesn't support the line\n" \
2454 "*** number argument added automatically. The line number\n" \
2455 "*** has been disabled for now. You can permanently disable\n" \
2456 "*** it by adding the following line to ~/.tigrc\n" \
2457 "*** set editor-line-number = no\n"
2459 static void
2460 open_editor(const char *file, unsigned int lineno)
2462 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
2463 char editor_cmd[SIZEOF_STR];
2464 char lineno_cmd[SIZEOF_STR];
2465 const char *editor;
2466 int argc = 0;
2468 editor = getenv("GIT_EDITOR");
2469 if (!editor && *opt_editor)
2470 editor = opt_editor;
2471 if (!editor)
2472 editor = getenv("VISUAL");
2473 if (!editor)
2474 editor = getenv("EDITOR");
2475 if (!editor)
2476 editor = "vi";
2478 string_ncopy(editor_cmd, editor, strlen(editor));
2479 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
2480 report("Failed to read editor command");
2481 return;
2484 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
2485 editor_argv[argc++] = lineno_cmd;
2486 editor_argv[argc] = file;
2487 if (!open_external_viewer(editor_argv, repo.cdup, TRUE, EDITOR_LINENO_MSG))
2488 opt_editor_lineno = FALSE;
2491 static enum request run_prompt_command(struct view *view, char *cmd);
2493 static enum request
2494 open_run_request(struct view *view, enum request request)
2496 struct run_request *req = get_run_request(request);
2497 const char **argv = NULL;
2498 bool confirmed = FALSE;
2500 request = REQ_NONE;
2502 if (!req) {
2503 report("Unknown run request");
2504 return request;
2507 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
2508 if (req->internal) {
2509 char cmd[SIZEOF_STR];
2511 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
2512 request = run_prompt_command(view, cmd);
2515 else {
2516 confirmed = !req->confirm;
2518 if (req->confirm) {
2519 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
2520 const char *and_exit = req->exit ? " and exit" : "";
2522 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
2523 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
2524 prompt_yesno(prompt)) {
2525 confirmed = TRUE;
2529 if (confirmed && argv_remove_quotes(argv)) {
2530 if (req->silent)
2531 io_run_bg(argv);
2532 else
2533 open_external_viewer(argv, NULL, !req->exit, "");
2538 if (argv)
2539 argv_free(argv);
2540 free(argv);
2542 if (request == REQ_NONE) {
2543 if (req->confirm && !confirmed)
2544 request = REQ_NONE;
2546 else if (req->exit)
2547 request = REQ_QUIT;
2549 else if (view_has_flags(view, VIEW_REFRESH) && !view->unrefreshable)
2550 request = REQ_REFRESH;
2552 return request;
2556 * User request switch noodle
2559 static int
2560 view_driver(struct view *view, enum request request)
2562 int i;
2564 if (request == REQ_NONE)
2565 return TRUE;
2567 if (request >= REQ_RUN_REQUESTS) {
2568 request = open_run_request(view, request);
2570 // exit quickly rather than going through view_request and back
2571 if (request == REQ_QUIT)
2572 return FALSE;
2575 request = view_request(view, request);
2576 if (request == REQ_NONE)
2577 return TRUE;
2579 switch (request) {
2580 case REQ_MOVE_UP:
2581 case REQ_MOVE_DOWN:
2582 case REQ_MOVE_PAGE_UP:
2583 case REQ_MOVE_PAGE_DOWN:
2584 case REQ_MOVE_FIRST_LINE:
2585 case REQ_MOVE_LAST_LINE:
2586 move_view(view, request);
2587 break;
2589 case REQ_SCROLL_FIRST_COL:
2590 case REQ_SCROLL_LEFT:
2591 case REQ_SCROLL_RIGHT:
2592 case REQ_SCROLL_LINE_DOWN:
2593 case REQ_SCROLL_LINE_UP:
2594 case REQ_SCROLL_PAGE_DOWN:
2595 case REQ_SCROLL_PAGE_UP:
2596 case REQ_SCROLL_WHEEL_DOWN:
2597 case REQ_SCROLL_WHEEL_UP:
2598 scroll_view(view, request);
2599 break;
2601 case REQ_VIEW_MAIN:
2602 case REQ_VIEW_DIFF:
2603 case REQ_VIEW_LOG:
2604 case REQ_VIEW_TREE:
2605 case REQ_VIEW_HELP:
2606 case REQ_VIEW_BRANCH:
2607 case REQ_VIEW_BLAME:
2608 case REQ_VIEW_BLOB:
2609 case REQ_VIEW_STATUS:
2610 case REQ_VIEW_STAGE:
2611 case REQ_VIEW_PAGER:
2612 case REQ_VIEW_STASH:
2613 open_view(view, request, OPEN_DEFAULT);
2614 break;
2616 case REQ_NEXT:
2617 case REQ_PREVIOUS:
2618 if (view->parent) {
2619 int line;
2621 view = view->parent;
2622 line = view->pos.lineno;
2623 view_request(view, request);
2624 move_view(view, request);
2625 if (view_is_displayed(view))
2626 update_view_title(view);
2627 if (line != view->pos.lineno)
2628 view_request(view, REQ_ENTER);
2629 } else {
2630 move_view(view, request);
2632 break;
2634 case REQ_VIEW_NEXT:
2636 int nviews = displayed_views();
2637 int next_view = (current_view + 1) % nviews;
2639 if (next_view == current_view) {
2640 report("Only one view is displayed");
2641 break;
2644 current_view = next_view;
2645 /* Blur out the title of the previous view. */
2646 update_view_title(view);
2647 report_clear();
2648 break;
2650 case REQ_REFRESH:
2651 report("Refreshing is not supported by the %s view", view->name);
2652 break;
2654 case REQ_PARENT:
2655 report("Moving to parent is not supported by the the %s view", view->name);
2656 break;
2658 case REQ_BACK:
2659 report("Going back is not supported for by %s view", view->name);
2660 break;
2662 case REQ_MAXIMIZE:
2663 if (displayed_views() == 2)
2664 maximize_view(view, TRUE);
2665 break;
2667 case REQ_OPTIONS:
2668 case REQ_TOGGLE_LINENO:
2669 case REQ_TOGGLE_DATE:
2670 case REQ_TOGGLE_AUTHOR:
2671 case REQ_TOGGLE_FILENAME:
2672 case REQ_TOGGLE_GRAPHIC:
2673 case REQ_TOGGLE_REV_GRAPH:
2674 case REQ_TOGGLE_REFS:
2675 case REQ_TOGGLE_CHANGES:
2676 case REQ_TOGGLE_IGNORE_SPACE:
2677 case REQ_TOGGLE_ID:
2678 case REQ_TOGGLE_FILES:
2679 case REQ_TOGGLE_TITLE_OVERFLOW:
2680 case REQ_TOGGLE_FILE_SIZE:
2681 case REQ_TOGGLE_UNTRACKED_DIRS:
2682 case REQ_TOGGLE_VERTICAL_SPLIT:
2684 char action[SIZEOF_STR] = "";
2685 enum view_flag flags = toggle_option(view, request, action);
2687 if (flags == VIEW_FLAG_RESET_DISPLAY) {
2688 resize_display();
2689 redraw_display(TRUE);
2690 } else {
2691 foreach_displayed_view(view, i) {
2692 if (view_has_flags(view, flags) && !view->unrefreshable)
2693 reload_view(view);
2694 else
2695 redraw_view(view);
2699 if (*action)
2700 report("%s", action);
2702 break;
2704 case REQ_TOGGLE_SORT_FIELD:
2705 case REQ_TOGGLE_SORT_ORDER:
2706 report("Sorting is not yet supported for the %s view", view->name);
2707 break;
2709 case REQ_DIFF_CONTEXT_UP:
2710 case REQ_DIFF_CONTEXT_DOWN:
2711 report("Changing the diff context is not yet supported for the %s view", view->name);
2712 break;
2714 case REQ_SEARCH:
2715 case REQ_SEARCH_BACK:
2716 search_view(view, request);
2717 break;
2719 case REQ_FIND_NEXT:
2720 case REQ_FIND_PREV:
2721 find_next(view, request);
2722 break;
2724 case REQ_STOP_LOADING:
2725 foreach_view(view, i) {
2726 if (view->pipe)
2727 report("Stopped loading the %s view", view->name),
2728 end_update(view, TRUE);
2730 break;
2732 case REQ_SHOW_VERSION:
2733 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
2734 return TRUE;
2736 case REQ_SCREEN_REDRAW:
2737 redraw_display(TRUE);
2738 break;
2740 case REQ_EDIT:
2741 report("Nothing to edit");
2742 break;
2744 case REQ_ENTER:
2745 report("Nothing to enter");
2746 break;
2748 case REQ_VIEW_CLOSE:
2749 /* XXX: Mark closed views by letting view->prev point to the
2750 * view itself. Parents to closed view should never be
2751 * followed. */
2752 if (view->prev && view->prev != view) {
2753 maximize_view(view->prev, TRUE);
2754 view->prev = view;
2755 break;
2757 /* Fall-through */
2758 case REQ_QUIT:
2759 return FALSE;
2761 default:
2762 report("Unknown key, press %s for help",
2763 get_view_key(view, REQ_VIEW_HELP));
2764 return TRUE;
2767 return TRUE;
2772 * View backend utilities
2775 enum sort_field {
2776 ORDERBY_NAME,
2777 ORDERBY_DATE,
2778 ORDERBY_AUTHOR,
2781 struct sort_state {
2782 const enum sort_field *fields;
2783 size_t size, current;
2784 bool reverse;
2787 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
2788 #define get_sort_field(state) ((state).fields[(state).current])
2789 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
2791 static void
2792 sort_view(struct view *view, enum request request, struct sort_state *state,
2793 int (*compare)(const void *, const void *))
2795 switch (request) {
2796 case REQ_TOGGLE_SORT_FIELD:
2797 state->current = (state->current + 1) % state->size;
2798 break;
2800 case REQ_TOGGLE_SORT_ORDER:
2801 state->reverse = !state->reverse;
2802 break;
2803 default:
2804 die("Not a sort request");
2807 qsort(view->line, view->lines, sizeof(*view->line), compare);
2808 redraw_view(view);
2811 static bool
2812 update_diff_context(enum request request)
2814 int diff_context = opt_diff_context;
2816 switch (request) {
2817 case REQ_DIFF_CONTEXT_UP:
2818 opt_diff_context += 1;
2819 update_diff_context_arg(opt_diff_context);
2820 break;
2822 case REQ_DIFF_CONTEXT_DOWN:
2823 if (opt_diff_context == 0) {
2824 report("Diff context cannot be less than zero");
2825 break;
2827 opt_diff_context -= 1;
2828 update_diff_context_arg(opt_diff_context);
2829 break;
2831 default:
2832 die("Not a diff context request");
2835 return diff_context != opt_diff_context;
2838 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
2840 /* Small cache to reduce memory consumption. It uses binary search to
2841 * lookup or find place to position new entries. No entries are ever
2842 * freed. */
2843 static const char *
2844 get_path(const char *path)
2846 static const char **paths;
2847 static size_t paths_size;
2848 int from = 0, to = paths_size - 1;
2849 char *entry;
2851 while (from <= to) {
2852 size_t pos = (to + from) / 2;
2853 int cmp = strcmp(path, paths[pos]);
2855 if (!cmp)
2856 return paths[pos];
2858 if (cmp < 0)
2859 to = pos - 1;
2860 else
2861 from = pos + 1;
2864 if (!realloc_paths(&paths, paths_size, 1))
2865 return NULL;
2866 entry = strdup(path);
2867 if (!entry)
2868 return NULL;
2870 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
2871 paths[from] = entry;
2872 paths_size++;
2874 return entry;
2877 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
2879 /* Small author cache to reduce memory consumption. It uses binary
2880 * search to lookup or find place to position new entries. No entries
2881 * are ever freed. */
2882 static struct ident *
2883 get_author(const char *name, const char *email)
2885 static struct ident **authors;
2886 static size_t authors_size;
2887 int from = 0, to = authors_size - 1;
2888 struct ident *ident;
2890 while (from <= to) {
2891 size_t pos = (to + from) / 2;
2892 int cmp = strcmp(name, authors[pos]->name);
2894 if (!cmp)
2895 return authors[pos];
2897 if (cmp < 0)
2898 to = pos - 1;
2899 else
2900 from = pos + 1;
2903 if (!realloc_authors(&authors, authors_size, 1))
2904 return NULL;
2905 ident = calloc(1, sizeof(*ident));
2906 if (!ident)
2907 return NULL;
2908 ident->name = strdup(name);
2909 ident->email = strdup(email);
2910 if (!ident->name || !ident->email) {
2911 free((void *) ident->name);
2912 free(ident);
2913 return NULL;
2916 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
2917 authors[from] = ident;
2918 authors_size++;
2920 return ident;
2923 static void
2924 parse_timesec(struct time *time, const char *sec)
2926 time->sec = (time_t) atol(sec);
2929 static void
2930 parse_timezone(struct time *time, const char *zone)
2932 long tz;
2934 tz = ('0' - zone[1]) * 60 * 60 * 10;
2935 tz += ('0' - zone[2]) * 60 * 60;
2936 tz += ('0' - zone[3]) * 60 * 10;
2937 tz += ('0' - zone[4]) * 60;
2939 if (zone[0] == '-')
2940 tz = -tz;
2942 time->tz = tz;
2943 time->sec -= tz;
2946 /* Parse author lines where the name may be empty:
2947 * author <email@address.tld> 1138474660 +0100
2949 static void
2950 parse_author_line(char *ident, const struct ident **author, struct time *time)
2952 char *nameend = strchr(ident, '<');
2953 char *emailend = strchr(ident, '>');
2954 const char *name, *email = "";
2956 if (nameend && emailend)
2957 *nameend = *emailend = 0;
2958 name = chomp_string(ident);
2959 if (nameend)
2960 email = chomp_string(nameend + 1);
2961 if (!*name)
2962 name = *email ? email : unknown_ident.name;
2963 if (!*email)
2964 email = *name ? name : unknown_ident.email;
2966 *author = get_author(name, email);
2968 /* Parse epoch and timezone */
2969 if (time && emailend && emailend[1] == ' ') {
2970 char *secs = emailend + 2;
2971 char *zone = strchr(secs, ' ');
2973 parse_timesec(time, secs);
2975 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
2976 parse_timezone(time, zone + 1);
2980 static struct line *
2981 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
2983 for (; view_has_line(view, line); line += direction)
2984 if (line->type == type)
2985 return line;
2987 return NULL;
2990 #define find_prev_line_by_type(view, line, type) \
2991 find_line_by_type(view, line, type, -1)
2993 #define find_next_line_by_type(view, line, type) \
2994 find_line_by_type(view, line, type, 1)
2997 * View history
3000 struct view_state {
3001 struct view_state *prev; /* Entry below this in the stack */
3002 struct position position; /* View position to restore */
3003 void *data; /* View specific state */
3006 struct view_history {
3007 size_t state_alloc;
3008 struct view_state *stack;
3009 struct position position;
3012 static bool
3013 view_history_is_empty(struct view_history *history)
3015 return !history->stack;
3018 static struct view_state *
3019 push_view_history_state(struct view_history *history, struct position *position, void *data)
3021 struct view_state *state = history->stack;
3023 if (state && data && history->state_alloc &&
3024 !memcmp(state->data, data, history->state_alloc))
3025 return NULL;
3027 state = calloc(1, sizeof(*state) + history->state_alloc);
3028 if (!state)
3029 return NULL;
3031 state->prev = history->stack;
3032 history->stack = state;
3033 clear_position(&history->position);
3034 state->position = *position;
3035 state->data = &state[1];
3036 if (data && history->state_alloc)
3037 memcpy(state->data, data, history->state_alloc);
3038 return state;
3041 static bool
3042 pop_view_history_state(struct view_history *history, struct position *position, void *data)
3044 struct view_state *state = history->stack;
3046 if (view_history_is_empty(history))
3047 return FALSE;
3049 history->position = state->position;
3050 history->stack = state->prev;
3052 if (data && history->state_alloc)
3053 memcpy(data, state->data, history->state_alloc);
3054 if (position)
3055 *position = state->position;
3057 free(state);
3058 return TRUE;
3061 static void
3062 reset_view_history(struct view_history *history)
3064 while (pop_view_history_state(history, NULL, NULL))
3069 * Blame
3072 struct blame_commit {
3073 char id[SIZEOF_REV]; /* SHA1 ID. */
3074 char title[128]; /* First line of the commit message. */
3075 const struct ident *author; /* Author of the commit. */
3076 struct time time; /* Date from the author ident. */
3077 const char *filename; /* Name of file. */
3078 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3079 const char *parent_filename; /* Parent/previous name of file. */
3082 struct blame_header {
3083 char id[SIZEOF_REV]; /* SHA1 ID. */
3084 size_t orig_lineno;
3085 size_t lineno;
3086 size_t group;
3089 static bool
3090 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3092 const char *pos = *posref;
3094 *posref = NULL;
3095 pos = strchr(pos + 1, ' ');
3096 if (!pos || !isdigit(pos[1]))
3097 return FALSE;
3098 *number = atoi(pos + 1);
3099 if (*number < min || *number > max)
3100 return FALSE;
3102 *posref = pos;
3103 return TRUE;
3106 static bool
3107 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3109 const char *pos = text + SIZEOF_REV - 2;
3111 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3112 return FALSE;
3114 string_ncopy(header->id, text, SIZEOF_REV);
3116 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3117 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3118 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3119 return FALSE;
3121 return TRUE;
3124 static bool
3125 match_blame_header(const char *name, char **line)
3127 size_t namelen = strlen(name);
3128 bool matched = !strncmp(name, *line, namelen);
3130 if (matched)
3131 *line += namelen;
3133 return matched;
3136 static bool
3137 parse_blame_info(struct blame_commit *commit, char *line)
3139 if (match_blame_header("author ", &line)) {
3140 parse_author_line(line, &commit->author, NULL);
3142 } else if (match_blame_header("author-time ", &line)) {
3143 parse_timesec(&commit->time, line);
3145 } else if (match_blame_header("author-tz ", &line)) {
3146 parse_timezone(&commit->time, line);
3148 } else if (match_blame_header("summary ", &line)) {
3149 string_ncopy(commit->title, line, strlen(line));
3151 } else if (match_blame_header("previous ", &line)) {
3152 if (strlen(line) <= SIZEOF_REV)
3153 return FALSE;
3154 string_copy_rev(commit->parent_id, line);
3155 line += SIZEOF_REV;
3156 commit->parent_filename = get_path(line);
3157 if (!commit->parent_filename)
3158 return TRUE;
3160 } else if (match_blame_header("filename ", &line)) {
3161 commit->filename = get_path(line);
3162 return TRUE;
3165 return FALSE;
3169 * Pager backend
3172 static bool
3173 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3175 if (draw_lineno(view, lineno))
3176 return TRUE;
3178 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
3179 return TRUE;
3181 draw_text(view, line->type, line->data);
3182 return TRUE;
3185 static bool
3186 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3188 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3189 char ref[SIZEOF_STR];
3191 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3192 return TRUE;
3194 /* This is the only fatal call, since it can "corrupt" the buffer. */
3195 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3196 return FALSE;
3198 return TRUE;
3201 static void
3202 add_pager_refs(struct view *view, const char *commit_id)
3204 char buf[SIZEOF_STR];
3205 struct ref_list *list;
3206 size_t bufpos = 0, i;
3207 const char *sep = "Refs: ";
3208 bool is_tag = FALSE;
3210 list = get_ref_list(commit_id);
3211 if (!list) {
3212 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3213 goto try_add_describe_ref;
3214 return;
3217 for (i = 0; i < list->size; i++) {
3218 struct ref *ref = list->refs[i];
3219 const char *fmt = ref->tag ? "%s[%s]" :
3220 ref->remote ? "%s<%s>" : "%s%s";
3222 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3223 return;
3224 sep = ", ";
3225 if (ref->tag)
3226 is_tag = TRUE;
3229 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3230 try_add_describe_ref:
3231 /* Add <tag>-g<commit_id> "fake" reference. */
3232 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3233 return;
3236 if (bufpos == 0)
3237 return;
3239 add_line_text(view, buf, LINE_PP_REFS);
3242 static struct line *
3243 pager_wrap_line(struct view *view, const char *data, enum line_type type)
3245 size_t first_line = 0;
3246 bool has_first_line = FALSE;
3247 size_t datalen = strlen(data);
3248 size_t lineno = 0;
3250 while (datalen > 0 || !has_first_line) {
3251 bool wrapped = !!first_line;
3252 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
3253 struct line *line;
3254 char *text;
3256 line = add_line(view, NULL, type, linelen + 1, wrapped);
3257 if (!line)
3258 break;
3259 if (!has_first_line) {
3260 first_line = view->lines - 1;
3261 has_first_line = TRUE;
3264 if (!wrapped)
3265 lineno = line->lineno;
3267 line->wrapped = wrapped;
3268 line->lineno = lineno;
3269 text = line->data;
3270 if (linelen)
3271 strncpy(text, data, linelen);
3272 text[linelen] = 0;
3274 datalen -= linelen;
3275 data += linelen;
3278 return has_first_line ? &view->line[first_line] : NULL;
3281 static bool
3282 pager_common_read(struct view *view, const char *data, enum line_type type)
3284 struct line *line;
3286 if (!data)
3287 return TRUE;
3289 if (opt_wrap_lines) {
3290 line = pager_wrap_line(view, data, type);
3291 } else {
3292 line = add_line_text(view, data, type);
3295 if (!line)
3296 return FALSE;
3298 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3299 add_pager_refs(view, data + STRING_SIZE("commit "));
3301 return TRUE;
3304 static bool
3305 pager_read(struct view *view, char *data)
3307 if (!data)
3308 return TRUE;
3310 return pager_common_read(view, data, get_line_type(data));
3313 static enum request
3314 pager_request(struct view *view, enum request request, struct line *line)
3316 int split = 0;
3318 if (request != REQ_ENTER)
3319 return request;
3321 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3322 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3323 split = 1;
3326 /* Always scroll the view even if it was split. That way
3327 * you can use Enter to scroll through the log view and
3328 * split open each commit diff. */
3329 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3331 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
3332 * but if we are scrolling a non-current view this won't properly
3333 * update the view title. */
3334 if (split)
3335 update_view_title(view);
3337 return REQ_NONE;
3340 static bool
3341 pager_grep(struct view *view, struct line *line)
3343 const char *text[] = { line->data, NULL };
3345 return grep_text(view, text);
3348 static void
3349 pager_select(struct view *view, struct line *line)
3351 if (line->type == LINE_COMMIT) {
3352 string_copy_rev_from_commit_line(ref_commit, line->data);
3353 if (!view_has_flags(view, VIEW_NO_REF))
3354 string_copy_rev(view->ref, ref_commit);
3358 struct log_state {
3359 /* Used for tracking when we need to recalculate the previous
3360 * commit, for example when the user scrolls up or uses the page
3361 * up/down in the log view. */
3362 int last_lineno;
3363 enum line_type last_type;
3366 static void
3367 log_select(struct view *view, struct line *line)
3369 struct log_state *state = view->private;
3370 int last_lineno = state->last_lineno;
3372 if (!last_lineno || abs(last_lineno - line->lineno) > 1
3373 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
3374 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
3376 if (commit_line)
3377 string_copy_rev_from_commit_line(view->ref, commit_line->data);
3380 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
3381 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
3383 string_copy_rev(ref_commit, view->ref);
3384 state->last_lineno = line->lineno;
3385 state->last_type = line->type;
3388 static bool
3389 pager_open(struct view *view, enum open_flags flags)
3391 if (!open_from_stdin(flags) && !view->lines) {
3392 report("No pager content, press %s to run command from prompt",
3393 get_view_key(view, REQ_PROMPT));
3394 return FALSE;
3397 return begin_update(view, NULL, NULL, flags);
3400 static struct view_ops pager_ops = {
3401 "line",
3402 { "pager" },
3403 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3405 pager_open,
3406 pager_read,
3407 pager_draw,
3408 pager_request,
3409 pager_grep,
3410 pager_select,
3413 static bool
3414 log_open(struct view *view, enum open_flags flags)
3416 static const char *log_argv[] = {
3417 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", "--", NULL
3420 return begin_update(view, NULL, log_argv, flags);
3423 static enum request
3424 log_request(struct view *view, enum request request, struct line *line)
3426 switch (request) {
3427 case REQ_REFRESH:
3428 load_refs(TRUE);
3429 refresh_view(view);
3430 return REQ_NONE;
3432 case REQ_ENTER:
3433 if (!display[1] || strcmp(display[1]->vid, view->ref))
3434 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3435 return REQ_NONE;
3437 default:
3438 return request;
3442 static struct view_ops log_ops = {
3443 "line",
3444 { "log" },
3445 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE | VIEW_REFRESH,
3446 sizeof(struct log_state),
3447 log_open,
3448 pager_read,
3449 pager_draw,
3450 log_request,
3451 pager_grep,
3452 log_select,
3455 struct diff_state {
3456 bool after_commit_title;
3457 bool after_diff;
3458 bool reading_diff_stat;
3459 bool combined_diff;
3462 #define DIFF_LINE_COMMIT_TITLE 1
3464 static bool
3465 diff_open(struct view *view, enum open_flags flags)
3467 static const char *diff_argv[] = {
3468 "git", "show", encoding_arg, "--pretty=fuller", "--root",
3469 "--patch-with-stat",
3470 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3471 "%(diffargs)", "%(cmdlineargs)", "--no-color", "%(commit)",
3472 "--", "%(fileargs)", NULL
3475 return begin_update(view, NULL, diff_argv, flags);
3478 static bool
3479 diff_common_read(struct view *view, const char *data, struct diff_state *state)
3481 enum line_type type = get_line_type(data);
3483 if (!view->lines && type != LINE_COMMIT)
3484 state->reading_diff_stat = TRUE;
3486 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
3487 state->reading_diff_stat = TRUE;
3489 if (state->reading_diff_stat) {
3490 size_t len = strlen(data);
3491 char *pipe = strchr(data, '|');
3492 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3493 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3494 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
3495 bool has_no_change = pipe && strstr(pipe, " 0");
3497 if (pipe && (has_histogram || has_bin_diff || has_rename || has_no_change)) {
3498 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3499 } else {
3500 state->reading_diff_stat = FALSE;
3503 } else if (!strcmp(data, "---")) {
3504 state->reading_diff_stat = TRUE;
3507 if (!state->after_commit_title && !prefixcmp(data, " ")) {
3508 struct line *line = add_line_text(view, data, LINE_DEFAULT);
3510 if (line)
3511 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
3512 state->after_commit_title = TRUE;
3513 return line != NULL;
3516 if (type == LINE_DIFF_HEADER) {
3517 const int len = get_line_info(LINE_DIFF_HEADER)->linelen;
3519 state->after_diff = TRUE;
3520 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3521 !strncmp(data + len, "cc ", strlen("cc ")))
3522 state->combined_diff = TRUE;
3524 } else if (type == LINE_PP_MERGE) {
3525 state->combined_diff = TRUE;
3528 /* ADD2 and DEL2 are only valid in combined diff hunks */
3529 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3530 type = LINE_DEFAULT;
3532 return pager_common_read(view, data, type);
3535 static bool
3536 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
3538 struct line *marker = find_next_line_by_type(view, line, type);
3540 return marker &&
3541 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
3544 static enum request
3545 diff_common_enter(struct view *view, enum request request, struct line *line)
3547 if (line->type == LINE_DIFF_STAT) {
3548 int file_number = 0;
3550 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
3551 file_number++;
3552 line--;
3555 for (line = view->line; view_has_line(view, line); line++) {
3556 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
3557 if (!line)
3558 break;
3560 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
3561 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
3562 if (file_number == 1) {
3563 break;
3565 file_number--;
3569 if (!line) {
3570 report("Failed to find file diff");
3571 return REQ_NONE;
3574 select_view_line(view, line - view->line);
3575 report_clear();
3576 return REQ_NONE;
3578 } else {
3579 return pager_request(view, request, line);
3583 static bool
3584 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3586 char *sep = strchr(*text, c);
3588 if (sep != NULL) {
3589 *sep = 0;
3590 draw_text(view, *type, *text);
3591 *sep = c;
3592 *text = sep;
3593 *type = next_type;
3596 return sep != NULL;
3599 static bool
3600 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3602 char *text = line->data;
3603 enum line_type type = line->type;
3605 if (draw_lineno(view, lineno))
3606 return TRUE;
3608 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
3609 return TRUE;
3611 if (type == LINE_DIFF_STAT) {
3612 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3613 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3614 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3615 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3616 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3617 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3618 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3620 } else {
3621 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3622 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3626 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
3627 draw_commit_title(view, text, 4);
3628 else
3629 draw_text(view, type, text);
3630 return TRUE;
3633 static bool
3634 diff_read(struct view *view, char *data)
3636 struct diff_state *state = view->private;
3638 if (!data) {
3639 /* Fall back to retry if no diff will be shown. */
3640 if (view->lines == 0 && opt_file_argv) {
3641 int pos = argv_size(view->argv)
3642 - argv_size(opt_file_argv) - 1;
3644 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3645 for (; view->argv[pos]; pos++) {
3646 free((void *) view->argv[pos]);
3647 view->argv[pos] = NULL;
3650 if (view->pipe)
3651 io_done(view->pipe);
3652 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
3653 return FALSE;
3656 return TRUE;
3659 return diff_common_read(view, data, state);
3662 static bool
3663 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3664 struct blame_header *header, struct blame_commit *commit)
3666 char line_arg[SIZEOF_STR];
3667 const char *blame_argv[] = {
3668 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
3670 struct io io;
3671 bool ok = FALSE;
3672 char *buf;
3674 if (!string_format(line_arg, "-L%ld,+1", lineno))
3675 return FALSE;
3677 if (!io_run(&io, IO_RD, repo.cdup, opt_env, blame_argv))
3678 return FALSE;
3680 while ((buf = io_get(&io, '\n', TRUE))) {
3681 if (header) {
3682 if (!parse_blame_header(header, buf, 9999999))
3683 break;
3684 header = NULL;
3686 } else if (parse_blame_info(commit, buf)) {
3687 ok = commit->filename != NULL;
3688 break;
3692 if (io_error(&io))
3693 ok = FALSE;
3695 io_done(&io);
3696 return ok;
3699 struct chunk_header_position {
3700 unsigned long position;
3701 unsigned long lines;
3704 struct chunk_header {
3705 struct chunk_header_position old;
3706 struct chunk_header_position new;
3709 static bool
3710 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
3712 const char *start = *pos_ptr;
3713 char *end;
3715 if (!isdigit(*start))
3716 return 0;
3718 *value = strtoul(start, &end, 10);
3719 if (end == start)
3720 return FALSE;
3722 start = end;
3723 while (skip && *start && strchr(skip, *start))
3724 start++;
3725 *pos_ptr = start;
3726 return TRUE;
3729 static bool
3730 parse_chunk_header(struct chunk_header *header, const char *line)
3732 memset(header, 0, sizeof(*header));
3734 if (prefixcmp(line, "@@ -"))
3735 return FALSE;
3737 line += STRING_SIZE("@@ -");
3739 return parse_ulong(&line, &header->old.position, ",") &&
3740 parse_ulong(&line, &header->old.lines, " +") &&
3741 parse_ulong(&line, &header->new.position, ",") &&
3742 parse_ulong(&line, &header->new.lines, NULL);
3745 static unsigned int
3746 diff_get_lineno(struct view *view, struct line *line)
3748 const struct line *header, *chunk;
3749 unsigned int lineno;
3750 struct chunk_header chunk_header;
3752 /* Verify that we are after a diff header and one of its chunks */
3753 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3754 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3755 if (!header || !chunk || chunk < header)
3756 return 0;
3759 * In a chunk header, the number after the '+' sign is the number of its
3760 * following line, in the new version of the file. We increment this
3761 * number for each non-deletion line, until the given line position.
3763 if (!parse_chunk_header(&chunk_header, chunk->data))
3764 return 0;
3766 lineno = chunk_header.new.position;
3767 chunk++;
3768 while (chunk++ < line)
3769 if (chunk->type != LINE_DIFF_DEL)
3770 lineno++;
3772 return lineno;
3775 static bool
3776 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
3778 struct chunk_header chunk_header;
3780 *lineno = 0;
3782 if (!parse_chunk_header(&chunk_header, chunk))
3783 return FALSE;
3785 *lineno = marker == '-' ? chunk_header.old.position : chunk_header.new.position;
3786 return TRUE;
3789 static enum request
3790 diff_trace_origin(struct view *view, struct line *line)
3792 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3793 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3794 const char *chunk_data;
3795 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3796 unsigned long lineno = 0;
3797 const char *file = NULL;
3798 char ref[SIZEOF_REF];
3799 struct blame_header header;
3800 struct blame_commit commit;
3802 if (!diff || !chunk || chunk == line) {
3803 report("The line to trace must be inside a diff chunk");
3804 return REQ_NONE;
3807 for (; diff < line && !file; diff++) {
3808 const char *data = diff->data;
3810 if (!prefixcmp(data, "--- a/")) {
3811 file = data + STRING_SIZE("--- a/");
3812 break;
3816 if (diff == line || !file) {
3817 report("Failed to read the file name");
3818 return REQ_NONE;
3821 chunk_data = chunk->data;
3823 if (!parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
3824 report("Failed to read the line number");
3825 return REQ_NONE;
3828 if (lineno == 0) {
3829 report("This is the origin of the line");
3830 return REQ_NONE;
3833 for (chunk += 1; chunk < line; chunk++) {
3834 if (chunk->type == LINE_DIFF_ADD) {
3835 lineno += chunk_marker == '+';
3836 } else if (chunk->type == LINE_DIFF_DEL) {
3837 lineno += chunk_marker == '-';
3838 } else {
3839 lineno++;
3843 if (chunk_marker == '+')
3844 string_copy(ref, view->vid);
3845 else
3846 string_format(ref, "%s^", view->vid);
3848 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
3849 report("Failed to read blame data");
3850 return REQ_NONE;
3853 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
3854 string_copy(opt_ref, header.id);
3855 opt_goto_line = header.orig_lineno - 1;
3857 return REQ_VIEW_BLAME;
3860 static const char *
3861 diff_get_pathname(struct view *view, struct line *line)
3863 const struct line *header;
3864 const char *dst = NULL;
3865 const char *prefixes[] = { " b/", "cc ", "combined " };
3866 int i;
3868 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3869 if (!header)
3870 return NULL;
3872 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
3873 dst = strstr(header->data, prefixes[i]);
3875 return dst ? dst + strlen(prefixes[--i]) : NULL;
3878 static enum request
3879 diff_common_edit(struct view *view, enum request request, struct line *line)
3881 const char *file = diff_get_pathname(view, line);
3882 char path[SIZEOF_STR];
3883 bool has_path = file && string_format(path, "%s%s", repo.cdup, file);
3885 if (has_path && access(path, R_OK)) {
3886 report("Failed to open file: %s", file);
3887 return REQ_NONE;
3890 open_editor(file, diff_get_lineno(view, line));
3891 return REQ_NONE;
3894 static enum request
3895 diff_request(struct view *view, enum request request, struct line *line)
3897 switch (request) {
3898 case REQ_VIEW_BLAME:
3899 return diff_trace_origin(view, line);
3901 case REQ_DIFF_CONTEXT_UP:
3902 case REQ_DIFF_CONTEXT_DOWN:
3903 if (!update_diff_context(request))
3904 return REQ_NONE;
3905 reload_view(view);
3906 return REQ_NONE;
3909 case REQ_EDIT:
3910 return diff_common_edit(view, request, line);
3912 case REQ_ENTER:
3913 return diff_common_enter(view, request, line);
3915 case REQ_REFRESH:
3916 if (string_rev_is_null(view->vid))
3917 refresh_view(view);
3918 else
3919 reload_view(view);
3920 return REQ_NONE;
3922 default:
3923 return pager_request(view, request, line);
3927 static void
3928 diff_select(struct view *view, struct line *line)
3930 if (line->type == LINE_DIFF_STAT) {
3931 string_format(view->ref, "Press '%s' to jump to file diff",
3932 get_view_key(view, REQ_ENTER));
3933 } else {
3934 const char *file = diff_get_pathname(view, line);
3936 if (file) {
3937 string_format(view->ref, "Changes to '%s'", file);
3938 string_format(opt_file, "%s", file);
3939 ref_blob[0] = 0;
3940 } else {
3941 string_ncopy(view->ref, view->id, strlen(view->id));
3942 pager_select(view, line);
3947 static struct view_ops diff_ops = {
3948 "line",
3949 { "diff" },
3950 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER | VIEW_REFRESH,
3951 sizeof(struct diff_state),
3952 diff_open,
3953 diff_read,
3954 diff_common_draw,
3955 diff_request,
3956 pager_grep,
3957 diff_select,
3961 * Help backend
3964 static bool
3965 help_draw(struct view *view, struct line *line, unsigned int lineno)
3967 if (line->type == LINE_HELP_KEYMAP) {
3968 struct keymap *keymap = line->data;
3970 draw_formatted(view, line->type, "[%c] %s bindings",
3971 keymap->hidden ? '+' : '-', keymap->name);
3972 return TRUE;
3973 } else {
3974 return pager_draw(view, line, lineno);
3978 static bool
3979 help_open_keymap_title(struct view *view, struct keymap *keymap)
3981 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
3982 return keymap->hidden;
3985 struct help_request_iterator {
3986 struct view *view;
3987 struct keymap *keymap;
3988 bool add_title;
3989 const char *group;
3992 static bool
3993 help_open_keymap(void *data, const struct request_info *req_info, const char *group)
3995 struct help_request_iterator *iterator = data;
3996 struct view *view = iterator->view;
3997 struct keymap *keymap = iterator->keymap;
3998 const char *key = get_keys(keymap, req_info->request, TRUE);
4000 if (req_info->request == REQ_NONE || !key || !*key)
4001 return TRUE;
4003 if (iterator->add_title && help_open_keymap_title(view, keymap))
4004 return FALSE;
4005 iterator->add_title = FALSE;
4007 if (iterator->group != group) {
4008 add_line_text(view, group, LINE_HELP_GROUP);
4009 iterator->group = group;
4012 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4013 enum_name(*req_info), req_info->help);
4014 return TRUE;
4017 static void
4018 help_open_keymap_run_requests(struct help_request_iterator *iterator)
4020 struct view *view = iterator->view;
4021 struct keymap *keymap = iterator->keymap;
4022 char buf[SIZEOF_STR];
4023 const char *group = "External commands:";
4024 int i;
4026 for (i = 0; TRUE; i++) {
4027 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4028 const char *key;
4030 if (!req)
4031 break;
4033 if (req->keymap != keymap)
4034 continue;
4036 key = get_key_name(req->key);
4037 if (!*key)
4038 key = "(no key defined)";
4040 if (iterator->add_title && help_open_keymap_title(view, keymap))
4041 return;
4042 iterator->add_title = FALSE;
4044 if (group) {
4045 add_line_text(view, group, LINE_HELP_GROUP);
4046 group = NULL;
4049 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4050 return;
4052 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4056 static bool
4057 help_open(struct view *view, enum open_flags flags)
4059 struct keymap *keymap;
4061 reset_view(view);
4062 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4063 add_line_text(view, "", LINE_DEFAULT);
4065 for (keymap = get_keymaps(); keymap; keymap = keymap->next) {
4066 struct help_request_iterator iterator = { view, keymap, TRUE };
4068 if (foreach_request(help_open_keymap, &iterator))
4069 help_open_keymap_run_requests(&iterator);
4072 return TRUE;
4075 static enum request
4076 help_request(struct view *view, enum request request, struct line *line)
4078 switch (request) {
4079 case REQ_ENTER:
4080 if (line->type == LINE_HELP_KEYMAP) {
4081 struct keymap *keymap = line->data;
4083 keymap->hidden = !keymap->hidden;
4084 refresh_view(view);
4087 return REQ_NONE;
4088 default:
4089 return pager_request(view, request, line);
4093 static void
4094 help_done(struct view *view)
4096 int i;
4098 for (i = 0; i < view->lines; i++)
4099 if (view->line[i].type == LINE_HELP_KEYMAP)
4100 view->line[i].data = NULL;
4103 static struct view_ops help_ops = {
4104 "line",
4105 { "help" },
4106 VIEW_NO_GIT_DIR,
4108 help_open,
4109 NULL,
4110 help_draw,
4111 help_request,
4112 pager_grep,
4113 pager_select,
4114 help_done,
4119 * Tree backend
4122 /* The top of the path stack. */
4123 static struct view_history tree_view_history = { sizeof(char *) };
4125 static void
4126 pop_tree_stack_entry(struct position *position)
4128 char *path_position = NULL;
4130 pop_view_history_state(&tree_view_history, position, &path_position);
4131 path_position[0] = 0;
4134 static void
4135 push_tree_stack_entry(const char *name, struct position *position)
4137 size_t pathlen = strlen(opt_path);
4138 char *path_position = opt_path + pathlen;
4139 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
4141 if (!state)
4142 return;
4144 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4145 pop_tree_stack_entry(NULL);
4146 return;
4149 clear_position(position);
4152 /* Parse output from git-ls-tree(1):
4154 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
4157 #define SIZEOF_TREE_ATTR \
4158 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4160 #define SIZEOF_TREE_MODE \
4161 STRING_SIZE("100644 ")
4163 #define TREE_ID_OFFSET \
4164 STRING_SIZE("100644 blob ")
4166 #define tree_path_is_parent(path) (!strcmp("..", (path)))
4168 struct tree_entry {
4169 char id[SIZEOF_REV];
4170 char commit[SIZEOF_REV];
4171 mode_t mode;
4172 struct time time; /* Date from the author ident. */
4173 const struct ident *author; /* Author of the commit. */
4174 unsigned long size;
4175 char name[1];
4178 struct tree_state {
4179 char commit[SIZEOF_REV];
4180 const struct ident *author;
4181 struct time author_time;
4182 int size_width;
4183 bool read_date;
4186 static const char *
4187 tree_path(const struct line *line)
4189 return ((struct tree_entry *) line->data)->name;
4192 static int
4193 tree_compare_entry(const struct line *line1, const struct line *line2)
4195 if (line1->type != line2->type)
4196 return line1->type == LINE_TREE_DIR ? -1 : 1;
4197 return strcmp(tree_path(line1), tree_path(line2));
4200 static const enum sort_field tree_sort_fields[] = {
4201 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4203 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4205 static int
4206 tree_compare(const void *l1, const void *l2)
4208 const struct line *line1 = (const struct line *) l1;
4209 const struct line *line2 = (const struct line *) l2;
4210 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4211 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4213 if (line1->type == LINE_TREE_HEAD)
4214 return -1;
4215 if (line2->type == LINE_TREE_HEAD)
4216 return 1;
4218 switch (get_sort_field(tree_sort_state)) {
4219 case ORDERBY_DATE:
4220 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4222 case ORDERBY_AUTHOR:
4223 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
4225 case ORDERBY_NAME:
4226 default:
4227 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4232 static struct line *
4233 tree_entry(struct view *view, enum line_type type, const char *path,
4234 const char *mode, const char *id, unsigned long size)
4236 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
4237 struct tree_entry *entry;
4238 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
4240 if (!line)
4241 return NULL;
4243 strncpy(entry->name, path, strlen(path));
4244 if (mode)
4245 entry->mode = strtoul(mode, NULL, 8);
4246 if (id)
4247 string_copy_rev(entry->id, id);
4248 entry->size = size;
4250 return line;
4253 static bool
4254 tree_read_date(struct view *view, char *text, struct tree_state *state)
4256 if (!text && state->read_date) {
4257 state->read_date = FALSE;
4258 return TRUE;
4260 } else if (!text) {
4261 /* Find next entry to process */
4262 const char *log_file[] = {
4263 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
4264 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4267 if (!view->lines) {
4268 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
4269 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
4270 report("Tree is empty");
4271 return TRUE;
4274 if (!begin_update(view, repo.cdup, log_file, OPEN_EXTRA)) {
4275 report("Failed to load tree data");
4276 return TRUE;
4279 state->read_date = TRUE;
4280 return FALSE;
4282 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
4283 string_copy_rev_from_commit_line(state->commit, text);
4285 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4286 parse_author_line(text + STRING_SIZE("author "),
4287 &state->author, &state->author_time);
4289 } else if (*text == ':') {
4290 char *pos;
4291 size_t annotated = 1;
4292 size_t i;
4294 pos = strchr(text, '\t');
4295 if (!pos)
4296 return TRUE;
4297 text = pos + 1;
4298 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4299 text += strlen(opt_path);
4300 pos = strchr(text, '/');
4301 if (pos)
4302 *pos = 0;
4304 for (i = 1; i < view->lines; i++) {
4305 struct line *line = &view->line[i];
4306 struct tree_entry *entry = line->data;
4308 annotated += !!entry->author;
4309 if (entry->author || strcmp(entry->name, text))
4310 continue;
4312 string_copy_rev(entry->commit, state->commit);
4313 entry->author = state->author;
4314 entry->time = state->author_time;
4315 line->dirty = 1;
4316 break;
4319 if (annotated == view->lines)
4320 io_kill(view->pipe);
4322 return TRUE;
4325 static inline size_t
4326 parse_size(const char *text, int *max_digits)
4328 size_t size = 0;
4329 int digits = 0;
4331 while (*text == ' ')
4332 text++;
4334 while (isdigit(*text)) {
4335 size = (size * 10) + (*text++ - '0');
4336 digits++;
4339 if (digits > *max_digits)
4340 *max_digits = digits;
4342 return size;
4345 static bool
4346 tree_read(struct view *view, char *text)
4348 struct tree_state *state = view->private;
4349 struct tree_entry *data;
4350 struct line *entry, *line;
4351 enum line_type type;
4352 size_t textlen = text ? strlen(text) : 0;
4353 const char *attr_offset = text + SIZEOF_TREE_ATTR;
4354 char *path;
4355 size_t size;
4357 if (state->read_date || !text)
4358 return tree_read_date(view, text, state);
4360 if (textlen <= SIZEOF_TREE_ATTR)
4361 return FALSE;
4362 if (view->lines == 0 &&
4363 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
4364 return FALSE;
4366 size = parse_size(attr_offset, &state->size_width);
4367 path = strchr(attr_offset, '\t');
4368 if (!path)
4369 return FALSE;
4370 path++;
4372 /* Strip the path part ... */
4373 if (*opt_path) {
4374 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4375 size_t striplen = strlen(opt_path);
4377 if (pathlen > striplen)
4378 memmove(path, path + striplen,
4379 pathlen - striplen + 1);
4381 /* Insert "link" to parent directory. */
4382 if (view->lines == 1 &&
4383 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
4384 return FALSE;
4387 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4388 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
4389 if (!entry)
4390 return FALSE;
4391 data = entry->data;
4393 /* Skip "Directory ..." and ".." line. */
4394 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4395 if (tree_compare_entry(line, entry) <= 0)
4396 continue;
4398 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4400 line->data = data;
4401 line->type = type;
4402 for (; line <= entry; line++)
4403 line->dirty = line->cleareol = 1;
4404 return TRUE;
4407 /* Move the current line to the first tree entry. */
4408 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
4409 goto_view_line(view, 0, 1);
4411 return TRUE;
4414 static bool
4415 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4417 struct tree_state *state = view->private;
4418 struct tree_entry *entry = line->data;
4420 if (line->type == LINE_TREE_HEAD) {
4421 if (draw_text(view, line->type, "Directory path /"))
4422 return TRUE;
4423 } else {
4424 if (draw_mode(view, entry->mode))
4425 return TRUE;
4427 if (draw_author(view, entry->author))
4428 return TRUE;
4430 if (draw_file_size(view, entry->size, state->size_width,
4431 line->type != LINE_TREE_FILE))
4432 return TRUE;
4434 if (draw_date(view, &entry->time))
4435 return TRUE;
4437 if (draw_id(view, entry->commit))
4438 return TRUE;
4441 draw_text(view, line->type, entry->name);
4442 return TRUE;
4445 static void
4446 open_blob_editor(const char *id, const char *name, unsigned int lineno)
4448 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4449 char file[SIZEOF_STR];
4450 int fd;
4452 if (!name)
4453 name = "unknown";
4455 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
4456 report("Temporary file name is too long");
4457 return;
4460 fd = mkstemps(file, strlen(name) + 1);
4462 if (fd == -1)
4463 report("Failed to create temporary file");
4464 else if (!io_run_append(blob_argv, fd))
4465 report("Failed to save blob data to file");
4466 else
4467 open_editor(file, lineno);
4468 if (fd != -1)
4469 unlink(file);
4472 static enum request
4473 tree_request(struct view *view, enum request request, struct line *line)
4475 enum open_flags flags;
4476 struct tree_entry *entry = line->data;
4478 switch (request) {
4479 case REQ_VIEW_BLAME:
4480 if (line->type != LINE_TREE_FILE) {
4481 report("Blame only supported for files");
4482 return REQ_NONE;
4485 string_copy(opt_ref, view->vid);
4486 return request;
4488 case REQ_EDIT:
4489 if (line->type != LINE_TREE_FILE) {
4490 report("Edit only supported for files");
4491 } else if (!is_head_commit(view->vid)) {
4492 open_blob_editor(entry->id, entry->name, 0);
4493 } else {
4494 open_editor(opt_file, 0);
4496 return REQ_NONE;
4498 case REQ_TOGGLE_SORT_FIELD:
4499 case REQ_TOGGLE_SORT_ORDER:
4500 sort_view(view, request, &tree_sort_state, tree_compare);
4501 return REQ_NONE;
4503 case REQ_PARENT:
4504 case REQ_BACK:
4505 if (!*opt_path) {
4506 /* quit view if at top of tree */
4507 return REQ_VIEW_CLOSE;
4509 /* fake 'cd ..' */
4510 line = &view->line[1];
4511 break;
4513 case REQ_ENTER:
4514 break;
4516 default:
4517 return request;
4520 /* Cleanup the stack if the tree view is at a different tree. */
4521 if (!*opt_path)
4522 reset_view_history(&tree_view_history);
4524 switch (line->type) {
4525 case LINE_TREE_DIR:
4526 /* Depending on whether it is a subdirectory or parent link
4527 * mangle the path buffer. */
4528 if (line == &view->line[1] && *opt_path) {
4529 pop_tree_stack_entry(&view->pos);
4531 } else {
4532 const char *basename = tree_path(line);
4534 push_tree_stack_entry(basename, &view->pos);
4537 /* Trees and subtrees share the same ID, so they are not not
4538 * unique like blobs. */
4539 flags = OPEN_RELOAD;
4540 request = REQ_VIEW_TREE;
4541 break;
4543 case LINE_TREE_FILE:
4544 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4545 request = REQ_VIEW_BLOB;
4546 break;
4548 default:
4549 return REQ_NONE;
4552 open_view(view, request, flags);
4554 return REQ_NONE;
4557 static bool
4558 tree_grep(struct view *view, struct line *line)
4560 struct tree_entry *entry = line->data;
4561 const char *text[] = {
4562 entry->name,
4563 mkauthor(entry->author, opt_author_width, opt_author),
4564 mkdate(&entry->time, opt_date),
4565 NULL
4568 return grep_text(view, text);
4571 static void
4572 tree_select(struct view *view, struct line *line)
4574 struct tree_entry *entry = line->data;
4576 if (line->type == LINE_TREE_HEAD) {
4577 string_format(view->ref, "Files in /%s", opt_path);
4578 return;
4581 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
4582 string_copy(view->ref, "Open parent directory");
4583 ref_blob[0] = 0;
4584 return;
4587 if (line->type == LINE_TREE_FILE) {
4588 string_copy_rev(ref_blob, entry->id);
4589 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4592 string_copy_rev(view->ref, entry->id);
4595 static bool
4596 tree_open(struct view *view, enum open_flags flags)
4598 static const char *tree_argv[] = {
4599 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
4602 if (string_rev_is_null(ref_commit)) {
4603 report("No tree exists for this commit");
4604 return FALSE;
4607 if (view->lines == 0 && repo.prefix[0]) {
4608 char *pos = repo.prefix;
4610 while (pos && *pos) {
4611 char *end = strchr(pos, '/');
4613 if (end)
4614 *end = 0;
4615 push_tree_stack_entry(pos, &view->pos);
4616 pos = end;
4617 if (end) {
4618 *end = '/';
4619 pos++;
4623 } else if (strcmp(view->vid, view->id)) {
4624 opt_path[0] = 0;
4627 return begin_update(view, repo.cdup, tree_argv, flags);
4630 static struct view_ops tree_ops = {
4631 "file",
4632 { "tree" },
4633 VIEW_SEND_CHILD_ENTER,
4634 sizeof(struct tree_state),
4635 tree_open,
4636 tree_read,
4637 tree_draw,
4638 tree_request,
4639 tree_grep,
4640 tree_select,
4643 static bool
4644 blob_open(struct view *view, enum open_flags flags)
4646 static const char *blob_argv[] = {
4647 "git", "cat-file", "blob", "%(blob)", NULL
4650 if (!ref_blob[0] && opt_file[0]) {
4651 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
4652 char blob_spec[SIZEOF_STR];
4653 const char *rev_parse_argv[] = {
4654 "git", "rev-parse", blob_spec, NULL
4657 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
4658 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
4659 report("Failed to resolve blob from file name");
4660 return FALSE;
4664 if (!ref_blob[0]) {
4665 report("No file chosen, press %s to open tree view",
4666 get_view_key(view, REQ_VIEW_TREE));
4667 return FALSE;
4670 view->encoding = get_path_encoding(opt_file, default_encoding);
4672 return begin_update(view, NULL, blob_argv, flags);
4675 static bool
4676 blob_read(struct view *view, char *line)
4678 if (!line)
4679 return TRUE;
4680 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4683 static enum request
4684 blob_request(struct view *view, enum request request, struct line *line)
4686 switch (request) {
4687 case REQ_VIEW_BLAME:
4688 if (view->parent)
4689 string_copy(opt_ref, view->parent->vid);
4690 return request;
4692 case REQ_EDIT:
4693 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
4694 return REQ_NONE;
4695 default:
4696 return pager_request(view, request, line);
4700 static struct view_ops blob_ops = {
4701 "line",
4702 { "blob" },
4703 VIEW_NO_FLAGS,
4705 blob_open,
4706 blob_read,
4707 pager_draw,
4708 blob_request,
4709 pager_grep,
4710 pager_select,
4714 * Blame backend
4716 * Loading the blame view is a two phase job:
4718 * 1. File content is read either using opt_file from the
4719 * filesystem or using git-cat-file.
4720 * 2. Then blame information is incrementally added by
4721 * reading output from git-blame.
4724 struct blame_history_state {
4725 char id[SIZEOF_REV]; /* SHA1 ID. */
4726 const char *filename; /* Name of file. */
4729 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
4731 struct blame {
4732 struct blame_commit *commit;
4733 unsigned long lineno;
4734 char text[1];
4737 struct blame_state {
4738 struct blame_commit *commit;
4739 int blamed;
4740 bool done_reading;
4741 bool auto_filename_display;
4742 /* The history state for the current view is cached in the view
4743 * state so it always matches what was used to load the current blame
4744 * view. */
4745 struct blame_history_state history_state;
4748 static bool
4749 blame_detect_filename_display(struct view *view)
4751 bool show_filenames = FALSE;
4752 const char *filename = NULL;
4753 int i;
4755 if (opt_blame_argv) {
4756 for (i = 0; opt_blame_argv[i]; i++) {
4757 if (prefixcmp(opt_blame_argv[i], "-C"))
4758 continue;
4760 show_filenames = TRUE;
4764 for (i = 0; i < view->lines; i++) {
4765 struct blame *blame = view->line[i].data;
4767 if (blame->commit && blame->commit->id[0]) {
4768 if (!filename)
4769 filename = blame->commit->filename;
4770 else if (strcmp(filename, blame->commit->filename))
4771 show_filenames = TRUE;
4775 return show_filenames;
4778 static bool
4779 blame_open(struct view *view, enum open_flags flags)
4781 struct blame_state *state = view->private;
4782 const char *file_argv[] = { repo.cdup, opt_file , NULL };
4783 char path[SIZEOF_STR];
4784 size_t i;
4786 if (!opt_file[0]) {
4787 report("No file chosen, press %s to open tree view",
4788 get_view_key(view, REQ_VIEW_TREE));
4789 return FALSE;
4792 if (!view->prev && *repo.prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
4793 string_copy(path, opt_file);
4794 if (!string_format(opt_file, "%s%s", repo.prefix, path)) {
4795 report("Failed to setup the blame view");
4796 return FALSE;
4800 if (*opt_ref || !begin_update(view, repo.cdup, file_argv, flags)) {
4801 const char *blame_cat_file_argv[] = {
4802 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4805 if (!begin_update(view, repo.cdup, blame_cat_file_argv, flags))
4806 return FALSE;
4809 /* First pass: remove multiple references to the same commit. */
4810 for (i = 0; i < view->lines; i++) {
4811 struct blame *blame = view->line[i].data;
4813 if (blame->commit && blame->commit->id[0])
4814 blame->commit->id[0] = 0;
4815 else
4816 blame->commit = NULL;
4819 /* Second pass: free existing references. */
4820 for (i = 0; i < view->lines; i++) {
4821 struct blame *blame = view->line[i].data;
4823 if (blame->commit)
4824 free(blame->commit);
4827 if (!(flags & OPEN_RELOAD))
4828 reset_view_history(&blame_view_history);
4829 string_copy_rev(state->history_state.id, opt_ref);
4830 state->history_state.filename = get_path(opt_file);
4831 if (!state->history_state.filename)
4832 return FALSE;
4833 string_format(view->vid, "%s", opt_file);
4834 string_format(view->ref, "%s ...", opt_file);
4836 return TRUE;
4839 static struct blame_commit *
4840 get_blame_commit(struct view *view, const char *id)
4842 size_t i;
4844 for (i = 0; i < view->lines; i++) {
4845 struct blame *blame = view->line[i].data;
4847 if (!blame->commit)
4848 continue;
4850 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4851 return blame->commit;
4855 struct blame_commit *commit = calloc(1, sizeof(*commit));
4857 if (commit)
4858 string_ncopy(commit->id, id, SIZEOF_REV);
4859 return commit;
4863 static struct blame_commit *
4864 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4866 struct blame_header header;
4867 struct blame_commit *commit;
4868 struct blame *blame;
4870 if (!parse_blame_header(&header, text, view->lines))
4871 return NULL;
4873 commit = get_blame_commit(view, text);
4874 if (!commit)
4875 return NULL;
4877 state->blamed += header.group;
4878 while (header.group--) {
4879 struct line *line = &view->line[header.lineno + header.group - 1];
4881 blame = line->data;
4882 blame->commit = commit;
4883 blame->lineno = header.orig_lineno + header.group - 1;
4884 line->dirty = 1;
4887 return commit;
4890 static bool
4891 blame_read_file(struct view *view, const char *text, struct blame_state *state)
4893 if (!text) {
4894 const char *blame_argv[] = {
4895 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
4896 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4899 if (view->lines == 0 && !view->prev)
4900 die("No blame exist for %s", view->vid);
4902 if (view->lines == 0 || !begin_update(view, repo.cdup, blame_argv, OPEN_EXTRA)) {
4903 report("Failed to load blame data");
4904 return TRUE;
4907 if (opt_goto_line > 0) {
4908 select_view_line(view, opt_goto_line);
4909 opt_goto_line = 0;
4912 state->done_reading = TRUE;
4913 return FALSE;
4915 } else {
4916 size_t textlen = strlen(text);
4917 struct blame *blame;
4919 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
4920 return FALSE;
4922 blame->commit = NULL;
4923 strncpy(blame->text, text, textlen);
4924 blame->text[textlen] = 0;
4925 return TRUE;
4929 static bool
4930 blame_read(struct view *view, char *line)
4932 struct blame_state *state = view->private;
4934 if (!state->done_reading)
4935 return blame_read_file(view, line, state);
4937 if (!line) {
4938 state->auto_filename_display = blame_detect_filename_display(view);
4939 string_format(view->ref, "%s", view->vid);
4940 if (view_is_displayed(view)) {
4941 update_view_title(view);
4942 redraw_view_from(view, 0);
4944 return TRUE;
4947 if (!state->commit) {
4948 state->commit = read_blame_commit(view, line, state);
4949 string_format(view->ref, "%s %2zd%%", view->vid,
4950 view->lines ? state->blamed * 100 / view->lines : 0);
4952 } else if (parse_blame_info(state->commit, line)) {
4953 if (!state->commit->filename)
4954 return FALSE;
4955 state->commit = NULL;
4958 return TRUE;
4961 static bool
4962 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4964 struct blame_state *state = view->private;
4965 struct blame *blame = line->data;
4966 struct time *time = NULL;
4967 const char *id = NULL, *filename = NULL;
4968 const struct ident *author = NULL;
4969 enum line_type id_type = LINE_ID;
4970 static const enum line_type blame_colors[] = {
4971 LINE_PALETTE_0,
4972 LINE_PALETTE_1,
4973 LINE_PALETTE_2,
4974 LINE_PALETTE_3,
4975 LINE_PALETTE_4,
4976 LINE_PALETTE_5,
4977 LINE_PALETTE_6,
4980 #define BLAME_COLOR(i) \
4981 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4983 if (blame->commit && blame->commit->filename) {
4984 id = blame->commit->id;
4985 author = blame->commit->author;
4986 filename = blame->commit->filename;
4987 time = &blame->commit->time;
4988 id_type = BLAME_COLOR((long) blame->commit);
4991 if (draw_date(view, time))
4992 return TRUE;
4994 if (draw_author(view, author))
4995 return TRUE;
4997 if (draw_filename(view, filename, state->auto_filename_display))
4998 return TRUE;
5000 if (draw_id_custom(view, id_type, id, opt_id_cols))
5001 return TRUE;
5003 if (draw_lineno(view, lineno))
5004 return TRUE;
5006 draw_text(view, LINE_DEFAULT, blame->text);
5007 return TRUE;
5010 static bool
5011 check_blame_commit(struct blame *blame, bool check_null_id)
5013 if (!blame->commit)
5014 report("Commit data not loaded yet");
5015 else if (check_null_id && string_rev_is_null(blame->commit->id))
5016 report("No commit exist for the selected line");
5017 else
5018 return TRUE;
5019 return FALSE;
5022 static void
5023 setup_blame_parent_line(struct view *view, struct blame *blame)
5025 char from[SIZEOF_REF + SIZEOF_STR];
5026 char to[SIZEOF_REF + SIZEOF_STR];
5027 const char *diff_tree_argv[] = {
5028 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
5029 "--no-color", "-U0", from, to, "--", NULL
5031 struct io io;
5032 int parent_lineno = -1;
5033 int blamed_lineno = -1;
5034 char *line;
5036 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5037 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5038 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
5039 return;
5041 while ((line = io_get(&io, '\n', TRUE))) {
5042 if (*line == '@') {
5043 char *pos = strchr(line, '+');
5045 parent_lineno = atoi(line + 4);
5046 if (pos)
5047 blamed_lineno = atoi(pos + 1);
5049 } else if (*line == '+' && parent_lineno != -1) {
5050 if (blame->lineno == blamed_lineno - 1 &&
5051 !strcmp(blame->text, line + 1)) {
5052 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5053 break;
5055 blamed_lineno++;
5059 io_done(&io);
5062 static void
5063 blame_go_forward(struct view *view, struct blame *blame, bool parent)
5065 struct blame_state *state = view->private;
5066 struct blame_history_state *history_state = &state->history_state;
5067 struct blame_commit *commit = blame->commit;
5068 const char *id = parent ? commit->parent_id : commit->id;
5069 const char *filename = parent ? commit->parent_filename : commit->filename;
5071 if (!*id && parent) {
5072 report("The selected commit has no parents");
5073 return;
5076 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
5077 report("The selected commit is already displayed");
5078 return;
5081 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
5082 report("Failed to save current view state");
5083 return;
5086 string_ncopy(opt_ref, id, sizeof(commit->id));
5087 string_ncopy(opt_file, filename, strlen(filename));
5088 if (parent)
5089 setup_blame_parent_line(view, blame);
5090 opt_goto_line = blame->lineno;
5091 reload_view(view);
5094 static void
5095 blame_go_back(struct view *view)
5097 struct blame_history_state history_state;
5099 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
5100 report("Already at start of history");
5101 return;
5104 string_copy(opt_ref, history_state.id);
5105 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
5106 opt_goto_line = view->pos.lineno;
5107 reload_view(view);
5110 static enum request
5111 blame_request(struct view *view, enum request request, struct line *line)
5113 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5114 struct blame *blame = line->data;
5116 switch (request) {
5117 case REQ_VIEW_BLAME:
5118 case REQ_PARENT:
5119 if (!check_blame_commit(blame, TRUE))
5120 break;
5121 blame_go_forward(view, blame, request == REQ_PARENT);
5122 break;
5124 case REQ_BACK:
5125 blame_go_back(view);
5126 break;
5128 case REQ_ENTER:
5129 if (!check_blame_commit(blame, FALSE))
5130 break;
5132 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5133 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5134 break;
5136 if (string_rev_is_null(blame->commit->id)) {
5137 struct view *diff = VIEW(REQ_VIEW_DIFF);
5138 const char *diff_parent_argv[] = {
5139 GIT_DIFF_BLAME(encoding_arg,
5140 opt_diff_context_arg,
5141 opt_ignore_space_arg, view->vid)
5143 const char *diff_no_parent_argv[] = {
5144 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
5145 opt_diff_context_arg,
5146 opt_ignore_space_arg, view->vid)
5148 const char **diff_index_argv = *blame->commit->parent_id
5149 ? diff_parent_argv : diff_no_parent_argv;
5151 open_argv(view, diff, diff_index_argv, NULL, flags);
5152 if (diff->pipe)
5153 string_copy_rev(diff->ref, NULL_ID);
5154 } else {
5155 open_view(view, REQ_VIEW_DIFF, flags);
5157 break;
5159 default:
5160 return request;
5163 return REQ_NONE;
5166 static bool
5167 blame_grep(struct view *view, struct line *line)
5169 struct blame *blame = line->data;
5170 struct blame_commit *commit = blame->commit;
5171 const char *text[] = {
5172 blame->text,
5173 commit ? commit->title : "",
5174 commit ? commit->id : "",
5175 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
5176 commit ? mkdate(&commit->time, opt_date) : "",
5177 NULL
5180 return grep_text(view, text);
5183 static void
5184 blame_select(struct view *view, struct line *line)
5186 struct blame *blame = line->data;
5187 struct blame_commit *commit = blame->commit;
5189 if (!commit)
5190 return;
5192 if (string_rev_is_null(commit->id))
5193 string_ncopy(ref_commit, "HEAD", 4);
5194 else
5195 string_copy_rev(ref_commit, commit->id);
5198 static struct view_ops blame_ops = {
5199 "line",
5200 { "blame" },
5201 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
5202 sizeof(struct blame_state),
5203 blame_open,
5204 blame_read,
5205 blame_draw,
5206 blame_request,
5207 blame_grep,
5208 blame_select,
5212 * Branch backend
5215 struct branch {
5216 const struct ident *author; /* Author of the last commit. */
5217 struct time time; /* Date of the last activity. */
5218 char title[128]; /* First line of the commit message. */
5219 const struct ref *ref; /* Name and commit ID information. */
5222 static const struct ref branch_all;
5223 #define BRANCH_ALL_NAME "All branches"
5224 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5226 static const enum sort_field branch_sort_fields[] = {
5227 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5229 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5231 struct branch_state {
5232 char id[SIZEOF_REV];
5233 size_t max_ref_length;
5236 static int
5237 branch_compare(const void *l1, const void *l2)
5239 const struct branch *branch1 = ((const struct line *) l1)->data;
5240 const struct branch *branch2 = ((const struct line *) l2)->data;
5242 if (branch_is_all(branch1))
5243 return -1;
5244 else if (branch_is_all(branch2))
5245 return 1;
5247 switch (get_sort_field(branch_sort_state)) {
5248 case ORDERBY_DATE:
5249 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5251 case ORDERBY_AUTHOR:
5252 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
5254 case ORDERBY_NAME:
5255 default:
5256 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5260 static bool
5261 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5263 struct branch_state *state = view->private;
5264 struct branch *branch = line->data;
5265 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5266 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
5268 if (draw_lineno(view, lineno))
5269 return TRUE;
5271 if (draw_date(view, &branch->time))
5272 return TRUE;
5274 if (draw_author(view, branch->author))
5275 return TRUE;
5277 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
5278 return TRUE;
5280 if (draw_id(view, branch->ref->id))
5281 return TRUE;
5283 draw_text(view, LINE_DEFAULT, branch->title);
5284 return TRUE;
5287 static enum request
5288 branch_request(struct view *view, enum request request, struct line *line)
5290 struct branch *branch = line->data;
5292 switch (request) {
5293 case REQ_REFRESH:
5294 load_refs(TRUE);
5295 refresh_view(view);
5296 return REQ_NONE;
5298 case REQ_TOGGLE_SORT_FIELD:
5299 case REQ_TOGGLE_SORT_ORDER:
5300 sort_view(view, request, &branch_sort_state, branch_compare);
5301 return REQ_NONE;
5303 case REQ_ENTER:
5305 const struct ref *ref = branch->ref;
5306 const char *all_branches_argv[] = {
5307 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
5309 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5311 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5312 return REQ_NONE;
5314 case REQ_JUMP_COMMIT:
5316 int lineno;
5318 for (lineno = 0; lineno < view->lines; lineno++) {
5319 struct branch *branch = view->line[lineno].data;
5321 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5322 select_view_line(view, lineno);
5323 report_clear();
5324 return REQ_NONE;
5328 default:
5329 return request;
5333 static bool
5334 branch_read(struct view *view, char *line)
5336 struct branch_state *state = view->private;
5337 const char *title = NULL;
5338 const struct ident *author = NULL;
5339 struct time time = {};
5340 size_t i;
5342 if (!line)
5343 return TRUE;
5345 switch (get_line_type(line)) {
5346 case LINE_COMMIT:
5347 string_copy_rev_from_commit_line(state->id, line);
5348 return TRUE;
5350 case LINE_AUTHOR:
5351 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5352 break;
5354 default:
5355 title = line + STRING_SIZE("title ");
5358 for (i = 0; i < view->lines; i++) {
5359 struct branch *branch = view->line[i].data;
5361 if (strcmp(branch->ref->id, state->id))
5362 continue;
5364 if (author) {
5365 branch->author = author;
5366 branch->time = time;
5369 if (title)
5370 string_expand(branch->title, sizeof(branch->title), title, 1);
5372 view->line[i].dirty = TRUE;
5375 return TRUE;
5378 static bool
5379 branch_open_visitor(void *data, const struct ref *ref)
5381 struct view *view = data;
5382 struct branch_state *state = view->private;
5383 struct branch *branch;
5384 bool is_all = ref == &branch_all;
5385 size_t ref_length;
5387 if (ref->tag || ref->ltag)
5388 return TRUE;
5390 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
5391 return FALSE;
5393 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
5394 if (ref_length > state->max_ref_length)
5395 state->max_ref_length = ref_length;
5397 branch->ref = ref;
5398 return TRUE;
5401 static bool
5402 branch_open(struct view *view, enum open_flags flags)
5404 const char *branch_log[] = {
5405 "git", "log", encoding_arg, "--no-color", "--date=raw",
5406 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5407 "--all", "--simplify-by-decoration", NULL
5410 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5411 report("Failed to load branch data");
5412 return FALSE;
5415 branch_open_visitor(view, &branch_all);
5416 foreach_ref(branch_open_visitor, view);
5418 return TRUE;
5421 static bool
5422 branch_grep(struct view *view, struct line *line)
5424 struct branch *branch = line->data;
5425 const char *text[] = {
5426 branch->ref->name,
5427 mkauthor(branch->author, opt_author_width, opt_author),
5428 NULL
5431 return grep_text(view, text);
5434 static void
5435 branch_select(struct view *view, struct line *line)
5437 struct branch *branch = line->data;
5439 if (branch_is_all(branch)) {
5440 string_copy(view->ref, BRANCH_ALL_NAME);
5441 return;
5443 string_copy_rev(view->ref, branch->ref->id);
5444 string_copy_rev(ref_commit, branch->ref->id);
5445 string_copy_rev(ref_head, branch->ref->id);
5446 string_copy_rev(ref_branch, branch->ref->name);
5449 static struct view_ops branch_ops = {
5450 "branch",
5451 { "branch" },
5452 VIEW_REFRESH,
5453 sizeof(struct branch_state),
5454 branch_open,
5455 branch_read,
5456 branch_draw,
5457 branch_request,
5458 branch_grep,
5459 branch_select,
5463 * Status backend
5466 struct status {
5467 char status;
5468 struct {
5469 mode_t mode;
5470 char rev[SIZEOF_REV];
5471 char name[SIZEOF_STR];
5472 } old;
5473 struct {
5474 mode_t mode;
5475 char rev[SIZEOF_REV];
5476 char name[SIZEOF_STR];
5477 } new;
5480 static char status_onbranch[SIZEOF_STR];
5481 static struct status stage_status;
5482 static enum line_type stage_line_type;
5484 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5486 /* This should work even for the "On branch" line. */
5487 static inline bool
5488 status_has_none(struct view *view, struct line *line)
5490 return view_has_line(view, line) && !line[1].data;
5493 /* Get fields from the diff line:
5494 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5496 static inline bool
5497 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5499 const char *old_mode = buf + 1;
5500 const char *new_mode = buf + 8;
5501 const char *old_rev = buf + 15;
5502 const char *new_rev = buf + 56;
5503 const char *status = buf + 97;
5505 if (bufsize < 98 ||
5506 old_mode[-1] != ':' ||
5507 new_mode[-1] != ' ' ||
5508 old_rev[-1] != ' ' ||
5509 new_rev[-1] != ' ' ||
5510 status[-1] != ' ')
5511 return FALSE;
5513 file->status = *status;
5515 string_copy_rev(file->old.rev, old_rev);
5516 string_copy_rev(file->new.rev, new_rev);
5518 file->old.mode = strtoul(old_mode, NULL, 8);
5519 file->new.mode = strtoul(new_mode, NULL, 8);
5521 file->old.name[0] = file->new.name[0] = 0;
5523 return TRUE;
5526 static bool
5527 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5529 struct status *unmerged = NULL;
5530 char *buf;
5531 struct io io;
5533 if (!io_run(&io, IO_RD, repo.cdup, opt_env, argv))
5534 return FALSE;
5536 add_line_nodata(view, type);
5538 while ((buf = io_get(&io, 0, TRUE))) {
5539 struct status *file = unmerged;
5541 if (!file) {
5542 if (!add_line_alloc(view, &file, type, 0, FALSE))
5543 goto error_out;
5546 /* Parse diff info part. */
5547 if (status) {
5548 file->status = status;
5549 if (status == 'A')
5550 string_copy(file->old.rev, NULL_ID);
5552 } else if (!file->status || file == unmerged) {
5553 if (!status_get_diff(file, buf, strlen(buf)))
5554 goto error_out;
5556 buf = io_get(&io, 0, TRUE);
5557 if (!buf)
5558 break;
5560 /* Collapse all modified entries that follow an
5561 * associated unmerged entry. */
5562 if (unmerged == file) {
5563 unmerged->status = 'U';
5564 unmerged = NULL;
5565 } else if (file->status == 'U') {
5566 unmerged = file;
5570 /* Grab the old name for rename/copy. */
5571 if (!*file->old.name &&
5572 (file->status == 'R' || file->status == 'C')) {
5573 string_ncopy(file->old.name, buf, strlen(buf));
5575 buf = io_get(&io, 0, TRUE);
5576 if (!buf)
5577 break;
5580 /* git-ls-files just delivers a NUL separated list of
5581 * file names similar to the second half of the
5582 * git-diff-* output. */
5583 string_ncopy(file->new.name, buf, strlen(buf));
5584 if (!*file->old.name)
5585 string_copy(file->old.name, file->new.name);
5586 file = NULL;
5589 if (io_error(&io)) {
5590 error_out:
5591 io_done(&io);
5592 return FALSE;
5595 if (!view->line[view->lines - 1].data)
5596 add_line_nodata(view, LINE_STAT_NONE);
5598 io_done(&io);
5599 return TRUE;
5602 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5603 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5605 static const char *status_list_other_argv[] = {
5606 "git", "ls-files", "-z", "--others", "--exclude-standard", repo.prefix, NULL, NULL,
5609 static const char *status_list_no_head_argv[] = {
5610 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5613 static const char *update_index_argv[] = {
5614 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5617 /* Restore the previous line number to stay in the context or select a
5618 * line with something that can be updated. */
5619 static void
5620 status_restore(struct view *view)
5622 if (!check_position(&view->prev_pos))
5623 return;
5625 if (view->prev_pos.lineno >= view->lines)
5626 view->prev_pos.lineno = view->lines - 1;
5627 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5628 view->prev_pos.lineno++;
5629 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5630 view->prev_pos.lineno--;
5632 /* If the above fails, always skip the "On branch" line. */
5633 if (view->prev_pos.lineno < view->lines)
5634 view->pos.lineno = view->prev_pos.lineno;
5635 else
5636 view->pos.lineno = 1;
5638 if (view->prev_pos.offset > view->pos.lineno)
5639 view->pos.offset = view->pos.lineno;
5640 else if (view->prev_pos.offset < view->lines)
5641 view->pos.offset = view->prev_pos.offset;
5643 clear_position(&view->prev_pos);
5646 static void
5647 status_update_onbranch(void)
5649 static const char *paths[][2] = {
5650 { "rebase-apply/rebasing", "Rebasing" },
5651 { "rebase-apply/applying", "Applying mailbox" },
5652 { "rebase-apply/", "Rebasing mailbox" },
5653 { "rebase-merge/interactive", "Interactive rebase" },
5654 { "rebase-merge/", "Rebase merge" },
5655 { "MERGE_HEAD", "Merging" },
5656 { "BISECT_LOG", "Bisecting" },
5657 { "HEAD", "On branch" },
5659 char buf[SIZEOF_STR];
5660 struct stat stat;
5661 int i;
5663 if (is_initial_commit()) {
5664 string_copy(status_onbranch, "Initial commit");
5665 return;
5668 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5669 char *head = repo.head;
5671 if (!string_format(buf, "%s/%s", repo.git_dir, paths[i][0]) ||
5672 lstat(buf, &stat) < 0)
5673 continue;
5675 if (!*repo.head) {
5676 struct io io;
5678 if (io_open(&io, "%s/rebase-merge/head-name", repo.git_dir) &&
5679 io_read_buf(&io, buf, sizeof(buf))) {
5680 head = buf;
5681 if (!prefixcmp(head, "refs/heads/"))
5682 head += STRING_SIZE("refs/heads/");
5686 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5687 string_copy(status_onbranch, repo.head);
5688 return;
5691 string_copy(status_onbranch, "Not currently on any branch");
5694 /* First parse staged info using git-diff-index(1), then parse unstaged
5695 * info using git-diff-files(1), and finally untracked files using
5696 * git-ls-files(1). */
5697 static bool
5698 status_open(struct view *view, enum open_flags flags)
5700 const char **staged_argv = is_initial_commit() ?
5701 status_list_no_head_argv : status_diff_index_argv;
5702 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
5704 if (repo.is_inside_work_tree == FALSE) {
5705 report("The status view requires a working tree");
5706 return FALSE;
5709 reset_view(view);
5711 add_line_nodata(view, LINE_STAT_HEAD);
5712 status_update_onbranch();
5714 io_run_bg(update_index_argv);
5716 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
5717 opt_untracked_dirs_content ? NULL : "--directory";
5719 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
5720 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5721 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
5722 report("Failed to load status data");
5723 return FALSE;
5726 /* Restore the exact position or use the specialized restore
5727 * mode? */
5728 status_restore(view);
5729 return TRUE;
5732 static bool
5733 status_draw(struct view *view, struct line *line, unsigned int lineno)
5735 struct status *status = line->data;
5736 enum line_type type;
5737 const char *text;
5739 if (!status) {
5740 switch (line->type) {
5741 case LINE_STAT_STAGED:
5742 type = LINE_STAT_SECTION;
5743 text = "Changes to be committed:";
5744 break;
5746 case LINE_STAT_UNSTAGED:
5747 type = LINE_STAT_SECTION;
5748 text = "Changed but not updated:";
5749 break;
5751 case LINE_STAT_UNTRACKED:
5752 type = LINE_STAT_SECTION;
5753 text = "Untracked files:";
5754 break;
5756 case LINE_STAT_NONE:
5757 type = LINE_DEFAULT;
5758 text = " (no files)";
5759 break;
5761 case LINE_STAT_HEAD:
5762 type = LINE_STAT_HEAD;
5763 text = status_onbranch;
5764 break;
5766 default:
5767 return FALSE;
5769 } else {
5770 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5772 buf[0] = status->status;
5773 if (draw_text(view, line->type, buf))
5774 return TRUE;
5775 type = LINE_DEFAULT;
5776 text = status->new.name;
5779 draw_text(view, type, text);
5780 return TRUE;
5783 static enum request
5784 status_enter(struct view *view, struct line *line)
5786 struct status *status = line->data;
5787 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5789 if (line->type == LINE_STAT_NONE ||
5790 (!status && line[1].type == LINE_STAT_NONE)) {
5791 report("No file to diff");
5792 return REQ_NONE;
5795 switch (line->type) {
5796 case LINE_STAT_STAGED:
5797 case LINE_STAT_UNSTAGED:
5798 break;
5800 case LINE_STAT_UNTRACKED:
5801 if (!status) {
5802 report("No file to show");
5803 return REQ_NONE;
5806 if (!suffixcmp(status->new.name, -1, "/")) {
5807 report("Cannot display a directory");
5808 return REQ_NONE;
5810 break;
5812 case LINE_STAT_HEAD:
5813 return REQ_NONE;
5815 default:
5816 die("line type %d not handled in switch", line->type);
5819 if (status) {
5820 stage_status = *status;
5821 } else {
5822 memset(&stage_status, 0, sizeof(stage_status));
5825 stage_line_type = line->type;
5827 open_view(view, REQ_VIEW_STAGE, flags);
5828 return REQ_NONE;
5831 static bool
5832 status_exists(struct view *view, struct status *status, enum line_type type)
5834 unsigned long lineno;
5836 for (lineno = 0; lineno < view->lines; lineno++) {
5837 struct line *line = &view->line[lineno];
5838 struct status *pos = line->data;
5840 if (line->type != type)
5841 continue;
5842 if (!pos && (!status || !status->status) && line[1].data) {
5843 select_view_line(view, lineno);
5844 return TRUE;
5846 if (pos && !strcmp(status->new.name, pos->new.name)) {
5847 select_view_line(view, lineno);
5848 return TRUE;
5852 return FALSE;
5856 static bool
5857 status_update_prepare(struct io *io, enum line_type type)
5859 const char *staged_argv[] = {
5860 "git", "update-index", "-z", "--index-info", NULL
5862 const char *others_argv[] = {
5863 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5866 switch (type) {
5867 case LINE_STAT_STAGED:
5868 return io_run(io, IO_WR, repo.cdup, opt_env, staged_argv);
5870 case LINE_STAT_UNSTAGED:
5871 case LINE_STAT_UNTRACKED:
5872 return io_run(io, IO_WR, repo.cdup, opt_env, others_argv);
5874 default:
5875 die("line type %d not handled in switch", type);
5876 return FALSE;
5880 static bool
5881 status_update_write(struct io *io, struct status *status, enum line_type type)
5883 switch (type) {
5884 case LINE_STAT_STAGED:
5885 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5886 status->old.rev, status->old.name, 0);
5888 case LINE_STAT_UNSTAGED:
5889 case LINE_STAT_UNTRACKED:
5890 return io_printf(io, "%s%c", status->new.name, 0);
5892 default:
5893 die("line type %d not handled in switch", type);
5894 return FALSE;
5898 static bool
5899 status_update_file(struct status *status, enum line_type type)
5901 struct io io;
5902 bool result;
5904 if (!status_update_prepare(&io, type))
5905 return FALSE;
5907 result = status_update_write(&io, status, type);
5908 return io_done(&io) && result;
5911 static bool
5912 status_update_files(struct view *view, struct line *line)
5914 char buf[sizeof(view->ref)];
5915 struct io io;
5916 bool result = TRUE;
5917 struct line *pos;
5918 int files = 0;
5919 int file, done;
5920 int cursor_y = -1, cursor_x = -1;
5922 if (!status_update_prepare(&io, line->type))
5923 return FALSE;
5925 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
5926 files++;
5928 string_copy(buf, view->ref);
5929 getsyx(cursor_y, cursor_x);
5930 for (file = 0, done = 5; result && file < files; line++, file++) {
5931 int almost_done = file * 100 / files;
5933 if (almost_done > done) {
5934 done = almost_done;
5935 string_format(view->ref, "updating file %u of %u (%d%% done)",
5936 file, files, done);
5937 update_view_title(view);
5938 setsyx(cursor_y, cursor_x);
5939 doupdate();
5941 result = status_update_write(&io, line->data, line->type);
5943 string_copy(view->ref, buf);
5945 return io_done(&io) && result;
5948 static bool
5949 status_update(struct view *view)
5951 struct line *line = &view->line[view->pos.lineno];
5953 assert(view->lines);
5955 if (!line->data) {
5956 if (status_has_none(view, line)) {
5957 report("Nothing to update");
5958 return FALSE;
5961 if (!status_update_files(view, line + 1)) {
5962 report("Failed to update file status");
5963 return FALSE;
5966 } else if (!status_update_file(line->data, line->type)) {
5967 report("Failed to update file status");
5968 return FALSE;
5971 return TRUE;
5974 static bool
5975 status_revert(struct status *status, enum line_type type, bool has_none)
5977 if (!status || type != LINE_STAT_UNSTAGED) {
5978 if (type == LINE_STAT_STAGED) {
5979 report("Cannot revert changes to staged files");
5980 } else if (type == LINE_STAT_UNTRACKED) {
5981 report("Cannot revert changes to untracked files");
5982 } else if (has_none) {
5983 report("Nothing to revert");
5984 } else {
5985 report("Cannot revert changes to multiple files");
5988 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5989 char mode[10] = "100644";
5990 const char *reset_argv[] = {
5991 "git", "update-index", "--cacheinfo", mode,
5992 status->old.rev, status->old.name, NULL
5994 const char *checkout_argv[] = {
5995 "git", "checkout", "--", status->old.name, NULL
5998 if (status->status == 'U') {
5999 string_format(mode, "%5o", status->old.mode);
6001 if (status->old.mode == 0 && status->new.mode == 0) {
6002 reset_argv[2] = "--force-remove";
6003 reset_argv[3] = status->old.name;
6004 reset_argv[4] = NULL;
6007 if (!io_run_fg(reset_argv, repo.cdup))
6008 return FALSE;
6009 if (status->old.mode == 0 && status->new.mode == 0)
6010 return TRUE;
6013 return io_run_fg(checkout_argv, repo.cdup);
6016 return FALSE;
6019 static enum request
6020 status_request(struct view *view, enum request request, struct line *line)
6022 struct status *status = line->data;
6024 switch (request) {
6025 case REQ_STATUS_UPDATE:
6026 if (!status_update(view))
6027 return REQ_NONE;
6028 break;
6030 case REQ_STATUS_REVERT:
6031 if (!status_revert(status, line->type, status_has_none(view, line)))
6032 return REQ_NONE;
6033 break;
6035 case REQ_STATUS_MERGE:
6036 if (!status || status->status != 'U') {
6037 report("Merging only possible for files with unmerged status ('U').");
6038 return REQ_NONE;
6040 open_mergetool(status->new.name);
6041 break;
6043 case REQ_EDIT:
6044 if (!status)
6045 return request;
6046 if (status->status == 'D') {
6047 report("File has been deleted.");
6048 return REQ_NONE;
6051 open_editor(status->new.name, 0);
6052 break;
6054 case REQ_VIEW_BLAME:
6055 if (line->type == LINE_STAT_UNTRACKED || !status) {
6056 report("Nothing to blame here");
6057 return REQ_NONE;
6059 if (status)
6060 opt_ref[0] = 0;
6061 return request;
6063 case REQ_ENTER:
6064 /* After returning the status view has been split to
6065 * show the stage view. No further reloading is
6066 * necessary. */
6067 return status_enter(view, line);
6069 case REQ_REFRESH:
6070 /* Load the current branch information and then the view. */
6071 load_refs(TRUE);
6072 break;
6074 default:
6075 return request;
6078 refresh_view(view);
6080 return REQ_NONE;
6083 static bool
6084 status_stage_info_(char *buf, size_t bufsize,
6085 enum line_type type, struct status *status)
6087 const char *file = status ? status->new.name : "";
6088 const char *info;
6090 switch (type) {
6091 case LINE_STAT_STAGED:
6092 if (status && status->status)
6093 info = "Staged changes to %s";
6094 else
6095 info = "Staged changes";
6096 break;
6098 case LINE_STAT_UNSTAGED:
6099 if (status && status->status)
6100 info = "Unstaged changes to %s";
6101 else
6102 info = "Unstaged changes";
6103 break;
6105 case LINE_STAT_UNTRACKED:
6106 info = "Untracked file %s";
6107 break;
6109 case LINE_STAT_HEAD:
6110 default:
6111 info = "";
6114 return string_nformat(buf, bufsize, NULL, info, file);
6116 #define status_stage_info(buf, type, status) \
6117 status_stage_info_(buf, sizeof(buf), type, status)
6119 static void
6120 status_select(struct view *view, struct line *line)
6122 struct status *status = line->data;
6123 char file[SIZEOF_STR] = "all files";
6124 const char *text;
6125 const char *key;
6127 if (status && !string_format(file, "'%s'", status->new.name))
6128 return;
6130 if (!status && line[1].type == LINE_STAT_NONE)
6131 line++;
6133 switch (line->type) {
6134 case LINE_STAT_STAGED:
6135 text = "Press %s to unstage %s for commit";
6136 break;
6138 case LINE_STAT_UNSTAGED:
6139 text = "Press %s to stage %s for commit";
6140 break;
6142 case LINE_STAT_UNTRACKED:
6143 text = "Press %s to stage %s for addition";
6144 break;
6146 case LINE_STAT_HEAD:
6147 case LINE_STAT_NONE:
6148 text = "Nothing to update";
6149 break;
6151 default:
6152 die("line type %d not handled in switch", line->type);
6155 if (status && status->status == 'U') {
6156 text = "Press %s to resolve conflict in %s";
6157 key = get_view_key(view, REQ_STATUS_MERGE);
6159 } else {
6160 key = get_view_key(view, REQ_STATUS_UPDATE);
6163 string_format(view->ref, text, key, file);
6164 status_stage_info(ref_status, line->type, status);
6165 if (status)
6166 string_copy(opt_file, status->new.name);
6169 static bool
6170 status_grep(struct view *view, struct line *line)
6172 struct status *status = line->data;
6174 if (status) {
6175 const char buf[2] = { status->status, 0 };
6176 const char *text[] = { status->new.name, buf, NULL };
6178 return grep_text(view, text);
6181 return FALSE;
6184 static struct view_ops status_ops = {
6185 "file",
6186 { "status" },
6187 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE | VIEW_REFRESH,
6189 status_open,
6190 NULL,
6191 status_draw,
6192 status_request,
6193 status_grep,
6194 status_select,
6198 struct stage_state {
6199 struct diff_state diff;
6200 size_t chunks;
6201 int *chunk;
6204 static bool
6205 stage_diff_write(struct io *io, struct line *line, struct line *end)
6207 while (line < end) {
6208 if (!io_write(io, line->data, strlen(line->data)) ||
6209 !io_write(io, "\n", 1))
6210 return FALSE;
6211 line++;
6212 if (line->type == LINE_DIFF_CHUNK ||
6213 line->type == LINE_DIFF_HEADER)
6214 break;
6217 return TRUE;
6220 static bool
6221 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6223 const char *apply_argv[SIZEOF_ARG] = {
6224 "git", "apply", "--whitespace=nowarn", NULL
6226 struct line *diff_hdr;
6227 struct io io;
6228 int argc = 3;
6230 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6231 if (!diff_hdr)
6232 return FALSE;
6234 if (!revert)
6235 apply_argv[argc++] = "--cached";
6236 if (line != NULL)
6237 apply_argv[argc++] = "--unidiff-zero";
6238 if (revert || stage_line_type == LINE_STAT_STAGED)
6239 apply_argv[argc++] = "-R";
6240 apply_argv[argc++] = "-";
6241 apply_argv[argc++] = NULL;
6242 if (!io_run(&io, IO_WR, repo.cdup, opt_env, apply_argv))
6243 return FALSE;
6245 if (line != NULL) {
6246 unsigned long lineno = 0;
6247 struct line *context = chunk + 1;
6248 const char *markers[] = {
6249 line->type == LINE_DIFF_DEL ? "" : ",0",
6250 line->type == LINE_DIFF_DEL ? ",0" : "",
6253 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6255 while (context < line) {
6256 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6257 break;
6258 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6259 lineno++;
6261 context++;
6264 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6265 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
6266 lineno, markers[0], lineno, markers[1]) ||
6267 !stage_diff_write(&io, line, line + 1)) {
6268 chunk = NULL;
6270 } else {
6271 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6272 !stage_diff_write(&io, chunk, view->line + view->lines))
6273 chunk = NULL;
6276 io_done(&io);
6278 return chunk ? TRUE : FALSE;
6281 static bool
6282 stage_update(struct view *view, struct line *line, bool single)
6284 struct line *chunk = NULL;
6286 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6287 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6289 if (chunk) {
6290 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6291 report("Failed to apply chunk");
6292 return FALSE;
6295 } else if (!stage_status.status) {
6296 view = view->parent;
6298 for (line = view->line; view_has_line(view, line); line++)
6299 if (line->type == stage_line_type)
6300 break;
6302 if (!status_update_files(view, line + 1)) {
6303 report("Failed to update files");
6304 return FALSE;
6307 } else if (!status_update_file(&stage_status, stage_line_type)) {
6308 report("Failed to update file");
6309 return FALSE;
6312 return TRUE;
6315 static bool
6316 stage_revert(struct view *view, struct line *line)
6318 struct line *chunk = NULL;
6320 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6321 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6323 if (chunk) {
6324 if (!prompt_yesno("Are you sure you want to revert changes?"))
6325 return FALSE;
6327 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6328 report("Failed to revert chunk");
6329 return FALSE;
6331 return TRUE;
6333 } else {
6334 return status_revert(stage_status.status ? &stage_status : NULL,
6335 stage_line_type, FALSE);
6340 static void
6341 stage_next(struct view *view, struct line *line)
6343 struct stage_state *state = view->private;
6344 int i;
6346 if (!state->chunks) {
6347 for (line = view->line; view_has_line(view, line); line++) {
6348 if (line->type != LINE_DIFF_CHUNK)
6349 continue;
6351 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6352 report("Allocation failure");
6353 return;
6356 state->chunk[state->chunks++] = line - view->line;
6360 for (i = 0; i < state->chunks; i++) {
6361 if (state->chunk[i] > view->pos.lineno) {
6362 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6363 report("Chunk %d of %zd", i + 1, state->chunks);
6364 return;
6368 report("No next chunk found");
6371 static struct line *
6372 stage_insert_chunk(struct view *view, struct chunk_header *header,
6373 struct line *from, struct line *to, struct line *last_unchanged_line)
6375 char buf[SIZEOF_STR];
6376 char *chunk_line;
6377 unsigned long from_lineno = last_unchanged_line - view->line;
6378 unsigned long to_lineno = to - view->line;
6379 unsigned long after_lineno = to_lineno;
6381 if (!string_format(buf, "@@ -%lu,%lu +%lu,%lu @@",
6382 header->old.position, header->old.lines,
6383 header->new.position, header->new.lines))
6384 return NULL;
6386 chunk_line = strdup(buf);
6387 if (!chunk_line)
6388 return NULL;
6390 free(from->data);
6391 from->data = chunk_line;
6393 if (!to)
6394 return from;
6396 if (!add_line_at(view, after_lineno++, buf, LINE_DIFF_CHUNK, strlen(buf) + 1, FALSE))
6397 return NULL;
6399 while (from_lineno < to_lineno) {
6400 struct line *line = &view->line[from_lineno++];
6402 if (!add_line_at(view, after_lineno++, line->data, line->type, strlen(line->data) + 1, FALSE))
6403 return FALSE;
6406 return view->line + after_lineno;
6409 static void
6410 stage_split_chunk(struct view *view, struct line *chunk_start)
6412 struct chunk_header header;
6413 struct line *last_changed_line = NULL, *last_unchanged_line = NULL, *pos;
6414 int chunks = 0;
6416 if (!chunk_start || !parse_chunk_header(&header, chunk_start->data)) {
6417 report("Failed to parse chunk header");
6418 return;
6421 header.old.lines = header.new.lines = 0;
6423 for (pos = chunk_start + 1; view_has_line(view, pos); pos++) {
6424 const char *chunk_line = pos->data;
6426 if (*chunk_line == '@' || *chunk_line == '\\')
6427 break;
6429 if (*chunk_line == ' ') {
6430 header.old.lines++;
6431 header.new.lines++;
6432 if (last_unchanged_line < last_changed_line)
6433 last_unchanged_line = pos;
6434 continue;
6437 if (last_changed_line && last_changed_line < last_unchanged_line) {
6438 unsigned long chunk_start_lineno = pos - view->line;
6439 unsigned long diff = pos - last_unchanged_line;
6441 pos = stage_insert_chunk(view, &header, chunk_start, pos, last_unchanged_line);
6443 header.old.position += header.old.lines - diff;
6444 header.new.position += header.new.lines - diff;
6445 header.old.lines = header.new.lines = diff;
6447 chunk_start = view->line + chunk_start_lineno;
6448 last_changed_line = last_unchanged_line = NULL;
6449 chunks++;
6452 if (*chunk_line == '-') {
6453 header.old.lines++;
6454 last_changed_line = pos;
6455 } else if (*chunk_line == '+') {
6456 header.new.lines++;
6457 last_changed_line = pos;
6461 if (chunks) {
6462 stage_insert_chunk(view, &header, chunk_start, NULL, NULL);
6463 redraw_view(view);
6464 report("Split the chunk in %d", chunks + 1);
6465 } else {
6466 report("The chunk cannot be split");
6470 static enum request
6471 stage_request(struct view *view, enum request request, struct line *line)
6473 switch (request) {
6474 case REQ_STATUS_UPDATE:
6475 if (!stage_update(view, line, FALSE))
6476 return REQ_NONE;
6477 break;
6479 case REQ_STATUS_REVERT:
6480 if (!stage_revert(view, line))
6481 return REQ_NONE;
6482 break;
6484 case REQ_STAGE_UPDATE_LINE:
6485 if (stage_line_type == LINE_STAT_UNTRACKED ||
6486 stage_status.status == 'A') {
6487 report("Staging single lines is not supported for new files");
6488 return REQ_NONE;
6490 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6491 report("Please select a change to stage");
6492 return REQ_NONE;
6494 if (!stage_update(view, line, TRUE))
6495 return REQ_NONE;
6496 break;
6498 case REQ_STAGE_NEXT:
6499 if (stage_line_type == LINE_STAT_UNTRACKED) {
6500 report("File is untracked; press %s to add",
6501 get_view_key(view, REQ_STATUS_UPDATE));
6502 return REQ_NONE;
6504 stage_next(view, line);
6505 return REQ_NONE;
6507 case REQ_STAGE_SPLIT_CHUNK:
6508 if (stage_line_type == LINE_STAT_UNTRACKED ||
6509 !(line = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK))) {
6510 report("No chunks to split in sight");
6511 return REQ_NONE;
6513 stage_split_chunk(view, line);
6514 return REQ_NONE;
6516 case REQ_EDIT:
6517 if (!stage_status.new.name[0])
6518 return diff_common_edit(view, request, line);
6520 if (stage_status.status == 'D') {
6521 report("File has been deleted.");
6522 return REQ_NONE;
6525 if (stage_line_type == LINE_STAT_UNTRACKED) {
6526 open_editor(stage_status.new.name, (line - view->line) + 1);
6527 } else {
6528 open_editor(stage_status.new.name, diff_get_lineno(view, line));
6530 break;
6532 case REQ_REFRESH:
6533 /* Reload everything(including current branch information) ... */
6534 load_refs(TRUE);
6535 break;
6537 case REQ_VIEW_BLAME:
6538 if (stage_line_type == LINE_STAT_UNTRACKED) {
6539 report("Nothing to blame here");
6540 return REQ_NONE;
6543 if (stage_status.new.name[0]) {
6544 string_copy(opt_file, stage_status.new.name);
6545 } else {
6546 const char *file = diff_get_pathname(view, line);
6548 if (file)
6549 string_copy(opt_file, file);
6552 opt_ref[0] = 0;
6553 opt_goto_line = diff_get_lineno(view, line);
6554 if (opt_goto_line > 0)
6555 opt_goto_line--;
6556 return request;
6558 case REQ_ENTER:
6559 return diff_common_enter(view, request, line);
6561 case REQ_DIFF_CONTEXT_UP:
6562 case REQ_DIFF_CONTEXT_DOWN:
6563 if (!update_diff_context(request))
6564 return REQ_NONE;
6565 break;
6567 default:
6568 return request;
6571 refresh_view(view->parent);
6573 /* Check whether the staged entry still exists, and close the
6574 * stage view if it doesn't. */
6575 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6576 status_restore(view->parent);
6577 return REQ_VIEW_CLOSE;
6580 refresh_view(view);
6582 return REQ_NONE;
6585 static bool
6586 stage_open(struct view *view, enum open_flags flags)
6588 static const char *no_head_diff_argv[] = {
6589 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6590 stage_status.new.name)
6592 static const char *index_show_argv[] = {
6593 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6594 stage_status.old.name, stage_status.new.name)
6596 static const char *files_show_argv[] = {
6597 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6598 stage_status.old.name, stage_status.new.name)
6600 /* Diffs for unmerged entries are empty when passing the new
6601 * path, so leave out the new path. */
6602 static const char *files_unmerged_argv[] = {
6603 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
6604 opt_diff_context_arg, opt_ignore_space_arg, "--",
6605 stage_status.old.name, NULL
6607 static const char *file_argv[] = { repo.cdup, stage_status.new.name, NULL };
6608 const char **argv = NULL;
6610 if (!stage_line_type) {
6611 report("No stage content, press %s to open the status view and choose file",
6612 get_view_key(view, REQ_VIEW_STATUS));
6613 return FALSE;
6616 view->encoding = NULL;
6618 switch (stage_line_type) {
6619 case LINE_STAT_STAGED:
6620 if (is_initial_commit()) {
6621 argv = no_head_diff_argv;
6622 } else {
6623 argv = index_show_argv;
6625 break;
6627 case LINE_STAT_UNSTAGED:
6628 if (stage_status.status != 'U')
6629 argv = files_show_argv;
6630 else
6631 argv = files_unmerged_argv;
6632 break;
6634 case LINE_STAT_UNTRACKED:
6635 argv = file_argv;
6636 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
6637 break;
6639 case LINE_STAT_HEAD:
6640 default:
6641 die("line type %d not handled in switch", stage_line_type);
6644 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
6645 || !argv_copy(&view->argv, argv)) {
6646 report("Failed to open staged view");
6647 return FALSE;
6650 view->vid[0] = 0;
6651 view->dir = repo.cdup;
6652 return begin_update(view, NULL, NULL, flags);
6655 static bool
6656 stage_read(struct view *view, char *data)
6658 struct stage_state *state = view->private;
6660 if (stage_line_type == LINE_STAT_UNTRACKED)
6661 return pager_common_read(view, data, LINE_DEFAULT);
6663 if (data && diff_common_read(view, data, &state->diff))
6664 return TRUE;
6666 return pager_read(view, data);
6669 static struct view_ops stage_ops = {
6670 "line",
6671 { "stage" },
6672 VIEW_DIFF_LIKE | VIEW_REFRESH,
6673 sizeof(struct stage_state),
6674 stage_open,
6675 stage_read,
6676 diff_common_draw,
6677 stage_request,
6678 pager_grep,
6679 pager_select,
6684 * Revision graph
6687 static const enum line_type graph_colors[] = {
6688 LINE_PALETTE_0,
6689 LINE_PALETTE_1,
6690 LINE_PALETTE_2,
6691 LINE_PALETTE_3,
6692 LINE_PALETTE_4,
6693 LINE_PALETTE_5,
6694 LINE_PALETTE_6,
6697 static enum line_type get_graph_color(struct graph_symbol *symbol)
6699 if (symbol->commit)
6700 return LINE_GRAPH_COMMIT;
6701 assert(symbol->color < ARRAY_SIZE(graph_colors));
6702 return graph_colors[symbol->color];
6705 static bool
6706 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6708 const char *chars = graph_symbol_to_utf8(symbol);
6710 return draw_text(view, color, chars + !!first);
6713 static bool
6714 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6716 const char *chars = graph_symbol_to_ascii(symbol);
6718 return draw_text(view, color, chars + !!first);
6721 static bool
6722 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6724 const chtype *chars = graph_symbol_to_chtype(symbol);
6726 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6729 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6731 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6733 static const draw_graph_fn fns[] = {
6734 draw_graph_ascii,
6735 draw_graph_chtype,
6736 draw_graph_utf8
6738 draw_graph_fn fn = fns[opt_line_graphics];
6739 int i;
6741 for (i = 0; i < canvas->size; i++) {
6742 struct graph_symbol *symbol = &canvas->symbols[i];
6743 enum line_type color = get_graph_color(symbol);
6745 if (fn(view, symbol, color, i == 0))
6746 return TRUE;
6749 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6753 * Main view backend
6756 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
6758 struct commit {
6759 char id[SIZEOF_REV]; /* SHA1 ID. */
6760 const struct ident *author; /* Author of the commit. */
6761 struct time time; /* Date from the author ident. */
6762 struct graph_canvas graph; /* Ancestry chain graphics. */
6763 char title[1]; /* First line of the commit message. */
6766 struct main_state {
6767 struct graph graph;
6768 struct commit current;
6769 char **reflog;
6770 size_t reflogs;
6771 int reflog_width;
6772 char reflogmsg[SIZEOF_STR / 2];
6773 bool in_header;
6774 bool added_changes_commits;
6775 bool with_graph;
6778 static void
6779 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
6781 struct main_state *state = view->private;
6783 string_copy_rev(commit->id, ids);
6784 if (state->with_graph)
6785 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
6788 static struct commit *
6789 main_add_commit(struct view *view, enum line_type type, struct commit *template,
6790 const char *title, bool custom)
6792 struct main_state *state = view->private;
6793 size_t titlelen = strlen(title);
6794 struct commit *commit;
6795 char buf[SIZEOF_STR / 2];
6797 /* FIXME: More graceful handling of titles; append "..." to
6798 * shortened titles, etc. */
6799 string_expand(buf, sizeof(buf), title, 1);
6800 title = buf;
6801 titlelen = strlen(title);
6803 if (!add_line_alloc(view, &commit, type, titlelen, custom))
6804 return NULL;
6806 *commit = *template;
6807 strncpy(commit->title, title, titlelen);
6808 state->graph.canvas = &commit->graph;
6809 memset(template, 0, sizeof(*template));
6810 state->reflogmsg[0] = 0;
6811 return commit;
6814 static inline void
6815 main_flush_commit(struct view *view, struct commit *commit)
6817 if (*commit->id)
6818 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
6821 static bool
6822 main_has_changes(const char *argv[])
6824 struct io io;
6826 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
6827 return FALSE;
6828 io_done(&io);
6829 return io.status == 1;
6832 static void
6833 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6835 char ids[SIZEOF_STR] = NULL_ID " ";
6836 struct main_state *state = view->private;
6837 struct commit commit = {};
6838 struct timeval now;
6839 struct timezone tz;
6841 if (!parent)
6842 return;
6844 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6846 if (!gettimeofday(&now, &tz)) {
6847 commit.time.tz = tz.tz_minuteswest * 60;
6848 commit.time.sec = now.tv_sec - commit.time.tz;
6851 commit.author = &unknown_ident;
6852 main_register_commit(view, &commit, ids, FALSE);
6853 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
6854 graph_render_parents(&state->graph);
6857 static void
6858 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
6860 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6861 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6862 const char *staged_parent = NULL_ID;
6863 const char *unstaged_parent = parent;
6865 if (!is_head_commit(parent))
6866 return;
6868 state->added_changes_commits = TRUE;
6870 io_run_bg(update_index_argv);
6872 if (!main_has_changes(unstaged_argv)) {
6873 unstaged_parent = NULL;
6874 staged_parent = parent;
6877 if (!main_has_changes(staged_argv)) {
6878 staged_parent = NULL;
6881 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6882 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6885 static bool
6886 main_open(struct view *view, enum open_flags flags)
6888 static const char *main_argv[] = {
6889 GIT_MAIN_LOG(encoding_arg, "%(cmdlineargs)", "%(revargs)", "%(fileargs)")
6891 struct main_state *state = view->private;
6893 state->with_graph = opt_rev_graph &&
6894 opt_commit_order != COMMIT_ORDER_REVERSE;
6896 if (flags & OPEN_PAGER_MODE) {
6897 state->added_changes_commits = TRUE;
6898 state->with_graph = FALSE;
6901 return begin_update(view, NULL, main_argv, flags);
6904 static void
6905 main_done(struct view *view)
6907 struct main_state *state = view->private;
6908 int i;
6910 for (i = 0; i < view->lines; i++) {
6911 struct commit *commit = view->line[i].data;
6913 free(commit->graph.symbols);
6916 for (i = 0; i < state->reflogs; i++)
6917 free(state->reflog[i]);
6918 free(state->reflog);
6921 #define MAIN_NO_COMMIT_REFS 1
6922 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
6923 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
6925 static inline struct ref_list *
6926 main_get_commit_refs(struct line *line, struct commit *commit)
6928 struct ref_list *refs = NULL;
6930 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
6931 main_mark_no_commit_refs(line);
6933 return refs;
6936 static bool
6937 main_draw(struct view *view, struct line *line, unsigned int lineno)
6939 struct main_state *state = view->private;
6940 struct commit *commit = line->data;
6941 struct ref_list *refs = NULL;
6943 if (!commit->author)
6944 return FALSE;
6946 if (draw_lineno(view, lineno))
6947 return TRUE;
6949 if (opt_show_id) {
6950 if (state->reflogs) {
6951 const char *id = state->reflog[line->lineno - 1];
6953 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
6954 return TRUE;
6955 } else if (draw_id(view, commit->id)) {
6956 return TRUE;
6960 if (draw_date(view, &commit->time))
6961 return TRUE;
6963 if (draw_author(view, commit->author))
6964 return TRUE;
6966 if (state->with_graph && draw_graph(view, &commit->graph))
6967 return TRUE;
6969 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
6970 return TRUE;
6972 if (commit->title)
6973 draw_commit_title(view, commit->title, 0);
6974 return TRUE;
6977 static bool
6978 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
6980 char *end = strchr(reflog, ' ');
6981 int id_width;
6983 if (!end)
6984 return FALSE;
6985 *end = 0;
6987 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
6988 || !(reflog = strdup(reflog)))
6989 return FALSE;
6991 state->reflog[state->reflogs++] = reflog;
6992 id_width = strlen(reflog);
6993 if (state->reflog_width < id_width) {
6994 state->reflog_width = id_width;
6995 if (opt_show_id)
6996 view->force_redraw = TRUE;
6999 return TRUE;
7002 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7003 static bool
7004 main_read(struct view *view, char *line)
7006 struct main_state *state = view->private;
7007 struct graph *graph = &state->graph;
7008 enum line_type type;
7009 struct commit *commit = &state->current;
7011 if (!line) {
7012 main_flush_commit(view, commit);
7014 if (!view->lines && !view->prev)
7015 die("No revisions match the given arguments.");
7016 if (view->lines > 0) {
7017 struct commit *last = view->line[view->lines - 1].data;
7019 view->line[view->lines - 1].dirty = 1;
7020 if (!last->author) {
7021 view->lines--;
7022 free(last);
7026 if (state->with_graph)
7027 done_graph(graph);
7028 return TRUE;
7031 type = get_line_type(line);
7032 if (type == LINE_COMMIT) {
7033 bool is_boundary;
7035 state->in_header = TRUE;
7036 line += STRING_SIZE("commit ");
7037 is_boundary = *line == '-';
7038 while (*line && !isalnum(*line))
7039 line++;
7041 if (!state->added_changes_commits && opt_show_changes && repo.is_inside_work_tree)
7042 main_add_changes_commits(view, state, line);
7043 else
7044 main_flush_commit(view, commit);
7046 main_register_commit(view, &state->current, line, is_boundary);
7047 return TRUE;
7050 if (!*commit->id)
7051 return TRUE;
7053 /* Empty line separates the commit header from the log itself. */
7054 if (*line == '\0')
7055 state->in_header = FALSE;
7057 switch (type) {
7058 case LINE_PP_REFLOG:
7059 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
7060 return FALSE;
7061 break;
7063 case LINE_PP_REFLOGMSG:
7064 line += STRING_SIZE("Reflog message: ");
7065 string_ncopy(state->reflogmsg, line, strlen(line));
7066 break;
7068 case LINE_PARENT:
7069 if (state->with_graph && !graph->has_parents)
7070 graph_add_parent(graph, line + STRING_SIZE("parent "));
7071 break;
7073 case LINE_AUTHOR:
7074 parse_author_line(line + STRING_SIZE("author "),
7075 &commit->author, &commit->time);
7076 if (state->with_graph)
7077 graph_render_parents(graph);
7078 break;
7080 default:
7081 /* Fill in the commit title if it has not already been set. */
7082 if (*commit->title)
7083 break;
7085 /* Skip lines in the commit header. */
7086 if (state->in_header)
7087 break;
7089 /* Require titles to start with a non-space character at the
7090 * offset used by git log. */
7091 if (strncmp(line, " ", 4))
7092 break;
7093 line += 4;
7094 /* Well, if the title starts with a whitespace character,
7095 * try to be forgiving. Otherwise we end up with no title. */
7096 while (isspace(*line))
7097 line++;
7098 if (*line == '\0')
7099 break;
7100 if (*state->reflogmsg)
7101 line = state->reflogmsg;
7102 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
7105 return TRUE;
7108 static enum request
7109 main_request(struct view *view, enum request request, struct line *line)
7111 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7112 ? OPEN_SPLIT : OPEN_DEFAULT;
7114 switch (request) {
7115 case REQ_NEXT:
7116 case REQ_PREVIOUS:
7117 if (view_is_displayed(view) && display[0] != view)
7118 return request;
7119 /* Do not pass navigation requests to the branch view
7120 * when the main view is maximized. (GH #38) */
7121 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
7123 case REQ_VIEW_DIFF:
7124 case REQ_ENTER:
7125 if (view_is_displayed(view) && display[0] != view)
7126 maximize_view(view, TRUE);
7128 if (line->type == LINE_STAT_UNSTAGED
7129 || line->type == LINE_STAT_STAGED) {
7130 struct view *diff = VIEW(REQ_VIEW_DIFF);
7131 const char *diff_staged_argv[] = {
7132 GIT_DIFF_STAGED(encoding_arg,
7133 opt_diff_context_arg,
7134 opt_ignore_space_arg, NULL, NULL)
7136 const char *diff_unstaged_argv[] = {
7137 GIT_DIFF_UNSTAGED(encoding_arg,
7138 opt_diff_context_arg,
7139 opt_ignore_space_arg, NULL, NULL)
7141 const char **diff_argv = line->type == LINE_STAT_STAGED
7142 ? diff_staged_argv : diff_unstaged_argv;
7144 open_argv(view, diff, diff_argv, NULL, flags);
7145 break;
7148 open_view(view, REQ_VIEW_DIFF, flags);
7149 break;
7151 case REQ_REFRESH:
7152 load_refs(TRUE);
7153 refresh_view(view);
7154 break;
7156 case REQ_JUMP_COMMIT:
7158 int lineno;
7160 for (lineno = 0; lineno < view->lines; lineno++) {
7161 struct commit *commit = view->line[lineno].data;
7163 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7164 select_view_line(view, lineno);
7165 report_clear();
7166 return REQ_NONE;
7170 report("Unable to find commit '%s'", opt_search);
7171 break;
7173 default:
7174 return request;
7177 return REQ_NONE;
7180 static bool
7181 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
7183 struct ref_list *list;
7184 regmatch_t pmatch;
7185 size_t i;
7187 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
7188 return FALSE;
7190 for (i = 0; i < list->size; i++) {
7191 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
7192 return TRUE;
7195 return FALSE;
7198 static bool
7199 main_grep(struct view *view, struct line *line)
7201 struct commit *commit = line->data;
7202 const char *text[] = {
7203 commit->id,
7204 commit->title,
7205 mkauthor(commit->author, opt_author_width, opt_author),
7206 mkdate(&commit->time, opt_date),
7207 NULL
7210 return grep_text(view, text) || grep_refs(line, commit, view->regex);
7213 static struct ref *
7214 main_get_commit_branch(struct line *line, struct commit *commit)
7216 struct ref_list *list = main_get_commit_refs(line, commit);
7217 struct ref *branch = NULL;
7218 size_t i;
7220 for (i = 0; list && i < list->size; i++) {
7221 struct ref *ref = list->refs[i];
7223 switch (get_line_type_from_ref(ref)) {
7224 case LINE_MAIN_HEAD:
7225 case LINE_MAIN_REF:
7226 /* Always prefer local branches. */
7227 return ref;
7229 default:
7230 branch = ref;
7234 return branch;
7237 static void
7238 main_select(struct view *view, struct line *line)
7240 struct commit *commit = line->data;
7242 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED) {
7243 string_ncopy(view->ref, commit->title, strlen(commit->title));
7244 } else {
7245 struct ref *branch = main_get_commit_branch(line, commit);
7247 if (branch)
7248 string_copy_rev(ref_branch, branch->name);
7249 string_copy_rev(view->ref, commit->id);
7251 string_copy_rev(ref_commit, commit->id);
7254 static struct view_ops main_ops = {
7255 "commit",
7256 { "main" },
7257 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE | VIEW_REFRESH,
7258 sizeof(struct main_state),
7259 main_open,
7260 main_read,
7261 main_draw,
7262 main_request,
7263 main_grep,
7264 main_select,
7265 main_done,
7268 static bool
7269 stash_open(struct view *view, enum open_flags flags)
7271 static const char *stash_argv[] = { "git", "stash", "list",
7272 encoding_arg, "--no-color", "--pretty=raw", NULL };
7273 struct main_state *state = view->private;
7275 state->added_changes_commits = TRUE;
7276 state->with_graph = FALSE;
7277 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
7280 static void
7281 stash_select(struct view *view, struct line *line)
7283 main_select(view, line);
7284 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
7285 string_copy(view->ref, ref_stash);
7288 static struct view_ops stash_ops = {
7289 "stash",
7290 { "stash" },
7291 VIEW_SEND_CHILD_ENTER | VIEW_REFRESH,
7292 sizeof(struct main_state),
7293 stash_open,
7294 main_read,
7295 main_draw,
7296 main_request,
7297 main_grep,
7298 stash_select,
7302 * Status management
7305 /* Whether or not the curses interface has been initialized. */
7306 static bool cursed = FALSE;
7308 /* Terminal hacks and workarounds. */
7309 static bool use_scroll_redrawwin;
7310 static bool use_scroll_status_wclear;
7312 /* The status window is used for polling keystrokes. */
7313 static WINDOW *status_win;
7315 /* Reading from the prompt? */
7316 static bool input_mode = FALSE;
7318 static bool status_empty = FALSE;
7320 /* Update status and title window. */
7321 static void
7322 report(const char *msg, ...)
7324 struct view *view = display[current_view];
7326 if (input_mode)
7327 return;
7329 if (!view) {
7330 char buf[SIZEOF_STR];
7331 int retval;
7333 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7334 die("%s", buf);
7337 if (!status_empty || *msg) {
7338 va_list args;
7340 va_start(args, msg);
7342 wmove(status_win, 0, 0);
7343 if (view->has_scrolled && use_scroll_status_wclear)
7344 wclear(status_win);
7345 if (*msg) {
7346 vwprintw(status_win, msg, args);
7347 status_empty = FALSE;
7348 } else {
7349 status_empty = TRUE;
7351 wclrtoeol(status_win);
7352 wnoutrefresh(status_win);
7354 va_end(args);
7357 update_view_title(view);
7360 static void
7361 done_display(void)
7363 endwin();
7366 static void
7367 init_display(void)
7369 const char *term;
7370 int x, y;
7372 die_callback = done_display;
7374 /* Initialize the curses library */
7375 if (isatty(STDIN_FILENO)) {
7376 cursed = !!initscr();
7377 opt_tty = stdin;
7378 } else {
7379 /* Leave stdin and stdout alone when acting as a pager. */
7380 opt_tty = fopen("/dev/tty", "r+");
7381 if (!opt_tty)
7382 die("Failed to open /dev/tty");
7383 cursed = !!newterm(NULL, opt_tty, opt_tty);
7386 if (!cursed)
7387 die("Failed to initialize curses");
7389 nonl(); /* Disable conversion and detect newlines from input. */
7390 cbreak(); /* Take input chars one at a time, no wait for \n */
7391 noecho(); /* Don't echo input */
7392 leaveok(stdscr, FALSE);
7394 if (has_colors())
7395 init_colors();
7397 getmaxyx(stdscr, y, x);
7398 status_win = newwin(1, x, y - 1, 0);
7399 if (!status_win)
7400 die("Failed to create status window");
7402 /* Enable keyboard mapping */
7403 keypad(status_win, TRUE);
7404 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7405 #ifdef NCURSES_MOUSE_VERSION
7406 /* Enable mouse */
7407 if (opt_mouse){
7408 mousemask(ALL_MOUSE_EVENTS, NULL);
7409 mouseinterval(0);
7411 #endif
7413 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7414 set_tabsize(opt_tab_size);
7415 #else
7416 TABSIZE = opt_tab_size;
7417 #endif
7419 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7420 if (term && !strcmp(term, "gnome-terminal")) {
7421 /* In the gnome-terminal-emulator, the message from
7422 * scrolling up one line when impossible followed by
7423 * scrolling down one line causes corruption of the
7424 * status line. This is fixed by calling wclear. */
7425 use_scroll_status_wclear = TRUE;
7426 use_scroll_redrawwin = FALSE;
7428 } else if (term && !strcmp(term, "xrvt-xpm")) {
7429 /* No problems with full optimizations in xrvt-(unicode)
7430 * and aterm. */
7431 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7433 } else {
7434 /* When scrolling in (u)xterm the last line in the
7435 * scrolling direction will update slowly. */
7436 use_scroll_redrawwin = TRUE;
7437 use_scroll_status_wclear = FALSE;
7441 static int
7442 get_input(int prompt_position)
7444 struct view *view;
7445 int i, key, cursor_y, cursor_x;
7447 if (prompt_position)
7448 input_mode = TRUE;
7450 while (TRUE) {
7451 bool loading = FALSE;
7453 foreach_view (view, i) {
7454 update_view(view);
7455 if (view_is_displayed(view) && view->has_scrolled &&
7456 use_scroll_redrawwin)
7457 redrawwin(view->win);
7458 view->has_scrolled = FALSE;
7459 if (view->pipe)
7460 loading = TRUE;
7463 /* Update the cursor position. */
7464 if (prompt_position) {
7465 getbegyx(status_win, cursor_y, cursor_x);
7466 cursor_x = prompt_position;
7467 } else {
7468 view = display[current_view];
7469 getbegyx(view->win, cursor_y, cursor_x);
7470 cursor_x = view->width - 1;
7471 cursor_y += view->pos.lineno - view->pos.offset;
7473 setsyx(cursor_y, cursor_x);
7475 /* Refresh, accept single keystroke of input */
7476 doupdate();
7477 nodelay(status_win, loading);
7478 key = wgetch(status_win);
7480 /* wgetch() with nodelay() enabled returns ERR when
7481 * there's no input. */
7482 if (key == ERR) {
7484 } else if (key == KEY_RESIZE) {
7485 int height, width;
7487 getmaxyx(stdscr, height, width);
7489 wresize(status_win, 1, width);
7490 mvwin(status_win, height - 1, 0);
7491 wnoutrefresh(status_win);
7492 resize_display();
7493 redraw_display(TRUE);
7495 } else {
7496 input_mode = FALSE;
7497 if (key == erasechar())
7498 key = KEY_BACKSPACE;
7499 return key;
7504 static char *
7505 prompt_input(const char *prompt, input_handler handler, void *data)
7507 enum input_status status = INPUT_OK;
7508 static char buf[SIZEOF_STR];
7509 size_t pos = 0;
7511 buf[pos] = 0;
7513 while (status == INPUT_OK || status == INPUT_SKIP) {
7514 int key;
7516 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7517 wclrtoeol(status_win);
7519 key = get_input(pos + 1);
7520 switch (key) {
7521 case KEY_RETURN:
7522 case KEY_ENTER:
7523 case '\n':
7524 status = pos ? INPUT_STOP : INPUT_CANCEL;
7525 break;
7527 case KEY_BACKSPACE:
7528 if (pos > 0)
7529 buf[--pos] = 0;
7530 else
7531 status = INPUT_CANCEL;
7532 break;
7534 case KEY_ESC:
7535 status = INPUT_CANCEL;
7536 break;
7538 default:
7539 if (pos >= sizeof(buf)) {
7540 report("Input string too long");
7541 return NULL;
7544 status = handler(data, buf, key);
7545 if (status == INPUT_OK)
7546 buf[pos++] = (char) key;
7550 /* Clear the status window */
7551 status_empty = FALSE;
7552 report_clear();
7554 if (status == INPUT_CANCEL)
7555 return NULL;
7557 buf[pos++] = 0;
7559 return buf;
7562 static enum input_status
7563 prompt_yesno_handler(void *data, char *buf, int c)
7565 if (c == 'y' || c == 'Y')
7566 return INPUT_STOP;
7567 if (c == 'n' || c == 'N')
7568 return INPUT_CANCEL;
7569 return INPUT_SKIP;
7572 static bool
7573 prompt_yesno(const char *prompt)
7575 char prompt2[SIZEOF_STR];
7577 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7578 return FALSE;
7580 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7583 static enum input_status
7584 read_prompt_handler(void *data, char *buf, int c)
7586 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7589 static char *
7590 read_prompt(const char *prompt)
7592 return prompt_input(prompt, read_prompt_handler, NULL);
7595 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7597 enum input_status status = INPUT_OK;
7598 int size = 0;
7600 while (items[size].text)
7601 size++;
7603 assert(size > 0);
7605 while (status == INPUT_OK) {
7606 const struct menu_item *item = &items[*selected];
7607 int key;
7608 int i;
7610 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7611 prompt, *selected + 1, size);
7612 if (item->hotkey)
7613 wprintw(status_win, "[%c] ", (char) item->hotkey);
7614 wprintw(status_win, "%s", item->text);
7615 wclrtoeol(status_win);
7617 key = get_input(COLS - 1);
7618 switch (key) {
7619 case KEY_RETURN:
7620 case KEY_ENTER:
7621 case '\n':
7622 status = INPUT_STOP;
7623 break;
7625 case KEY_LEFT:
7626 case KEY_UP:
7627 *selected = *selected - 1;
7628 if (*selected < 0)
7629 *selected = size - 1;
7630 break;
7632 case KEY_RIGHT:
7633 case KEY_DOWN:
7634 *selected = (*selected + 1) % size;
7635 break;
7637 case KEY_ESC:
7638 status = INPUT_CANCEL;
7639 break;
7641 default:
7642 for (i = 0; items[i].text; i++)
7643 if (items[i].hotkey == key) {
7644 *selected = i;
7645 status = INPUT_STOP;
7646 break;
7651 /* Clear the status window */
7652 status_empty = FALSE;
7653 report_clear();
7655 return status != INPUT_CANCEL;
7659 * Repository properties
7663 static void
7664 set_remote_branch(const char *name, const char *value, size_t valuelen)
7666 if (!strcmp(name, ".remote")) {
7667 string_ncopy(repo.remote, value, valuelen);
7669 } else if (*repo.remote && !strcmp(name, ".merge")) {
7670 size_t from = strlen(repo.remote);
7672 if (!prefixcmp(value, "refs/heads/"))
7673 value += STRING_SIZE("refs/heads/");
7675 if (!string_format_from(repo.remote, &from, "/%s", value))
7676 repo.remote[0] = 0;
7680 static void
7681 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
7683 const char *argv[SIZEOF_ARG] = { name, "=" };
7684 int argc = 1 + (cmd == option_set_command);
7685 enum status_code error;
7687 if (!argv_from_string(argv, &argc, value))
7688 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
7689 else
7690 error = cmd(argc, argv);
7692 if (error != SUCCESS)
7693 warn("Option 'tig.%s': %s", name, get_status_message(error));
7696 static void
7697 set_work_tree(const char *value)
7699 char cwd[SIZEOF_STR];
7701 if (!getcwd(cwd, sizeof(cwd)))
7702 die("Failed to get cwd path: %s", strerror(errno));
7703 if (chdir(cwd) < 0)
7704 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7705 if (chdir(repo.git_dir) < 0)
7706 die("Failed to chdir(%s): %s", repo.git_dir, strerror(errno));
7707 if (!getcwd(repo.git_dir, sizeof(repo.git_dir)))
7708 die("Failed to get git path: %s", strerror(errno));
7709 if (chdir(value) < 0)
7710 die("Failed to chdir(%s): %s", value, strerror(errno));
7711 if (!getcwd(cwd, sizeof(cwd)))
7712 die("Failed to get cwd path: %s", strerror(errno));
7713 if (setenv("GIT_WORK_TREE", cwd, TRUE))
7714 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7715 if (setenv("GIT_DIR", repo.git_dir, TRUE))
7716 die("Failed to set GIT_DIR to '%s'", repo.git_dir);
7717 repo.is_inside_work_tree = TRUE;
7720 static void
7721 parse_git_color_option(enum line_type type, char *value)
7723 struct line_info *info = get_line_info(type);
7724 const char *argv[SIZEOF_ARG];
7725 int argc = 0;
7726 bool first_color = TRUE;
7727 int i;
7729 if (!argv_from_string(argv, &argc, value))
7730 return;
7732 info->fg = COLOR_DEFAULT;
7733 info->bg = COLOR_DEFAULT;
7734 info->attr = 0;
7736 for (i = 0; i < argc; i++) {
7737 int attr = 0;
7739 if (set_attribute(&attr, argv[i])) {
7740 info->attr |= attr;
7742 } else if (set_color(&attr, argv[i])) {
7743 if (first_color)
7744 info->fg = attr;
7745 else
7746 info->bg = attr;
7747 first_color = FALSE;
7752 static void
7753 set_git_color_option(const char *name, char *value)
7755 static const struct enum_map_entry color_option_map[] = {
7756 ENUM_MAP_ENTRY("branch.current", LINE_MAIN_HEAD),
7757 ENUM_MAP_ENTRY("branch.local", LINE_MAIN_REF),
7758 ENUM_MAP_ENTRY("branch.plain", LINE_MAIN_REF),
7759 ENUM_MAP_ENTRY("branch.remote", LINE_MAIN_REMOTE),
7761 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_HEADER),
7762 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_INDEX),
7763 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_OLDMODE),
7764 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_NEWMODE),
7765 ENUM_MAP_ENTRY("diff.frag", LINE_DIFF_CHUNK),
7766 ENUM_MAP_ENTRY("diff.old", LINE_DIFF_DEL),
7767 ENUM_MAP_ENTRY("diff.new", LINE_DIFF_ADD),
7769 //ENUM_MAP_ENTRY("diff.commit", LINE_DIFF_ADD),
7771 ENUM_MAP_ENTRY("status.branch", LINE_STAT_HEAD),
7772 //ENUM_MAP_ENTRY("status.nobranch", LINE_STAT_HEAD),
7773 ENUM_MAP_ENTRY("status.added", LINE_STAT_STAGED),
7774 ENUM_MAP_ENTRY("status.updated", LINE_STAT_STAGED),
7775 ENUM_MAP_ENTRY("status.changed", LINE_STAT_UNSTAGED),
7776 ENUM_MAP_ENTRY("status.untracked", LINE_STAT_UNTRACKED),
7778 int type = LINE_NONE;
7780 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7781 parse_git_color_option(type, value);
7785 static void
7786 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
7788 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
7789 encoding_arg[0] = 0;
7792 static int
7793 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7795 if (!strcmp(name, "i18n.commitencoding"))
7796 set_encoding(&default_encoding, value, FALSE);
7798 else if (!strcmp(name, "gui.encoding"))
7799 set_encoding(&default_encoding, value, TRUE);
7801 else if (!strcmp(name, "core.editor"))
7802 string_ncopy(opt_editor, value, valuelen);
7804 else if (!strcmp(name, "core.worktree"))
7805 set_work_tree(value);
7807 else if (!strcmp(name, "core.abbrev"))
7808 parse_id(&opt_id_cols, value);
7810 else if (!prefixcmp(name, "tig.color."))
7811 set_repo_config_option(name + 10, value, option_color_command);
7813 else if (!prefixcmp(name, "tig.bind."))
7814 set_repo_config_option(name + 9, value, option_bind_command);
7816 else if (!prefixcmp(name, "tig."))
7817 set_repo_config_option(name + 4, value, option_set_command);
7819 else if (!prefixcmp(name, "color."))
7820 set_git_color_option(name + STRING_SIZE("color."), value);
7822 else if (*repo.head && !prefixcmp(name, "branch.") &&
7823 !strncmp(name + 7, repo.head, strlen(repo.head)))
7824 set_remote_branch(name + 7 + strlen(repo.head), value, valuelen);
7826 return OK;
7829 static int
7830 load_git_config(void)
7832 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7834 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7839 * Main
7842 static const char usage[] =
7843 "tig " TIG_VERSION " (" __DATE__ ")\n"
7844 "\n"
7845 "Usage: tig [options] [revs] [--] [paths]\n"
7846 " or: tig log [options] [revs] [--] [paths]\n"
7847 " or: tig show [options] [revs] [--] [paths]\n"
7848 " or: tig blame [options] [rev] [--] path\n"
7849 " or: tig stash\n"
7850 " or: tig status\n"
7851 " or: tig < [git command output]\n"
7852 "\n"
7853 "Options:\n"
7854 " +<number> Select line <number> in the first view\n"
7855 " -v, --version Show version and exit\n"
7856 " -h, --help Show help message and exit";
7858 static void TIG_NORETURN
7859 quit(int sig)
7861 if (sig)
7862 signal(sig, SIG_DFL);
7864 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7865 if (cursed)
7866 endwin();
7867 exit(0);
7870 static int
7871 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7873 const char ***filter_args = data;
7875 return argv_append(filter_args, name) ? OK : ERR;
7878 static void
7879 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7881 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7882 const char **all_argv = NULL;
7884 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7885 !argv_append_array(&all_argv, argv) ||
7886 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7887 die("Failed to split arguments");
7888 argv_free(all_argv);
7889 free(all_argv);
7892 static bool
7893 is_rev_flag(const char *flag)
7895 static const char *rev_flags[] = { GIT_REV_FLAGS };
7896 int i;
7898 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
7899 if (!strcmp(flag, rev_flags[i]))
7900 return TRUE;
7902 return FALSE;
7905 static void
7906 filter_options(const char *argv[], bool blame)
7908 const char **flags = NULL;
7909 int next, flags_pos;
7911 for (next = flags_pos = 0; argv[next]; next++) {
7912 const char *flag = argv[next];
7913 int value = -1;
7915 if (map_enum(&value, commit_order_arg_map, flag)) {
7916 opt_commit_order = value;
7917 update_commit_order_arg();
7918 continue;
7921 if (map_enum(&value, ignore_space_arg_map, flag)) {
7922 opt_ignore_space = value;
7923 update_ignore_space_arg();
7924 continue;
7927 if (!prefixcmp(flag, "-U")
7928 && parse_int(&value, flag + 2, 0, 999999) == SUCCESS) {
7929 opt_diff_context = value;
7930 update_diff_context_arg(opt_diff_context);
7931 continue;
7934 argv[flags_pos++] = flag;
7937 argv[flags_pos] = NULL;
7939 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7940 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
7942 if (flags) {
7943 for (next = flags_pos = 0; flags && flags[next]; next++) {
7944 const char *flag = flags[next];
7946 if (is_rev_flag(flag))
7947 argv_append(&opt_rev_argv, flag);
7948 else
7949 flags[flags_pos++] = flag;
7952 flags[flags_pos] = NULL;
7954 if (blame)
7955 opt_blame_argv = flags;
7956 else
7957 opt_cmdline_argv = flags;
7960 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7963 static enum request
7964 parse_options(int argc, const char *argv[], bool pager_mode)
7966 enum request request;
7967 const char *subcommand;
7968 bool seen_dashdash = FALSE;
7969 const char **filter_argv = NULL;
7970 int i;
7972 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
7974 if (argc <= 1)
7975 return request;
7977 subcommand = argv[1];
7978 if (!strcmp(subcommand, "status")) {
7979 request = REQ_VIEW_STATUS;
7981 } else if (!strcmp(subcommand, "blame")) {
7982 request = REQ_VIEW_BLAME;
7984 } else if (!strcmp(subcommand, "show")) {
7985 request = REQ_VIEW_DIFF;
7987 } else if (!strcmp(subcommand, "log")) {
7988 request = REQ_VIEW_LOG;
7990 } else if (!strcmp(subcommand, "stash")) {
7991 request = REQ_VIEW_STASH;
7993 } else {
7994 subcommand = NULL;
7997 for (i = 1 + !!subcommand; i < argc; i++) {
7998 const char *opt = argv[i];
8000 // stop parsing our options after -- and let rev-parse handle the rest
8001 if (!seen_dashdash) {
8002 if (!strcmp(opt, "--")) {
8003 seen_dashdash = TRUE;
8004 continue;
8006 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8007 printf("tig version %s\n", TIG_VERSION);
8008 quit(0);
8010 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8011 printf("%s\n", usage);
8012 quit(0);
8014 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8015 opt_lineno = atoi(opt + 1);
8016 continue;
8021 if (!argv_append(&filter_argv, opt))
8022 die("command too long");
8025 if (filter_argv)
8026 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8028 /* Finish validating and setting up blame options */
8029 if (request == REQ_VIEW_BLAME) {
8030 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8031 die("invalid number of options to blame\n\n%s", usage);
8033 if (opt_rev_argv) {
8034 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8037 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8040 return request;
8043 static enum request
8044 open_pager_mode(enum request request)
8046 enum open_flags flags = OPEN_DEFAULT;
8048 if (request == REQ_VIEW_PAGER) {
8049 /* Detect if the user requested the main view. */
8050 if (argv_contains(opt_rev_argv, "--stdin")) {
8051 request = REQ_VIEW_MAIN;
8052 flags |= OPEN_FORWARD_STDIN;
8053 } else if (argv_contains(opt_cmdline_argv, "--pretty=raw")) {
8054 request = REQ_VIEW_MAIN;
8055 flags |= OPEN_STDIN;
8056 } else {
8057 flags |= OPEN_STDIN;
8060 } else if (request == REQ_VIEW_DIFF) {
8061 if (argv_contains(opt_rev_argv, "--stdin"))
8062 flags |= OPEN_FORWARD_STDIN;
8065 /* Open the requested view even if the pager mode is enabled so
8066 * the warning message below is displayed correctly. */
8067 open_view(NULL, request, flags);
8069 if (!open_in_pager_mode(flags)) {
8070 close(STDIN_FILENO);
8071 report("Ignoring stdin.");
8074 return REQ_NONE;
8077 static enum request
8078 run_prompt_command(struct view *view, char *cmd)
8080 enum request request;
8082 if (cmd && string_isnumber(cmd)) {
8083 int lineno = view->pos.lineno + 1;
8085 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
8086 select_view_line(view, lineno - 1);
8087 report_clear();
8088 } else {
8089 report("Unable to parse '%s' as a line number", cmd);
8091 } else if (cmd && iscommit(cmd)) {
8092 string_ncopy(opt_search, cmd, strlen(cmd));
8094 request = view_request(view, REQ_JUMP_COMMIT);
8095 if (request == REQ_JUMP_COMMIT) {
8096 report("Jumping to commits is not supported by the '%s' view", view->name);
8099 } else if (cmd && strlen(cmd) == 1) {
8100 request = get_keybinding(&view->ops->keymap, cmd[0]);
8101 return request;
8103 } else if (cmd && cmd[0] == '!') {
8104 struct view *next = VIEW(REQ_VIEW_PAGER);
8105 const char *argv[SIZEOF_ARG];
8106 int argc = 0;
8108 cmd++;
8109 /* When running random commands, initially show the
8110 * command in the title. However, it maybe later be
8111 * overwritten if a commit line is selected. */
8112 string_ncopy(next->ref, cmd, strlen(cmd));
8114 if (!argv_from_string(argv, &argc, cmd)) {
8115 report("Too many arguments");
8116 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
8117 report("Argument formatting failed");
8118 } else {
8119 next->dir = NULL;
8120 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8123 } else if (cmd) {
8124 request = get_request(cmd);
8125 if (request != REQ_UNKNOWN)
8126 return request;
8128 char *args = strchr(cmd, ' ');
8129 if (args) {
8130 *args++ = 0;
8131 if (set_option(cmd, args) == SUCCESS) {
8132 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
8133 if (!strcmp(cmd, "color"))
8134 init_colors();
8137 return request;
8139 return REQ_NONE;
8142 #ifdef NCURSES_MOUSE_VERSION
8143 static struct view *
8144 find_clicked_view(MEVENT *event)
8146 struct view *view;
8147 int i;
8149 foreach_displayed_view (view, i) {
8150 int beg_y = 0, beg_x = 0;
8152 getbegyx(view->win, beg_y, beg_x);
8154 if (beg_y <= event->y && event->y < beg_y + view->height
8155 && beg_x <= event->x && event->x < beg_x + view->width) {
8156 if (i != current_view) {
8157 current_view = i;
8159 return view;
8163 return NULL;
8166 static enum request
8167 handle_mouse_event(void)
8169 MEVENT event;
8170 struct view *view;
8172 if (getmouse(&event) != OK)
8173 return REQ_NONE;
8175 view = find_clicked_view(&event);
8176 if (!view)
8177 return REQ_NONE;
8179 if (event.bstate & BUTTON2_PRESSED)
8180 return REQ_SCROLL_WHEEL_DOWN;
8182 if (event.bstate & BUTTON4_PRESSED)
8183 return REQ_SCROLL_WHEEL_UP;
8185 if (event.bstate & BUTTON1_PRESSED) {
8186 if (event.y == view->pos.lineno - view->pos.offset) {
8187 /* Click is on the same line, perform an "ENTER" */
8188 return REQ_ENTER;
8190 } else {
8191 int y = getbegy(view->win);
8192 unsigned long lineno = (event.y - y) + view->pos.offset;
8194 select_view_line(view, lineno);
8195 update_view_title(view);
8196 report_clear();
8200 return REQ_NONE;
8202 #endif
8205 main(int argc, const char *argv[])
8207 const char *codeset = ENCODING_UTF8;
8208 bool pager_mode = !isatty(STDIN_FILENO);
8209 enum request request = parse_options(argc, argv, pager_mode);
8210 struct view *view;
8211 int i;
8213 signal(SIGINT, quit);
8214 signal(SIGQUIT, quit);
8215 signal(SIGPIPE, SIG_IGN);
8217 if (setlocale(LC_ALL, "")) {
8218 codeset = nl_langinfo(CODESET);
8221 foreach_view(view, i) {
8222 add_keymap(&view->ops->keymap);
8225 if (load_repo_info() == ERR)
8226 die("Failed to load repo info.");
8228 if (load_options() == ERR)
8229 die("Failed to load user config.");
8231 if (load_git_config() == ERR)
8232 die("Failed to load repo config.");
8234 /* Require a git repository unless when running in pager mode. */
8235 if (!repo.git_dir[0] && request != REQ_VIEW_PAGER)
8236 die("Not a git repository");
8238 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8239 char translit[SIZEOF_STR];
8241 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8242 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8243 else
8244 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8245 if (opt_iconv_out == ICONV_NONE)
8246 die("Failed to initialize character set conversion");
8249 if (load_refs(FALSE) == ERR)
8250 die("Failed to load refs.");
8252 init_display();
8254 if (pager_mode)
8255 request = open_pager_mode(request);
8257 while (view_driver(display[current_view], request)) {
8258 int key = get_input(0);
8260 #ifdef NCURSES_MOUSE_VERSION
8261 if (key == KEY_MOUSE) {
8262 request = handle_mouse_event();
8263 continue;
8265 #endif
8267 if (key == KEY_ESC)
8268 key = get_input(0) + 0x80;
8270 view = display[current_view];
8271 request = get_keybinding(&view->ops->keymap, key);
8273 /* Some low-level request handling. This keeps access to
8274 * status_win restricted. */
8275 switch (request) {
8276 case REQ_NONE:
8277 report("Unknown key, press %s for help",
8278 get_view_key(view, REQ_VIEW_HELP));
8279 break;
8280 case REQ_PROMPT:
8282 char *cmd = read_prompt(":");
8283 request = run_prompt_command(view, cmd);
8284 break;
8286 case REQ_SEARCH:
8287 case REQ_SEARCH_BACK:
8289 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8290 char *search = read_prompt(prompt);
8292 if (search)
8293 string_ncopy(opt_search, search, strlen(search));
8294 else if (*opt_search)
8295 request = request == REQ_SEARCH ?
8296 REQ_FIND_NEXT :
8297 REQ_FIND_PREV;
8298 else
8299 request = REQ_NONE;
8300 break;
8302 default:
8303 break;
8307 quit(0);
8309 return 0;
8312 /* vim: set ts=8 sw=8 noexpandtab: */