Load main view from any --pretty=raw output given on stdin
[tig.git] / tig.c
blobb66e71155c65f5bcae1745dc635dc95b00f8d9d0
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 "io.h"
18 #include "refs.h"
19 #include "graph.h"
20 #include "git.h"
22 static void TIG_NORETURN die(const char *err, ...) PRINTF_LIKE(1, 2);
23 static void warn(const char *msg, ...) PRINTF_LIKE(1, 2);
24 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
25 #define report_clear() report("%s", "")
28 enum input_status {
29 INPUT_OK,
30 INPUT_SKIP,
31 INPUT_STOP,
32 INPUT_CANCEL
35 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
37 static char *prompt_input(const char *prompt, input_handler handler, void *data);
38 static bool prompt_yesno(const char *prompt);
39 static char *read_prompt(const char *prompt);
41 struct menu_item {
42 int hotkey;
43 const char *text;
44 void *data;
47 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
49 #define GRAPHIC_ENUM(_) \
50 _(GRAPHIC, ASCII), \
51 _(GRAPHIC, DEFAULT), \
52 _(GRAPHIC, UTF_8)
54 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
56 #define DATE_ENUM(_) \
57 _(DATE, NO), \
58 _(DATE, DEFAULT), \
59 _(DATE, LOCAL), \
60 _(DATE, RELATIVE), \
61 _(DATE, SHORT)
63 DEFINE_ENUM(date, DATE_ENUM);
65 struct time {
66 time_t sec;
67 int tz;
70 static inline int timecmp(const struct time *t1, const struct time *t2)
72 return t1->sec - t2->sec;
75 static const char *
76 mkdate(const struct time *time, enum date date)
78 static char buf[DATE_WIDTH + 1];
79 static const struct enum_map reldate[] = {
80 { "second", 1, 60 * 2 },
81 { "minute", 60, 60 * 60 * 2 },
82 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
83 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
84 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
85 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
86 { "year", 60 * 60 * 24 * 365, 0 },
88 struct tm tm;
90 if (!date || !time || !time->sec)
91 return "";
93 if (date == DATE_RELATIVE) {
94 struct timeval now;
95 time_t date = time->sec + time->tz;
96 time_t seconds;
97 int i;
99 gettimeofday(&now, NULL);
100 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
101 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
102 if (seconds >= reldate[i].value && reldate[i].value)
103 continue;
105 seconds /= reldate[i].namelen;
106 if (!string_format(buf, "%ld %s%s %s",
107 seconds, reldate[i].name,
108 seconds > 1 ? "s" : "",
109 now.tv_sec >= date ? "ago" : "ahead"))
110 break;
111 return buf;
115 if (date == DATE_LOCAL) {
116 time_t date = time->sec + time->tz;
117 localtime_r(&date, &tm);
119 else {
120 gmtime_r(&time->sec, &tm);
122 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
125 #define FILE_SIZE_ENUM(_) \
126 _(FILE_SIZE, NO), \
127 _(FILE_SIZE, DEFAULT), \
128 _(FILE_SIZE, UNITS)
130 DEFINE_ENUM(file_size, FILE_SIZE_ENUM);
132 static const char *
133 mkfilesize(unsigned long size, enum file_size format)
135 static char buf[64 + 1];
136 static const char relsize[] = {
137 'B', 'K', 'M', 'G', 'T', 'P'
140 if (!format)
141 return "";
143 if (format == FILE_SIZE_UNITS) {
144 const char *fmt = "%.0f%c";
145 double rsize = size;
146 int i;
148 for (i = 0; i < ARRAY_SIZE(relsize); i++) {
149 if (rsize > 1024.0 && i + 1 < ARRAY_SIZE(relsize)) {
150 rsize /= 1024;
151 continue;
154 size = rsize * 10;
155 if (size % 10 > 0)
156 fmt = "%.1f%c";
158 return string_format(buf, fmt, rsize, relsize[i])
159 ? buf : NULL;
163 return string_format(buf, "%ld", size) ? buf : NULL;
166 #define AUTHOR_ENUM(_) \
167 _(AUTHOR, NO), \
168 _(AUTHOR, FULL), \
169 _(AUTHOR, ABBREVIATED), \
170 _(AUTHOR, EMAIL), \
171 _(AUTHOR, EMAIL_USER)
173 DEFINE_ENUM(author, AUTHOR_ENUM);
175 struct ident {
176 const char *name;
177 const char *email;
180 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
182 static inline int
183 ident_compare(const struct ident *i1, const struct ident *i2)
185 if (!i1 || !i2)
186 return (!!i1) - (!!i2);
187 if (!i1->name || !i2->name)
188 return (!!i1->name) - (!!i2->name);
189 return strcmp(i1->name, i2->name);
192 static const char *
193 get_author_initials(const char *author)
195 static char initials[AUTHOR_WIDTH * 6 + 1];
196 size_t pos = 0;
197 const char *end = strchr(author, '\0');
199 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
201 memset(initials, 0, sizeof(initials));
202 while (author < end) {
203 unsigned char bytes;
204 size_t i;
206 while (author < end && is_initial_sep(*author))
207 author++;
209 bytes = utf8_char_length(author, end);
210 if (bytes >= sizeof(initials) - 1 - pos)
211 break;
212 while (bytes--) {
213 initials[pos++] = *author++;
216 i = pos;
217 while (author < end && !is_initial_sep(*author)) {
218 bytes = utf8_char_length(author, end);
219 if (bytes >= sizeof(initials) - 1 - i) {
220 while (author < end && !is_initial_sep(*author))
221 author++;
222 break;
224 while (bytes--) {
225 initials[i++] = *author++;
229 initials[i++] = 0;
232 return initials;
235 static const char *
236 get_email_user(const char *email)
238 static char user[AUTHOR_WIDTH * 6 + 1];
239 const char *end = strchr(email, '@');
240 int length = end ? end - email : strlen(email);
242 string_format(user, "%.*s%c", length, email, 0);
243 return user;
246 #define author_trim(cols) (cols == 0 || cols > 10)
248 static const char *
249 mkauthor(const struct ident *ident, int cols, enum author author)
251 bool trim = author_trim(cols);
252 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
254 if (author == AUTHOR_NO || !ident)
255 return "";
256 if (author == AUTHOR_EMAIL && ident->email)
257 return ident->email;
258 if (author == AUTHOR_EMAIL_USER && ident->email)
259 return get_email_user(ident->email);
260 if (abbreviate && ident->name)
261 return get_author_initials(ident->name);
262 return ident->name;
265 static const char *
266 mkmode(mode_t mode)
268 if (S_ISDIR(mode))
269 return "drwxr-xr-x";
270 else if (S_ISLNK(mode))
271 return "lrwxrwxrwx";
272 else if (S_ISGITLINK(mode))
273 return "m---------";
274 else if (S_ISREG(mode) && mode & S_IXUSR)
275 return "-rwxr-xr-x";
276 else if (S_ISREG(mode))
277 return "-rw-r--r--";
278 else
279 return "----------";
282 static const char *
283 get_temp_dir(void)
285 static const char *tmp;
287 if (tmp)
288 return tmp;
290 if (!tmp)
291 tmp = getenv("TMPDIR");
292 if (!tmp)
293 tmp = getenv("TEMP");
294 if (!tmp)
295 tmp = getenv("TMP");
296 if (!tmp)
297 tmp = "/tmp";
299 return tmp;
302 #define FILENAME_ENUM(_) \
303 _(FILENAME, NO), \
304 _(FILENAME, ALWAYS), \
305 _(FILENAME, AUTO)
307 DEFINE_ENUM(filename, FILENAME_ENUM);
309 #define IGNORE_SPACE_ENUM(_) \
310 _(IGNORE_SPACE, NO), \
311 _(IGNORE_SPACE, ALL), \
312 _(IGNORE_SPACE, SOME), \
313 _(IGNORE_SPACE, AT_EOL)
315 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
317 #define COMMIT_ORDER_ENUM(_) \
318 _(COMMIT_ORDER, DEFAULT), \
319 _(COMMIT_ORDER, TOPO), \
320 _(COMMIT_ORDER, DATE), \
321 _(COMMIT_ORDER, REVERSE)
323 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
325 #define VIEW_INFO(_) \
326 _(MAIN, main, ref_head), \
327 _(DIFF, diff, ref_commit), \
328 _(LOG, log, ref_head), \
329 _(TREE, tree, ref_commit), \
330 _(BLOB, blob, ref_blob), \
331 _(BLAME, blame, ref_commit), \
332 _(BRANCH, branch, ref_head), \
333 _(HELP, help, ""), \
334 _(PAGER, pager, ""), \
335 _(STATUS, status, "status"), \
336 _(STAGE, stage, ref_status), \
337 _(STASH, stash, ref_stash)
339 static struct encoding *
340 get_path_encoding(const char *path, struct encoding *default_encoding)
342 const char *check_attr_argv[] = {
343 "git", "check-attr", "encoding", "--", path, NULL
345 char buf[SIZEOF_STR];
346 char *encoding;
348 /* <path>: encoding: <encoding> */
350 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
351 || !(encoding = strstr(buf, ENCODING_SEP)))
352 return default_encoding;
354 encoding += STRING_SIZE(ENCODING_SEP);
355 if (!strcmp(encoding, ENCODING_UTF8)
356 || !strcmp(encoding, "unspecified")
357 || !strcmp(encoding, "set"))
358 return default_encoding;
360 return encoding_open(encoding);
364 * User requests
367 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
369 #define REQ_INFO \
370 REQ_GROUP("View switching") \
371 VIEW_INFO(VIEW_REQ), \
373 REQ_GROUP("View manipulation") \
374 REQ_(ENTER, "Enter current line and scroll"), \
375 REQ_(NEXT, "Move to next"), \
376 REQ_(PREVIOUS, "Move to previous"), \
377 REQ_(PARENT, "Move to parent"), \
378 REQ_(VIEW_NEXT, "Move focus to next view"), \
379 REQ_(REFRESH, "Reload and refresh"), \
380 REQ_(MAXIMIZE, "Maximize the current view"), \
381 REQ_(VIEW_CLOSE, "Close the current view"), \
382 REQ_(QUIT, "Close all views and quit"), \
384 REQ_GROUP("View specific requests") \
385 REQ_(STATUS_UPDATE, "Update file status"), \
386 REQ_(STATUS_REVERT, "Revert file changes"), \
387 REQ_(STATUS_MERGE, "Merge file using external tool"), \
388 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
389 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
390 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
391 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
393 REQ_GROUP("Cursor navigation") \
394 REQ_(MOVE_UP, "Move cursor one line up"), \
395 REQ_(MOVE_DOWN, "Move cursor one line down"), \
396 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
397 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
398 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
399 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
401 REQ_GROUP("Scrolling") \
402 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
403 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
404 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
405 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
406 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
407 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
408 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
410 REQ_GROUP("Searching") \
411 REQ_(SEARCH, "Search the view"), \
412 REQ_(SEARCH_BACK, "Search backwards in the view"), \
413 REQ_(FIND_NEXT, "Find next search match"), \
414 REQ_(FIND_PREV, "Find previous search match"), \
416 REQ_GROUP("Option manipulation") \
417 REQ_(OPTIONS, "Open option menu"), \
418 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
419 REQ_(TOGGLE_DATE, "Toggle date display"), \
420 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
421 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
422 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
423 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
424 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
425 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
426 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
427 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
428 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
429 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
430 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
431 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
432 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
433 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
434 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
436 REQ_GROUP("Misc") \
437 REQ_(PROMPT, "Bring up the prompt"), \
438 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
439 REQ_(SHOW_VERSION, "Show version information"), \
440 REQ_(STOP_LOADING, "Stop all loading views"), \
441 REQ_(EDIT, "Open in editor"), \
442 REQ_(NONE, "Do nothing")
445 /* User action requests. */
446 enum request {
447 #define REQ_GROUP(help)
448 #define REQ_(req, help) REQ_##req
450 /* Offset all requests to avoid conflicts with ncurses getch values. */
451 REQ_UNKNOWN = KEY_MAX + 1,
452 REQ_OFFSET,
453 REQ_INFO,
455 /* Internal requests. */
456 REQ_JUMP_COMMIT,
458 #undef REQ_GROUP
459 #undef REQ_
462 struct request_info {
463 enum request request;
464 const char *name;
465 int namelen;
466 const char *help;
469 static const struct request_info req_info[] = {
470 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
471 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
472 REQ_INFO
473 #undef REQ_GROUP
474 #undef REQ_
477 static enum request
478 get_request(const char *name)
480 int namelen = strlen(name);
481 int i;
483 for (i = 0; i < ARRAY_SIZE(req_info); i++)
484 if (enum_equals(req_info[i], name, namelen))
485 return req_info[i].request;
487 return REQ_UNKNOWN;
492 * Options
495 /* Option and state variables. */
496 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
497 static enum date opt_date = DATE_DEFAULT;
498 static enum author opt_author = AUTHOR_FULL;
499 static enum filename opt_filename = FILENAME_AUTO;
500 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
501 static bool opt_rev_graph = TRUE;
502 static bool opt_line_number = FALSE;
503 static bool opt_show_refs = TRUE;
504 static bool opt_show_changes = TRUE;
505 static bool opt_untracked_dirs_content = TRUE;
506 static bool opt_read_git_colors = TRUE;
507 static bool opt_wrap_lines = FALSE;
508 static bool opt_ignore_case = FALSE;
509 static bool opt_focus_child = TRUE;
510 static int opt_diff_context = 3;
511 static char opt_diff_context_arg[9] = "";
512 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
513 static char opt_ignore_space_arg[22] = "";
514 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
515 static char opt_commit_order_arg[22] = "";
516 static bool opt_notes = TRUE;
517 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
518 static int opt_num_interval = 5;
519 static double opt_hscroll = 0.50;
520 static double opt_scale_split_view = 2.0 / 3.0;
521 static double opt_scale_vsplit_view = 0.5;
522 static bool opt_vsplit = FALSE;
523 static int opt_tab_size = 8;
524 static int opt_author_width = AUTHOR_WIDTH;
525 static int opt_filename_width = FILENAME_WIDTH;
526 static char opt_path[SIZEOF_STR] = "";
527 static char opt_file[SIZEOF_STR] = "";
528 static char opt_ref[SIZEOF_REF] = "";
529 static unsigned long opt_goto_line = 0;
530 static char opt_head[SIZEOF_REF] = "";
531 static char opt_remote[SIZEOF_REF] = "";
532 static struct encoding *opt_encoding = NULL;
533 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
534 static iconv_t opt_iconv_out = ICONV_NONE;
535 static char opt_search[SIZEOF_STR] = "";
536 static char opt_cdup[SIZEOF_STR] = "";
537 static char opt_prefix[SIZEOF_STR] = "";
538 static char opt_git_dir[SIZEOF_STR] = "";
539 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
540 static char opt_editor[SIZEOF_STR] = "";
541 static bool opt_editor_lineno = TRUE;
542 static FILE *opt_tty = NULL;
543 static const char **opt_diff_argv = NULL;
544 static const char **opt_rev_argv = NULL;
545 static const char **opt_file_argv = NULL;
546 static const char **opt_blame_argv = NULL;
547 static int opt_lineno = 0;
548 static bool opt_show_id = FALSE;
549 static int opt_id_cols = ID_WIDTH;
550 static bool opt_file_filter = TRUE;
551 static bool opt_show_title_overflow = FALSE;
552 static int opt_title_overflow = 50;
553 static char opt_env_lines[64] = "";
554 static char opt_env_columns[64] = "";
555 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
557 #define is_initial_commit() (!get_ref_head())
558 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
560 static inline int
561 load_refs(bool force)
563 static bool loaded = FALSE;
565 if (force)
566 opt_head[0] = 0;
567 else if (loaded)
568 return OK;
570 loaded = TRUE;
571 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
574 static inline void
575 update_diff_context_arg(int diff_context)
577 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
578 string_ncopy(opt_diff_context_arg, "-U3", 3);
581 static inline void
582 update_ignore_space_arg()
584 if (opt_ignore_space == IGNORE_SPACE_ALL) {
585 string_copy(opt_ignore_space_arg, "--ignore-all-space");
586 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
587 string_copy(opt_ignore_space_arg, "--ignore-space-change");
588 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
589 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
590 } else {
591 string_copy(opt_ignore_space_arg, "");
595 static inline void
596 update_commit_order_arg()
598 if (opt_commit_order == COMMIT_ORDER_TOPO) {
599 string_copy(opt_commit_order_arg, "--topo-order");
600 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
601 string_copy(opt_commit_order_arg, "--date-order");
602 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
603 string_copy(opt_commit_order_arg, "--reverse");
604 } else {
605 string_copy(opt_commit_order_arg, "");
609 static inline void
610 update_notes_arg()
612 if (opt_notes) {
613 string_copy(opt_notes_arg, "--show-notes");
614 } else {
615 /* Notes are disabled by default when passing --pretty args. */
616 string_copy(opt_notes_arg, "");
621 * Line-oriented content detection.
624 #define LINE_INFO \
625 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
626 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
627 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
628 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
629 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
630 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
631 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
632 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
633 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
634 LINE(DIFF_DELETED_FILE_MODE, \
635 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
636 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
637 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
638 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
639 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
640 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
641 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
642 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
643 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
644 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
645 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
646 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
647 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
648 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
649 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
650 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
651 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
652 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
653 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
654 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
655 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
656 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
657 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
658 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
659 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
660 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
661 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
662 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
663 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
664 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
665 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
666 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
667 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
668 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
669 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
670 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
671 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
672 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
673 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
674 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
675 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
676 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
677 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
678 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
679 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
680 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
681 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
682 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
683 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
684 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
685 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
686 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
687 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
688 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
689 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
690 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
691 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
692 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
693 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
694 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
695 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
696 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
697 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
698 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
699 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
700 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
701 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
702 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
703 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
705 enum line_type {
706 #define LINE(type, line, fg, bg, attr) \
707 LINE_##type
708 LINE_INFO,
709 LINE_NONE
710 #undef LINE
713 struct line_info {
714 const char *name; /* Option name. */
715 int namelen; /* Size of option name. */
716 const char *line; /* The start of line to match. */
717 int linelen; /* Size of string to match. */
718 int fg, bg, attr; /* Color and text attributes for the lines. */
719 int color_pair;
722 static struct line_info line_info[] = {
723 #define LINE(type, line, fg, bg, attr) \
724 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
725 LINE_INFO
726 #undef LINE
729 static struct line_info **color_pair;
730 static size_t color_pairs;
732 static struct line_info *custom_color;
733 static size_t custom_colors;
735 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
736 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
738 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
739 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
741 /* Color IDs must be 1 or higher. [GH #15] */
742 #define COLOR_ID(line_type) ((line_type) + 1)
744 static enum line_type
745 get_line_type(const char *line)
747 int linelen = strlen(line);
748 enum line_type type;
750 for (type = 0; type < custom_colors; type++)
751 /* Case insensitive search matches Signed-off-by lines better. */
752 if (linelen >= custom_color[type].linelen &&
753 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
754 return TO_CUSTOM_COLOR_TYPE(type);
756 for (type = 0; type < ARRAY_SIZE(line_info); type++)
757 /* Case insensitive search matches Signed-off-by lines better. */
758 if (linelen >= line_info[type].linelen &&
759 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
760 return type;
762 return LINE_DEFAULT;
765 static enum line_type
766 get_line_type_from_ref(const struct ref *ref)
768 if (ref->head)
769 return LINE_MAIN_HEAD;
770 else if (ref->ltag)
771 return LINE_MAIN_LOCAL_TAG;
772 else if (ref->tag)
773 return LINE_MAIN_TAG;
774 else if (ref->tracked)
775 return LINE_MAIN_TRACKED;
776 else if (ref->remote)
777 return LINE_MAIN_REMOTE;
778 else if (ref->replace)
779 return LINE_MAIN_REPLACE;
781 return LINE_MAIN_REF;
784 static inline struct line_info *
785 get_line(enum line_type type)
787 if (type > LINE_NONE) {
788 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
789 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
790 } else {
791 assert(type < ARRAY_SIZE(line_info));
792 return &line_info[type];
796 static inline int
797 get_line_color(enum line_type type)
799 return COLOR_ID(get_line(type)->color_pair);
802 static inline int
803 get_line_attr(enum line_type type)
805 struct line_info *info = get_line(type);
807 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
810 static struct line_info *
811 get_line_info(const char *name)
813 size_t namelen = strlen(name);
814 enum line_type type;
816 for (type = 0; type < ARRAY_SIZE(line_info); type++)
817 if (enum_equals(line_info[type], name, namelen))
818 return &line_info[type];
820 return NULL;
823 static struct line_info *
824 add_custom_color(const char *quoted_line)
826 struct line_info *info;
827 char *line;
828 size_t linelen;
830 if (!realloc_custom_color(&custom_color, custom_colors, 1))
831 die("Failed to alloc custom line info");
833 linelen = strlen(quoted_line) - 1;
834 line = malloc(linelen);
835 if (!line)
836 return NULL;
838 strncpy(line, quoted_line + 1, linelen);
839 line[linelen - 1] = 0;
841 info = &custom_color[custom_colors++];
842 info->name = info->line = line;
843 info->namelen = info->linelen = strlen(line);
845 return info;
848 static void
849 init_line_info_color_pair(struct line_info *info, enum line_type type,
850 int default_bg, int default_fg)
852 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
853 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
854 int i;
856 for (i = 0; i < color_pairs; i++) {
857 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
858 info->color_pair = i;
859 return;
863 if (!realloc_color_pair(&color_pair, color_pairs, 1))
864 die("Failed to alloc color pair");
866 color_pair[color_pairs] = info;
867 info->color_pair = color_pairs++;
868 init_pair(COLOR_ID(info->color_pair), fg, bg);
871 static void
872 init_colors(void)
874 int default_bg = line_info[LINE_DEFAULT].bg;
875 int default_fg = line_info[LINE_DEFAULT].fg;
876 enum line_type type;
878 start_color();
880 if (assume_default_colors(default_fg, default_bg) == ERR) {
881 default_bg = COLOR_BLACK;
882 default_fg = COLOR_WHITE;
885 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
886 struct line_info *info = &line_info[type];
888 init_line_info_color_pair(info, type, default_bg, default_fg);
891 for (type = 0; type < custom_colors; type++) {
892 struct line_info *info = &custom_color[type];
894 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
895 default_bg, default_fg);
899 struct line {
900 enum line_type type;
901 unsigned int lineno:24;
903 /* State flags */
904 unsigned int selected:1;
905 unsigned int dirty:1;
906 unsigned int cleareol:1;
907 unsigned int wrapped:1;
909 unsigned int user_flags:6;
910 void *data; /* User data */
915 * Keys
918 struct keybinding {
919 int alias;
920 enum request request;
923 static struct keybinding default_keybindings[] = {
924 /* View switching */
925 { 'm', REQ_VIEW_MAIN },
926 { 'd', REQ_VIEW_DIFF },
927 { 'l', REQ_VIEW_LOG },
928 { 't', REQ_VIEW_TREE },
929 { 'f', REQ_VIEW_BLOB },
930 { 'B', REQ_VIEW_BLAME },
931 { 'H', REQ_VIEW_BRANCH },
932 { 'p', REQ_VIEW_PAGER },
933 { 'h', REQ_VIEW_HELP },
934 { 'S', REQ_VIEW_STATUS },
935 { 'c', REQ_VIEW_STAGE },
936 { 'y', REQ_VIEW_STASH },
938 /* View manipulation */
939 { 'q', REQ_VIEW_CLOSE },
940 { KEY_TAB, REQ_VIEW_NEXT },
941 { KEY_RETURN, REQ_ENTER },
942 { KEY_UP, REQ_PREVIOUS },
943 { KEY_CTL('P'), REQ_PREVIOUS },
944 { KEY_DOWN, REQ_NEXT },
945 { KEY_CTL('N'), REQ_NEXT },
946 { 'R', REQ_REFRESH },
947 { KEY_F(5), REQ_REFRESH },
948 { 'O', REQ_MAXIMIZE },
949 { ',', REQ_PARENT },
951 /* View specific */
952 { 'u', REQ_STATUS_UPDATE },
953 { '!', REQ_STATUS_REVERT },
954 { 'M', REQ_STATUS_MERGE },
955 { '1', REQ_STAGE_UPDATE_LINE },
956 { '@', REQ_STAGE_NEXT },
957 { '[', REQ_DIFF_CONTEXT_DOWN },
958 { ']', REQ_DIFF_CONTEXT_UP },
960 /* Cursor navigation */
961 { 'k', REQ_MOVE_UP },
962 { 'j', REQ_MOVE_DOWN },
963 { KEY_HOME, REQ_MOVE_FIRST_LINE },
964 { KEY_END, REQ_MOVE_LAST_LINE },
965 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
966 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
967 { ' ', REQ_MOVE_PAGE_DOWN },
968 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
969 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
970 { 'b', REQ_MOVE_PAGE_UP },
971 { '-', REQ_MOVE_PAGE_UP },
973 /* Scrolling */
974 { '|', REQ_SCROLL_FIRST_COL },
975 { KEY_LEFT, REQ_SCROLL_LEFT },
976 { KEY_RIGHT, REQ_SCROLL_RIGHT },
977 { KEY_IC, REQ_SCROLL_LINE_UP },
978 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
979 { KEY_DC, REQ_SCROLL_LINE_DOWN },
980 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
981 { 'w', REQ_SCROLL_PAGE_UP },
982 { 's', REQ_SCROLL_PAGE_DOWN },
984 /* Searching */
985 { '/', REQ_SEARCH },
986 { '?', REQ_SEARCH_BACK },
987 { 'n', REQ_FIND_NEXT },
988 { 'N', REQ_FIND_PREV },
990 /* Misc */
991 { 'Q', REQ_QUIT },
992 { 'z', REQ_STOP_LOADING },
993 { 'v', REQ_SHOW_VERSION },
994 { 'r', REQ_SCREEN_REDRAW },
995 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
996 { 'o', REQ_OPTIONS },
997 { '.', REQ_TOGGLE_LINENO },
998 { 'D', REQ_TOGGLE_DATE },
999 { 'A', REQ_TOGGLE_AUTHOR },
1000 { 'g', REQ_TOGGLE_REV_GRAPH },
1001 { '~', REQ_TOGGLE_GRAPHIC },
1002 { '#', REQ_TOGGLE_FILENAME },
1003 { 'F', REQ_TOGGLE_REFS },
1004 { 'I', REQ_TOGGLE_SORT_ORDER },
1005 { 'i', REQ_TOGGLE_SORT_FIELD },
1006 { 'W', REQ_TOGGLE_IGNORE_SPACE },
1007 { 'X', REQ_TOGGLE_ID },
1008 { '%', REQ_TOGGLE_FILES },
1009 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
1010 { ':', REQ_PROMPT },
1011 { 'e', REQ_EDIT },
1014 struct keymap {
1015 const char *name;
1016 struct keymap *next;
1017 struct keybinding *data;
1018 size_t size;
1019 bool hidden;
1022 static struct keymap generic_keymap = { "generic" };
1023 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
1025 static struct keymap *keymaps = &generic_keymap;
1027 static void
1028 add_keymap(struct keymap *keymap)
1030 keymap->next = keymaps;
1031 keymaps = keymap;
1034 static struct keymap *
1035 get_keymap(const char *name)
1037 struct keymap *keymap = keymaps;
1039 while (keymap) {
1040 if (!strcasecmp(keymap->name, name))
1041 return keymap;
1042 keymap = keymap->next;
1045 return NULL;
1049 static void
1050 add_keybinding(struct keymap *table, enum request request, int key)
1052 size_t i;
1054 for (i = 0; i < table->size; i++) {
1055 if (table->data[i].alias == key) {
1056 table->data[i].request = request;
1057 return;
1061 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1062 if (!table->data)
1063 die("Failed to allocate keybinding");
1064 table->data[table->size].alias = key;
1065 table->data[table->size++].request = request;
1067 if (request == REQ_NONE && is_generic_keymap(table)) {
1068 int i;
1070 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1071 if (default_keybindings[i].alias == key)
1072 default_keybindings[i].request = REQ_NONE;
1076 /* Looks for a key binding first in the given map, then in the generic map, and
1077 * lastly in the default keybindings. */
1078 static enum request
1079 get_keybinding(struct keymap *keymap, int key)
1081 size_t i;
1083 for (i = 0; i < keymap->size; i++)
1084 if (keymap->data[i].alias == key)
1085 return keymap->data[i].request;
1087 for (i = 0; i < generic_keymap.size; i++)
1088 if (generic_keymap.data[i].alias == key)
1089 return generic_keymap.data[i].request;
1091 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1092 if (default_keybindings[i].alias == key)
1093 return default_keybindings[i].request;
1095 return (enum request) key;
1099 struct key {
1100 const char *name;
1101 int value;
1104 static const struct key key_table[] = {
1105 { "Enter", KEY_RETURN },
1106 { "Space", ' ' },
1107 { "Backspace", KEY_BACKSPACE },
1108 { "Tab", KEY_TAB },
1109 { "Escape", KEY_ESC },
1110 { "Left", KEY_LEFT },
1111 { "Right", KEY_RIGHT },
1112 { "Up", KEY_UP },
1113 { "Down", KEY_DOWN },
1114 { "Insert", KEY_IC },
1115 { "Delete", KEY_DC },
1116 { "Hash", '#' },
1117 { "Home", KEY_HOME },
1118 { "End", KEY_END },
1119 { "PageUp", KEY_PPAGE },
1120 { "PageDown", KEY_NPAGE },
1121 { "F1", KEY_F(1) },
1122 { "F2", KEY_F(2) },
1123 { "F3", KEY_F(3) },
1124 { "F4", KEY_F(4) },
1125 { "F5", KEY_F(5) },
1126 { "F6", KEY_F(6) },
1127 { "F7", KEY_F(7) },
1128 { "F8", KEY_F(8) },
1129 { "F9", KEY_F(9) },
1130 { "F10", KEY_F(10) },
1131 { "F11", KEY_F(11) },
1132 { "F12", KEY_F(12) },
1135 static int
1136 get_key_value(const char *name)
1138 int i;
1140 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1141 if (!strcasecmp(key_table[i].name, name))
1142 return key_table[i].value;
1144 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1145 return (int)name[2] + 0x80;
1146 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1147 return (int)name[1] & 0x1f;
1148 if (strlen(name) == 1 && isprint(*name))
1149 return (int) *name;
1150 return ERR;
1153 static const char *
1154 get_key_name(int key_value)
1156 static char key_char[] = "'X'\0";
1157 const char *seq = NULL;
1158 int key;
1160 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1161 if (key_table[key].value == key_value)
1162 seq = key_table[key].name;
1164 if (seq == NULL && key_value < 0x7f) {
1165 char *s = key_char + 1;
1167 if (key_value >= 0x20) {
1168 *s++ = key_value;
1169 } else {
1170 *s++ = '^';
1171 *s++ = 0x40 | (key_value & 0x1f);
1173 *s++ = '\'';
1174 *s++ = '\0';
1175 seq = key_char;
1178 return seq ? seq : "(no key)";
1181 static bool
1182 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1184 const char *sep = *pos > 0 ? ", " : "";
1185 const char *keyname = get_key_name(keybinding->alias);
1187 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1190 static bool
1191 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1192 struct keymap *keymap, bool all)
1194 int i;
1196 for (i = 0; i < keymap->size; i++) {
1197 if (keymap->data[i].request == request) {
1198 if (!append_key(buf, pos, &keymap->data[i]))
1199 return FALSE;
1200 if (!all)
1201 break;
1205 return TRUE;
1208 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1210 static const char *
1211 get_keys(struct keymap *keymap, enum request request, bool all)
1213 static char buf[BUFSIZ];
1214 size_t pos = 0;
1215 int i;
1217 buf[pos] = 0;
1219 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1220 return "Too many keybindings!";
1221 if (pos > 0 && !all)
1222 return buf;
1224 if (!is_generic_keymap(keymap)) {
1225 /* Only the generic keymap includes the default keybindings when
1226 * listing all keys. */
1227 if (all)
1228 return buf;
1230 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1231 return "Too many keybindings!";
1232 if (pos)
1233 return buf;
1236 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1237 if (default_keybindings[i].request == request) {
1238 if (!append_key(buf, &pos, &default_keybindings[i]))
1239 return "Too many keybindings!";
1240 if (!all)
1241 return buf;
1245 return buf;
1248 enum run_request_flag {
1249 RUN_REQUEST_DEFAULT = 0,
1250 RUN_REQUEST_FORCE = 1,
1251 RUN_REQUEST_SILENT = 2,
1252 RUN_REQUEST_CONFIRM = 4,
1253 RUN_REQUEST_EXIT = 8,
1254 RUN_REQUEST_INTERNAL = 16,
1257 struct run_request {
1258 struct keymap *keymap;
1259 int key;
1260 const char **argv;
1261 bool silent;
1262 bool confirm;
1263 bool exit;
1264 bool internal;
1267 static struct run_request *run_request;
1268 static size_t run_requests;
1270 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1272 static bool
1273 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1275 bool force = flags & RUN_REQUEST_FORCE;
1276 struct run_request *req;
1278 if (!force && get_keybinding(keymap, key) != key)
1279 return TRUE;
1281 if (!realloc_run_requests(&run_request, run_requests, 1))
1282 return FALSE;
1284 if (!argv_copy(&run_request[run_requests].argv, argv))
1285 return FALSE;
1287 req = &run_request[run_requests++];
1288 req->silent = flags & RUN_REQUEST_SILENT;
1289 req->confirm = flags & RUN_REQUEST_CONFIRM;
1290 req->exit = flags & RUN_REQUEST_EXIT;
1291 req->internal = flags & RUN_REQUEST_INTERNAL;
1292 req->keymap = keymap;
1293 req->key = key;
1295 add_keybinding(keymap, REQ_NONE + run_requests, key);
1296 return TRUE;
1299 static struct run_request *
1300 get_run_request(enum request request)
1302 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1303 return NULL;
1304 return &run_request[request - REQ_NONE - 1];
1307 static void
1308 add_builtin_run_requests(void)
1310 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1311 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1312 const char *commit[] = { "git", "commit", NULL };
1313 const char *gc[] = { "git", "gc", NULL };
1314 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1316 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1317 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1318 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1319 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1320 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1324 * User config file handling.
1327 #define OPT_ERR_INFO \
1328 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1329 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1330 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1331 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1332 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1333 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1334 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1335 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1336 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1337 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1338 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1339 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1340 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1341 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1342 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1343 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1344 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1345 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"), \
1346 OPT_ERR_(HOME_UNRESOLVABLE, "HOME environment variable could not be resolved"),
1348 enum option_code {
1349 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1350 OPT_ERR_INFO
1351 #undef OPT_ERR_
1352 OPT_OK
1355 static const char *option_errors[] = {
1356 #define OPT_ERR_(name, msg) msg
1357 OPT_ERR_INFO
1358 #undef OPT_ERR_
1361 static const struct enum_map color_map[] = {
1362 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1363 COLOR_MAP(DEFAULT),
1364 COLOR_MAP(BLACK),
1365 COLOR_MAP(BLUE),
1366 COLOR_MAP(CYAN),
1367 COLOR_MAP(GREEN),
1368 COLOR_MAP(MAGENTA),
1369 COLOR_MAP(RED),
1370 COLOR_MAP(WHITE),
1371 COLOR_MAP(YELLOW),
1374 static const struct enum_map attr_map[] = {
1375 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1376 ATTR_MAP(NORMAL),
1377 ATTR_MAP(BLINK),
1378 ATTR_MAP(BOLD),
1379 ATTR_MAP(DIM),
1380 ATTR_MAP(REVERSE),
1381 ATTR_MAP(STANDOUT),
1382 ATTR_MAP(UNDERLINE),
1385 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1387 static enum option_code
1388 parse_step(double *opt, const char *arg)
1390 *opt = atoi(arg);
1391 if (!strchr(arg, '%'))
1392 return OPT_OK;
1394 /* "Shift down" so 100% and 1 does not conflict. */
1395 *opt = (*opt - 1) / 100;
1396 if (*opt >= 1.0) {
1397 *opt = 0.99;
1398 return OPT_ERR_INVALID_STEP_VALUE;
1400 if (*opt < 0.0) {
1401 *opt = 1;
1402 return OPT_ERR_INVALID_STEP_VALUE;
1404 return OPT_OK;
1407 static enum option_code
1408 parse_int(int *opt, const char *arg, int min, int max)
1410 int value = atoi(arg);
1412 if (min <= value && value <= max) {
1413 *opt = value;
1414 return OPT_OK;
1417 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1420 #define parse_id(opt, arg) \
1421 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1423 static bool
1424 set_color(int *color, const char *name)
1426 if (map_enum(color, color_map, name))
1427 return TRUE;
1428 if (!prefixcmp(name, "color"))
1429 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1430 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1431 return parse_int(color, name, 0, 255) == OPT_OK;
1434 /* Wants: object fgcolor bgcolor [attribute] */
1435 static enum option_code
1436 option_color_command(int argc, const char *argv[])
1438 struct line_info *info;
1440 if (argc < 3)
1441 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1443 if (*argv[0] == '"' || *argv[0] == '\'') {
1444 info = add_custom_color(argv[0]);
1445 } else {
1446 info = get_line_info(argv[0]);
1448 if (!info) {
1449 static const struct enum_map obsolete[] = {
1450 ENUM_MAP("main-delim", LINE_DELIMITER),
1451 ENUM_MAP("main-date", LINE_DATE),
1452 ENUM_MAP("main-author", LINE_AUTHOR),
1453 ENUM_MAP("blame-id", LINE_ID),
1455 int index;
1457 if (!map_enum(&index, obsolete, argv[0]))
1458 return OPT_ERR_UNKNOWN_COLOR_NAME;
1459 info = &line_info[index];
1462 if (!set_color(&info->fg, argv[1]) ||
1463 !set_color(&info->bg, argv[2]))
1464 return OPT_ERR_UNKNOWN_COLOR;
1466 info->attr = 0;
1467 while (argc-- > 3) {
1468 int attr;
1470 if (!set_attribute(&attr, argv[argc]))
1471 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1472 info->attr |= attr;
1475 return OPT_OK;
1478 static enum option_code
1479 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1481 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1482 ? TRUE : FALSE;
1483 if (matched)
1484 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1485 return OPT_OK;
1488 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1490 static enum option_code
1491 parse_enum_do(unsigned int *opt, const char *arg,
1492 const struct enum_map *map, size_t map_size)
1494 bool is_true;
1496 assert(map_size > 1);
1498 if (map_enum_do(map, map_size, (int *) opt, arg))
1499 return OPT_OK;
1501 parse_bool(&is_true, arg);
1502 *opt = is_true ? map[1].value : map[0].value;
1503 return OPT_OK;
1506 #define parse_enum(opt, arg, map) \
1507 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1509 static enum option_code
1510 parse_string(char *opt, const char *arg, size_t optsize)
1512 int arglen = strlen(arg);
1514 switch (arg[0]) {
1515 case '\"':
1516 case '\'':
1517 if (arglen == 1 || arg[arglen - 1] != arg[0])
1518 return OPT_ERR_UNMATCHED_QUOTATION;
1519 arg += 1; arglen -= 2;
1520 default:
1521 string_ncopy_do(opt, optsize, arg, arglen);
1522 return OPT_OK;
1526 static enum option_code
1527 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1529 char buf[SIZEOF_STR];
1530 enum option_code code = parse_string(buf, arg, sizeof(buf));
1532 if (code == OPT_OK) {
1533 struct encoding *encoding = *encoding_ref;
1535 if (encoding && !priority)
1536 return code;
1537 encoding = encoding_open(buf);
1538 if (encoding)
1539 *encoding_ref = encoding;
1542 return code;
1545 static enum option_code
1546 parse_args(const char ***args, const char *argv[])
1548 if (!argv_copy(args, argv))
1549 return OPT_ERR_OUT_OF_MEMORY;
1550 return OPT_OK;
1553 /* Wants: name = value */
1554 static enum option_code
1555 option_set_command(int argc, const char *argv[])
1557 if (argc < 3)
1558 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1560 if (strcmp(argv[1], "="))
1561 return OPT_ERR_NO_VALUE_ASSIGNED;
1563 if (!strcmp(argv[0], "blame-options"))
1564 return parse_args(&opt_blame_argv, argv + 2);
1566 if (!strcmp(argv[0], "diff-options"))
1567 return parse_args(&opt_diff_argv, argv + 2);
1569 if (argc != 3)
1570 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1572 if (!strcmp(argv[0], "show-author"))
1573 return parse_enum(&opt_author, argv[2], author_map);
1575 if (!strcmp(argv[0], "show-date"))
1576 return parse_enum(&opt_date, argv[2], date_map);
1578 if (!strcmp(argv[0], "show-rev-graph"))
1579 return parse_bool(&opt_rev_graph, argv[2]);
1581 if (!strcmp(argv[0], "show-refs"))
1582 return parse_bool(&opt_show_refs, argv[2]);
1584 if (!strcmp(argv[0], "show-changes"))
1585 return parse_bool(&opt_show_changes, argv[2]);
1587 if (!strcmp(argv[0], "show-notes")) {
1588 bool matched = FALSE;
1589 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1591 if (res == OPT_OK && matched) {
1592 update_notes_arg();
1593 return res;
1596 opt_notes = TRUE;
1597 strcpy(opt_notes_arg, "--show-notes=");
1598 res = parse_string(opt_notes_arg + 8, argv[2],
1599 sizeof(opt_notes_arg) - 8);
1600 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1601 opt_notes_arg[7] = '\0';
1602 return res;
1605 if (!strcmp(argv[0], "show-line-numbers"))
1606 return parse_bool(&opt_line_number, argv[2]);
1608 if (!strcmp(argv[0], "line-graphics"))
1609 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1611 if (!strcmp(argv[0], "line-number-interval"))
1612 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1614 if (!strcmp(argv[0], "author-width"))
1615 return parse_int(&opt_author_width, argv[2], 0, 1024);
1617 if (!strcmp(argv[0], "filename-width"))
1618 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1620 if (!strcmp(argv[0], "show-filename"))
1621 return parse_enum(&opt_filename, argv[2], filename_map);
1623 if (!strcmp(argv[0], "show-file-size"))
1624 return parse_enum(&opt_file_size, argv[2], file_size_map);
1626 if (!strcmp(argv[0], "horizontal-scroll"))
1627 return parse_step(&opt_hscroll, argv[2]);
1629 if (!strcmp(argv[0], "split-view-height"))
1630 return parse_step(&opt_scale_split_view, argv[2]);
1632 if (!strcmp(argv[0], "vertical-split"))
1633 return parse_bool(&opt_vsplit, argv[2]);
1635 if (!strcmp(argv[0], "tab-size"))
1636 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1638 if (!strcmp(argv[0], "diff-context")) {
1639 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1641 if (code == OPT_OK)
1642 update_diff_context_arg(opt_diff_context);
1643 return code;
1646 if (!strcmp(argv[0], "ignore-space")) {
1647 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1649 if (code == OPT_OK)
1650 update_ignore_space_arg();
1651 return code;
1654 if (!strcmp(argv[0], "commit-order")) {
1655 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1657 if (code == OPT_OK)
1658 update_commit_order_arg();
1659 return code;
1662 if (!strcmp(argv[0], "status-untracked-dirs"))
1663 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1665 if (!strcmp(argv[0], "read-git-colors"))
1666 return parse_bool(&opt_read_git_colors, argv[2]);
1668 if (!strcmp(argv[0], "ignore-case"))
1669 return parse_bool(&opt_ignore_case, argv[2]);
1671 if (!strcmp(argv[0], "focus-child"))
1672 return parse_bool(&opt_focus_child, argv[2]);
1674 if (!strcmp(argv[0], "wrap-lines"))
1675 return parse_bool(&opt_wrap_lines, argv[2]);
1677 if (!strcmp(argv[0], "show-id"))
1678 return parse_bool(&opt_show_id, argv[2]);
1680 if (!strcmp(argv[0], "id-width"))
1681 return parse_id(&opt_id_cols, argv[2]);
1683 if (!strcmp(argv[0], "title-overflow")) {
1684 bool matched;
1685 enum option_code code;
1688 * "title-overflow" is considered a boolint.
1689 * We try to parse it as a boolean (and set the value to 50 if true),
1690 * otherwise we parse it as an integer and use the given value.
1692 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1693 if (code == OPT_OK && matched) {
1694 if (opt_show_title_overflow)
1695 opt_title_overflow = 50;
1696 } else {
1697 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1698 if (code == OPT_OK)
1699 opt_show_title_overflow = TRUE;
1702 return code;
1705 if (!strcmp(argv[0], "editor-line-number"))
1706 return parse_bool(&opt_editor_lineno, argv[2]);
1708 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1711 /* Wants: mode request key */
1712 static enum option_code
1713 option_bind_command(int argc, const char *argv[])
1715 enum request request;
1716 struct keymap *keymap;
1717 int key;
1719 if (argc < 3)
1720 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1722 if (!(keymap = get_keymap(argv[0])))
1723 return OPT_ERR_UNKNOWN_KEY_MAP;
1725 key = get_key_value(argv[1]);
1726 if (key == ERR)
1727 return OPT_ERR_UNKNOWN_KEY;
1729 request = get_request(argv[2]);
1730 if (request == REQ_UNKNOWN) {
1731 static const struct enum_map obsolete[] = {
1732 ENUM_MAP("cherry-pick", REQ_NONE),
1733 ENUM_MAP("screen-resize", REQ_NONE),
1734 ENUM_MAP("tree-parent", REQ_PARENT),
1736 int alias;
1738 if (map_enum(&alias, obsolete, argv[2])) {
1739 if (alias != REQ_NONE)
1740 add_keybinding(keymap, alias, key);
1741 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1745 if (request == REQ_UNKNOWN) {
1746 enum run_request_flag flags = RUN_REQUEST_FORCE;
1748 if (strchr("!?@<", *argv[2])) {
1749 while (*argv[2]) {
1750 if (*argv[2] == '@') {
1751 flags |= RUN_REQUEST_SILENT;
1752 } else if (*argv[2] == '?') {
1753 flags |= RUN_REQUEST_CONFIRM;
1754 } else if (*argv[2] == '<') {
1755 flags |= RUN_REQUEST_EXIT;
1756 } else if (*argv[2] != '!') {
1757 break;
1759 argv[2]++;
1762 } else if (*argv[2] == ':') {
1763 argv[2]++;
1764 flags |= RUN_REQUEST_INTERNAL;
1766 } else {
1767 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1770 return add_run_request(keymap, key, argv + 2, flags)
1771 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1774 add_keybinding(keymap, request, key);
1776 return OPT_OK;
1780 static enum option_code load_option_file(const char *path);
1782 static enum option_code
1783 option_source_command(int argc, const char *argv[])
1785 if (argc < 1)
1786 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1788 return load_option_file(argv[0]);
1791 static enum option_code
1792 set_option(const char *opt, char *value)
1794 const char *argv[SIZEOF_ARG];
1795 int argc = 0;
1797 if (!argv_from_string(argv, &argc, value))
1798 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1800 if (!strcmp(opt, "color"))
1801 return option_color_command(argc, argv);
1803 if (!strcmp(opt, "set"))
1804 return option_set_command(argc, argv);
1806 if (!strcmp(opt, "bind"))
1807 return option_bind_command(argc, argv);
1809 if (!strcmp(opt, "source"))
1810 return option_source_command(argc, argv);
1812 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1815 struct config_state {
1816 const char *path;
1817 int lineno;
1818 bool errors;
1821 static int
1822 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1824 struct config_state *config = data;
1825 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1827 config->lineno++;
1829 /* Check for comment markers, since read_properties() will
1830 * only ensure opt and value are split at first " \t". */
1831 optlen = strcspn(opt, "#");
1832 if (optlen == 0)
1833 return OK;
1835 if (opt[optlen] == 0) {
1836 /* Look for comment endings in the value. */
1837 size_t len = strcspn(value, "#");
1839 if (len < valuelen) {
1840 valuelen = len;
1841 value[valuelen] = 0;
1844 status = set_option(opt, value);
1847 if (status != OPT_OK) {
1848 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1849 option_errors[status], (int) optlen, opt);
1850 config->errors = TRUE;
1853 /* Always keep going if errors are encountered. */
1854 return OK;
1857 static enum option_code
1858 load_option_file(const char *path)
1860 struct config_state config = { path, 0, FALSE };
1861 struct io io;
1862 char buf[SIZEOF_STR];
1864 /* Do not read configuration from stdin if set to "" */
1865 if (!path || !strlen(path))
1866 return OPT_OK;
1868 if (!prefixcmp(path, "~/")) {
1869 const char *home = getenv("HOME");
1871 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1872 return OPT_ERR_HOME_UNRESOLVABLE;
1873 path = buf;
1876 /* It's OK that the file doesn't exist. */
1877 if (!io_open(&io, "%s", path))
1878 return OPT_ERR_FILE_DOES_NOT_EXIST;
1880 if (io_load(&io, " \t", read_option, &config) == ERR ||
1881 config.errors == TRUE)
1882 warn("Errors while loading %s.", path);
1883 return OPT_OK;
1886 static int
1887 load_options(void)
1889 const char *tigrc_user = getenv("TIGRC_USER");
1890 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1891 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1892 const bool diff_opts_from_args = !!opt_diff_argv;
1894 if (!tigrc_system)
1895 tigrc_system = SYSCONFDIR "/tigrc";
1896 load_option_file(tigrc_system);
1898 if (!tigrc_user)
1899 tigrc_user = "~/.tigrc";
1900 load_option_file(tigrc_user);
1902 /* Add _after_ loading config files to avoid adding run requests
1903 * that conflict with keybindings. */
1904 add_builtin_run_requests();
1906 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1907 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1908 char buf[SIZEOF_STR];
1909 int argc = 0;
1911 if (!string_format(buf, "%s", tig_diff_opts) ||
1912 !argv_from_string(diff_opts, &argc, buf))
1913 die("TIG_DIFF_OPTS contains too many arguments");
1914 else if (!argv_copy(&opt_diff_argv, diff_opts))
1915 die("Failed to format TIG_DIFF_OPTS arguments");
1918 return OK;
1923 * The viewer
1926 struct view;
1927 struct view_ops;
1929 /* The display array of active views and the index of the current view. */
1930 static struct view *display[2];
1931 static WINDOW *display_win[2];
1932 static WINDOW *display_title[2];
1933 static WINDOW *display_sep;
1935 static unsigned int current_view;
1937 #define foreach_displayed_view(view, i) \
1938 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1940 #define displayed_views() (display[1] != NULL ? 2 : 1)
1942 /* Current head and commit ID */
1943 static char ref_blob[SIZEOF_REF] = "";
1944 static char ref_commit[SIZEOF_REF] = "HEAD";
1945 static char ref_head[SIZEOF_REF] = "HEAD";
1946 static char ref_branch[SIZEOF_REF] = "";
1947 static char ref_status[SIZEOF_STR] = "";
1948 static char ref_stash[SIZEOF_REF] = "";
1950 enum view_flag {
1951 VIEW_NO_FLAGS = 0,
1952 VIEW_ALWAYS_LINENO = 1 << 0,
1953 VIEW_CUSTOM_STATUS = 1 << 1,
1954 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1955 VIEW_ADD_PAGER_REFS = 1 << 3,
1956 VIEW_OPEN_DIFF = 1 << 4,
1957 VIEW_NO_REF = 1 << 5,
1958 VIEW_NO_GIT_DIR = 1 << 6,
1959 VIEW_DIFF_LIKE = 1 << 7,
1960 VIEW_SEND_CHILD_ENTER = 1 << 9,
1961 VIEW_FILE_FILTER = 1 << 10,
1962 VIEW_LOG_LIKE = 1 << 11,
1963 VIEW_STATUS_LIKE = 1 << 12,
1966 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1968 struct position {
1969 unsigned long offset; /* Offset of the window top */
1970 unsigned long col; /* Offset from the window side. */
1971 unsigned long lineno; /* Current line number */
1974 struct view {
1975 const char *name; /* View name */
1976 const char *id; /* Points to either of ref_{head,commit,blob} */
1978 struct view_ops *ops; /* View operations */
1980 char ref[SIZEOF_REF]; /* Hovered commit reference */
1981 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1983 int height, width; /* The width and height of the main window */
1984 WINDOW *win; /* The main window */
1986 /* Navigation */
1987 struct position pos; /* Current position. */
1988 struct position prev_pos; /* Previous position. */
1990 /* Searching */
1991 char grep[SIZEOF_STR]; /* Search string */
1992 regex_t *regex; /* Pre-compiled regexp */
1994 /* If non-NULL, points to the view that opened this view. If this view
1995 * is closed tig will switch back to the parent view. */
1996 struct view *parent;
1997 struct view *prev;
1999 /* Buffering */
2000 size_t lines; /* Total number of lines */
2001 struct line *line; /* Line index */
2002 unsigned int digits; /* Number of digits in the lines member. */
2004 /* Number of lines with custom status, not to be counted in the
2005 * view title. */
2006 unsigned int custom_lines;
2008 /* Drawing */
2009 struct line *curline; /* Line currently being drawn. */
2010 enum line_type curtype; /* Attribute currently used for drawing. */
2011 unsigned long col; /* Column when drawing. */
2012 bool has_scrolled; /* View was scrolled. */
2013 bool force_redraw; /* Whether to force a redraw after reading. */
2015 /* Loading */
2016 const char **argv; /* Shell command arguments. */
2017 const char *dir; /* Directory from which to execute. */
2018 struct io io;
2019 struct io *pipe;
2020 time_t start_time;
2021 time_t update_secs;
2022 struct encoding *encoding;
2023 bool unrefreshable;
2025 /* Private data */
2026 void *private;
2029 enum open_flags {
2030 OPEN_DEFAULT = 0, /* Use default view switching. */
2031 OPEN_STDIN = 1, /* Open in pager mode. */
2032 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
2033 OPEN_SPLIT = 4, /* Split current view. */
2034 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
2035 OPEN_REFRESH = 16, /* Refresh view using previous command. */
2036 OPEN_PREPARED = 32, /* Open already prepared command. */
2037 OPEN_EXTRA = 64, /* Open extra data from command. */
2039 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
2042 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
2043 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
2045 struct view_ops {
2046 /* What type of content being displayed. Used in the title bar. */
2047 const char *type;
2048 /* What keymap does this view have */
2049 struct keymap keymap;
2050 /* Flags to control the view behavior. */
2051 enum view_flag flags;
2052 /* Size of private data. */
2053 size_t private_size;
2054 /* Open and reads in all view content. */
2055 bool (*open)(struct view *view, enum open_flags flags);
2056 /* Read one line; updates view->line. */
2057 bool (*read)(struct view *view, char *data);
2058 /* Draw one line; @lineno must be < view->height. */
2059 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
2060 /* Depending on view handle a special requests. */
2061 enum request (*request)(struct view *view, enum request request, struct line *line);
2062 /* Search for regexp in a line. */
2063 bool (*grep)(struct view *view, struct line *line);
2064 /* Select line */
2065 void (*select)(struct view *view, struct line *line);
2066 /* Release resources when reloading the view */
2067 void (*done)(struct view *view);
2070 #define VIEW_OPS(id, name, ref) name##_ops
2071 static struct view_ops VIEW_INFO(VIEW_OPS);
2073 static struct view views[] = {
2074 #define VIEW_DATA(id, name, ref) \
2075 { #name, ref, &name##_ops }
2076 VIEW_INFO(VIEW_DATA)
2079 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2081 #define foreach_view(view, i) \
2082 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2084 #define view_is_displayed(view) \
2085 (view == display[0] || view == display[1])
2087 #define view_has_line(view, line_) \
2088 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2090 static bool
2091 forward_request_to_child(struct view *child, enum request request)
2093 return displayed_views() == 2 && view_is_displayed(child) &&
2094 !strcmp(child->vid, child->id);
2097 static enum request
2098 view_request(struct view *view, enum request request)
2100 if (!view || !view->lines)
2101 return request;
2103 if (request == REQ_ENTER && !opt_focus_child &&
2104 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2105 struct view *child = display[1];
2107 if (forward_request_to_child(child, request)) {
2108 view_request(child, request);
2109 return REQ_NONE;
2113 if (request == REQ_REFRESH && view->unrefreshable) {
2114 report("This view can not be refreshed");
2115 return REQ_NONE;
2118 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2122 * View drawing.
2125 static inline void
2126 set_view_attr(struct view *view, enum line_type type)
2128 if (!view->curline->selected && view->curtype != type) {
2129 (void) wattrset(view->win, get_line_attr(type));
2130 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2131 view->curtype = type;
2135 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2137 static bool
2138 draw_chars(struct view *view, enum line_type type, const char *string,
2139 int max_len, bool use_tilde)
2141 int len = 0;
2142 int col = 0;
2143 int trimmed = FALSE;
2144 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2146 if (max_len <= 0)
2147 return VIEW_MAX_LEN(view) <= 0;
2149 if (opt_iconv_out != ICONV_NONE) {
2150 string = encoding_iconv(opt_iconv_out, string);
2151 if (!string)
2152 return VIEW_MAX_LEN(view) <= 0;
2155 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2157 set_view_attr(view, type);
2158 if (len > 0) {
2159 waddnstr(view->win, string, len);
2161 if (trimmed && use_tilde) {
2162 set_view_attr(view, LINE_DELIMITER);
2163 waddch(view->win, '~');
2164 col++;
2168 view->col += col;
2169 return VIEW_MAX_LEN(view) <= 0;
2172 static bool
2173 draw_space(struct view *view, enum line_type type, int max, int spaces)
2175 static char space[] = " ";
2177 spaces = MIN(max, spaces);
2179 while (spaces > 0) {
2180 int len = MIN(spaces, sizeof(space) - 1);
2182 if (draw_chars(view, type, space, len, FALSE))
2183 return TRUE;
2184 spaces -= len;
2187 return VIEW_MAX_LEN(view) <= 0;
2190 static bool
2191 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2193 static char text[SIZEOF_STR];
2195 do {
2196 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2198 if (draw_chars(view, type, text, max_len, use_tilde))
2199 return TRUE;
2200 string += pos;
2201 } while (*string);
2203 return VIEW_MAX_LEN(view) <= 0;
2206 static bool
2207 draw_text(struct view *view, enum line_type type, const char *string)
2209 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2212 static bool
2213 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2215 if (on) {
2216 int max = MIN(VIEW_MAX_LEN(view), overflow);
2217 int len = strlen(text);
2219 if (draw_text_expanded(view, type, text, max, max < overflow))
2220 return TRUE;
2222 text = len > overflow ? text + overflow : "";
2223 type = LINE_OVERFLOW;
2226 if (*text && draw_text(view, type, text))
2227 return TRUE;
2229 return VIEW_MAX_LEN(view) <= 0;
2232 #define draw_commit_title(view, text, offset) \
2233 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2235 static bool PRINTF_LIKE(3, 4)
2236 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2238 char text[SIZEOF_STR];
2239 int retval;
2241 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2242 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2245 static bool
2246 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2248 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2249 int max = VIEW_MAX_LEN(view);
2250 int i;
2252 if (max < size)
2253 size = max;
2255 set_view_attr(view, type);
2256 /* Using waddch() instead of waddnstr() ensures that
2257 * they'll be rendered correctly for the cursor line. */
2258 for (i = skip; i < size; i++)
2259 waddch(view->win, graphic[i]);
2261 view->col += size;
2262 if (separator) {
2263 if (size < max && skip <= size)
2264 waddch(view->win, ' ');
2265 view->col++;
2268 return VIEW_MAX_LEN(view) <= 0;
2271 enum align {
2272 ALIGN_LEFT,
2273 ALIGN_RIGHT
2276 static bool
2277 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2279 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2280 int col = view->col;
2282 if (!text)
2283 return draw_space(view, type, max, max);
2285 if (align == ALIGN_RIGHT) {
2286 int textlen = strlen(text);
2287 int leftpad = max - textlen - 1;
2289 if (leftpad > 0) {
2290 if (draw_space(view, type, leftpad, leftpad))
2291 return TRUE;
2292 max -= leftpad;
2293 col += leftpad;;
2297 return draw_chars(view, type, text, max - 1, trim)
2298 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2301 static bool
2302 draw_date(struct view *view, struct time *time)
2304 const char *date = mkdate(time, opt_date);
2305 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2307 if (opt_date == DATE_NO)
2308 return FALSE;
2310 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2313 static bool
2314 draw_author(struct view *view, const struct ident *author)
2316 bool trim = author_trim(opt_author_width);
2317 const char *text = mkauthor(author, opt_author_width, opt_author);
2319 if (opt_author == AUTHOR_NO)
2320 return FALSE;
2322 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2325 static bool
2326 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2328 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2331 static bool
2332 draw_id(struct view *view, const char *id)
2334 if (!opt_show_id)
2335 return FALSE;
2337 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2340 static bool
2341 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2343 bool trim = filename && strlen(filename) >= opt_filename_width;
2345 if (opt_filename == FILENAME_NO)
2346 return FALSE;
2348 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2349 return FALSE;
2351 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2354 static bool
2355 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2357 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2359 if (!width || opt_file_size == FILE_SIZE_NO)
2360 return FALSE;
2362 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2365 static bool
2366 draw_mode(struct view *view, mode_t mode)
2368 const char *str = mkmode(mode);
2370 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2373 static bool
2374 draw_lineno(struct view *view, unsigned int lineno)
2376 char number[10];
2377 int digits3 = view->digits < 3 ? 3 : view->digits;
2378 int max = MIN(VIEW_MAX_LEN(view), digits3);
2379 char *text = NULL;
2380 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2382 if (!opt_line_number)
2383 return FALSE;
2385 lineno += view->pos.offset + 1;
2386 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2387 static char fmt[] = "%1ld";
2389 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2390 if (string_format(number, fmt, lineno))
2391 text = number;
2393 if (text)
2394 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2395 else
2396 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2397 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2400 static bool
2401 draw_refs(struct view *view, struct ref_list *refs)
2403 size_t i;
2405 if (!opt_show_refs || !refs)
2406 return FALSE;
2408 for (i = 0; i < refs->size; i++) {
2409 struct ref *ref = refs->refs[i];
2410 enum line_type type = get_line_type_from_ref(ref);
2412 if (draw_formatted(view, type, "[%s]", ref->name))
2413 return TRUE;
2415 if (draw_text(view, LINE_DEFAULT, " "))
2416 return TRUE;
2419 return FALSE;
2422 static bool
2423 draw_view_line(struct view *view, unsigned int lineno)
2425 struct line *line;
2426 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2428 assert(view_is_displayed(view));
2430 if (view->pos.offset + lineno >= view->lines)
2431 return FALSE;
2433 line = &view->line[view->pos.offset + lineno];
2435 wmove(view->win, lineno, 0);
2436 if (line->cleareol)
2437 wclrtoeol(view->win);
2438 view->col = 0;
2439 view->curline = line;
2440 view->curtype = LINE_NONE;
2441 line->selected = FALSE;
2442 line->dirty = line->cleareol = 0;
2444 if (selected) {
2445 set_view_attr(view, LINE_CURSOR);
2446 line->selected = TRUE;
2447 view->ops->select(view, line);
2450 return view->ops->draw(view, line, lineno);
2453 static void
2454 redraw_view_dirty(struct view *view)
2456 bool dirty = FALSE;
2457 int lineno;
2459 for (lineno = 0; lineno < view->height; lineno++) {
2460 if (view->pos.offset + lineno >= view->lines)
2461 break;
2462 if (!view->line[view->pos.offset + lineno].dirty)
2463 continue;
2464 dirty = TRUE;
2465 if (!draw_view_line(view, lineno))
2466 break;
2469 if (!dirty)
2470 return;
2471 wnoutrefresh(view->win);
2474 static void
2475 redraw_view_from(struct view *view, int lineno)
2477 assert(0 <= lineno && lineno < view->height);
2479 for (; lineno < view->height; lineno++) {
2480 if (!draw_view_line(view, lineno))
2481 break;
2484 wnoutrefresh(view->win);
2487 static void
2488 redraw_view(struct view *view)
2490 werase(view->win);
2491 redraw_view_from(view, 0);
2495 static void
2496 update_view_title(struct view *view)
2498 char buf[SIZEOF_STR];
2499 char state[SIZEOF_STR];
2500 size_t bufpos = 0, statelen = 0;
2501 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2502 struct line *line = &view->line[view->pos.lineno];
2504 assert(view_is_displayed(view));
2506 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2507 line->lineno) {
2508 unsigned int view_lines = view->pos.offset + view->height;
2509 unsigned int lines = view->lines
2510 ? MIN(view_lines, view->lines) * 100 / view->lines
2511 : 0;
2513 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2514 view->ops->type,
2515 line->lineno,
2516 view->lines - view->custom_lines,
2517 lines);
2521 if (view->pipe) {
2522 time_t secs = time(NULL) - view->start_time;
2524 /* Three git seconds are a long time ... */
2525 if (secs > 2)
2526 string_format_from(state, &statelen, " loading %lds", secs);
2529 string_format_from(buf, &bufpos, "[%s]", view->name);
2530 if (*view->ref && bufpos < view->width) {
2531 size_t refsize = strlen(view->ref);
2532 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2534 if (minsize < view->width)
2535 refsize = view->width - minsize + 7;
2536 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2539 if (statelen && bufpos < view->width) {
2540 string_format_from(buf, &bufpos, "%s", state);
2543 if (view == display[current_view])
2544 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2545 else
2546 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2548 mvwaddnstr(window, 0, 0, buf, bufpos);
2549 wclrtoeol(window);
2550 wnoutrefresh(window);
2553 static int
2554 apply_step(double step, int value)
2556 if (step >= 1)
2557 return (int) step;
2558 value *= step + 0.01;
2559 return value ? value : 1;
2562 static void
2563 apply_horizontal_split(struct view *base, struct view *view)
2565 view->width = base->width;
2566 view->height = apply_step(opt_scale_split_view, base->height);
2567 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2568 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2569 base->height -= view->height;
2572 static void
2573 apply_vertical_split(struct view *base, struct view *view)
2575 view->height = base->height;
2576 view->width = apply_step(opt_scale_vsplit_view, base->width);
2577 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2578 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2579 base->width -= view->width;
2582 static void
2583 redraw_display_separator(bool clear)
2585 if (displayed_views() > 1 && opt_vsplit) {
2586 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2588 if (clear)
2589 wclear(display_sep);
2590 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2591 wnoutrefresh(display_sep);
2595 static void
2596 resize_display(void)
2598 int x, y, i;
2599 struct view *base = display[0];
2600 struct view *view = display[1] ? display[1] : display[0];
2602 /* Setup window dimensions */
2604 getmaxyx(stdscr, base->height, base->width);
2605 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2606 string_format(opt_env_lines, "LINES=%d", base->height);
2608 /* Make room for the status window. */
2609 base->height -= 1;
2611 if (view != base) {
2612 if (opt_vsplit) {
2613 apply_vertical_split(base, view);
2615 /* Make room for the separator bar. */
2616 view->width -= 1;
2617 } else {
2618 apply_horizontal_split(base, view);
2621 /* Make room for the title bar. */
2622 view->height -= 1;
2625 /* Make room for the title bar. */
2626 base->height -= 1;
2628 x = y = 0;
2630 foreach_displayed_view (view, i) {
2631 if (!display_win[i]) {
2632 display_win[i] = newwin(view->height, view->width, y, x);
2633 if (!display_win[i])
2634 die("Failed to create %s view", view->name);
2636 scrollok(display_win[i], FALSE);
2638 display_title[i] = newwin(1, view->width, y + view->height, x);
2639 if (!display_title[i])
2640 die("Failed to create title window");
2642 } else {
2643 wresize(display_win[i], view->height, view->width);
2644 mvwin(display_win[i], y, x);
2645 wresize(display_title[i], 1, view->width);
2646 mvwin(display_title[i], y + view->height, x);
2649 if (i > 0 && opt_vsplit) {
2650 if (!display_sep) {
2651 display_sep = newwin(view->height, 1, 0, x - 1);
2652 if (!display_sep)
2653 die("Failed to create separator window");
2655 } else {
2656 wresize(display_sep, view->height, 1);
2657 mvwin(display_sep, 0, x - 1);
2661 view->win = display_win[i];
2663 if (opt_vsplit)
2664 x += view->width + 1;
2665 else
2666 y += view->height + 1;
2669 redraw_display_separator(FALSE);
2672 static void
2673 redraw_display(bool clear)
2675 struct view *view;
2676 int i;
2678 foreach_displayed_view (view, i) {
2679 if (clear)
2680 wclear(view->win);
2681 redraw_view(view);
2682 update_view_title(view);
2685 redraw_display_separator(clear);
2689 * Option management
2692 #define TOGGLE_MENU_INFO(_) \
2693 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2694 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2695 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2696 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2697 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2698 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2699 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2700 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2701 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2702 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2703 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2704 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2705 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2706 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2707 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2709 static enum view_flag
2710 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2712 const struct {
2713 enum request request;
2714 const struct enum_map *map;
2715 size_t map_size;
2716 enum view_flag reload_flags;
2717 } data[] = {
2718 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2719 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2721 const struct menu_item menu[] = {
2722 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2723 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2724 { 0 }
2726 int i = 0;
2728 if (request == REQ_OPTIONS) {
2729 if (!prompt_menu("Toggle option", menu, &i))
2730 return VIEW_NO_FLAGS;
2731 } else {
2732 while (i < ARRAY_SIZE(data) && data[i].request != request)
2733 i++;
2734 if (i >= ARRAY_SIZE(data))
2735 die("Invalid request (%d)", request);
2738 if (data[i].map != NULL) {
2739 unsigned int *opt = menu[i].data;
2741 *opt = (*opt + 1) % data[i].map_size;
2742 if (data[i].map == ignore_space_map) {
2743 update_ignore_space_arg();
2744 string_format_size(msg, SIZEOF_STR,
2745 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2747 } else if (data[i].map == commit_order_map) {
2748 update_commit_order_arg();
2749 string_format_size(msg, SIZEOF_STR,
2750 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2752 } else {
2753 string_format_size(msg, SIZEOF_STR,
2754 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2757 } else {
2758 bool *option = menu[i].data;
2760 *option = !*option;
2761 string_format_size(msg, SIZEOF_STR,
2762 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2765 return data[i].reload_flags;
2770 * Navigation
2773 static bool
2774 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2776 if (lineno >= view->lines)
2777 lineno = view->lines > 0 ? view->lines - 1 : 0;
2779 if (offset > lineno || offset + view->height <= lineno) {
2780 unsigned long half = view->height / 2;
2782 if (lineno > half)
2783 offset = lineno - half;
2784 else
2785 offset = 0;
2788 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2789 view->pos.offset = offset;
2790 view->pos.lineno = lineno;
2791 return TRUE;
2794 return FALSE;
2797 /* Scrolling backend */
2798 static void
2799 do_scroll_view(struct view *view, int lines)
2801 bool redraw_current_line = FALSE;
2803 /* The rendering expects the new offset. */
2804 view->pos.offset += lines;
2806 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2807 assert(lines);
2809 /* Move current line into the view. */
2810 if (view->pos.lineno < view->pos.offset) {
2811 view->pos.lineno = view->pos.offset;
2812 redraw_current_line = TRUE;
2813 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2814 view->pos.lineno = view->pos.offset + view->height - 1;
2815 redraw_current_line = TRUE;
2818 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2820 /* Redraw the whole screen if scrolling is pointless. */
2821 if (view->height < ABS(lines)) {
2822 redraw_view(view);
2824 } else {
2825 int line = lines > 0 ? view->height - lines : 0;
2826 int end = line + ABS(lines);
2828 scrollok(view->win, TRUE);
2829 wscrl(view->win, lines);
2830 scrollok(view->win, FALSE);
2832 while (line < end && draw_view_line(view, line))
2833 line++;
2835 if (redraw_current_line)
2836 draw_view_line(view, view->pos.lineno - view->pos.offset);
2837 wnoutrefresh(view->win);
2840 view->has_scrolled = TRUE;
2841 report_clear();
2844 /* Scroll frontend */
2845 static void
2846 scroll_view(struct view *view, enum request request)
2848 int lines = 1;
2850 assert(view_is_displayed(view));
2852 switch (request) {
2853 case REQ_SCROLL_FIRST_COL:
2854 view->pos.col = 0;
2855 redraw_view_from(view, 0);
2856 report_clear();
2857 return;
2858 case REQ_SCROLL_LEFT:
2859 if (view->pos.col == 0) {
2860 report("Cannot scroll beyond the first column");
2861 return;
2863 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2864 view->pos.col = 0;
2865 else
2866 view->pos.col -= apply_step(opt_hscroll, view->width);
2867 redraw_view_from(view, 0);
2868 report_clear();
2869 return;
2870 case REQ_SCROLL_RIGHT:
2871 view->pos.col += apply_step(opt_hscroll, view->width);
2872 redraw_view(view);
2873 report_clear();
2874 return;
2875 case REQ_SCROLL_PAGE_DOWN:
2876 lines = view->height;
2877 case REQ_SCROLL_LINE_DOWN:
2878 if (view->pos.offset + lines > view->lines)
2879 lines = view->lines - view->pos.offset;
2881 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2882 report("Cannot scroll beyond the last line");
2883 return;
2885 break;
2887 case REQ_SCROLL_PAGE_UP:
2888 lines = view->height;
2889 case REQ_SCROLL_LINE_UP:
2890 if (lines > view->pos.offset)
2891 lines = view->pos.offset;
2893 if (lines == 0) {
2894 report("Cannot scroll beyond the first line");
2895 return;
2898 lines = -lines;
2899 break;
2901 default:
2902 die("request %d not handled in switch", request);
2905 do_scroll_view(view, lines);
2908 /* Cursor moving */
2909 static void
2910 move_view(struct view *view, enum request request)
2912 int scroll_steps = 0;
2913 int steps;
2915 switch (request) {
2916 case REQ_MOVE_FIRST_LINE:
2917 steps = -view->pos.lineno;
2918 break;
2920 case REQ_MOVE_LAST_LINE:
2921 steps = view->lines - view->pos.lineno - 1;
2922 break;
2924 case REQ_MOVE_PAGE_UP:
2925 steps = view->height > view->pos.lineno
2926 ? -view->pos.lineno : -view->height;
2927 break;
2929 case REQ_MOVE_PAGE_DOWN:
2930 steps = view->pos.lineno + view->height >= view->lines
2931 ? view->lines - view->pos.lineno - 1 : view->height;
2932 break;
2934 case REQ_MOVE_UP:
2935 case REQ_PREVIOUS:
2936 steps = -1;
2937 break;
2939 case REQ_MOVE_DOWN:
2940 case REQ_NEXT:
2941 steps = 1;
2942 break;
2944 default:
2945 die("request %d not handled in switch", request);
2948 if (steps <= 0 && view->pos.lineno == 0) {
2949 report("Cannot move beyond the first line");
2950 return;
2952 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2953 report("Cannot move beyond the last line");
2954 return;
2957 /* Move the current line */
2958 view->pos.lineno += steps;
2959 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2961 /* Check whether the view needs to be scrolled */
2962 if (view->pos.lineno < view->pos.offset ||
2963 view->pos.lineno >= view->pos.offset + view->height) {
2964 scroll_steps = steps;
2965 if (steps < 0 && -steps > view->pos.offset) {
2966 scroll_steps = -view->pos.offset;
2968 } else if (steps > 0) {
2969 if (view->pos.lineno == view->lines - 1 &&
2970 view->lines > view->height) {
2971 scroll_steps = view->lines - view->pos.offset - 1;
2972 if (scroll_steps >= view->height)
2973 scroll_steps -= view->height - 1;
2978 if (!view_is_displayed(view)) {
2979 view->pos.offset += scroll_steps;
2980 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2981 view->ops->select(view, &view->line[view->pos.lineno]);
2982 return;
2985 /* Repaint the old "current" line if we be scrolling */
2986 if (ABS(steps) < view->height)
2987 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2989 if (scroll_steps) {
2990 do_scroll_view(view, scroll_steps);
2991 return;
2994 /* Draw the current line */
2995 draw_view_line(view, view->pos.lineno - view->pos.offset);
2997 wnoutrefresh(view->win);
2998 report_clear();
3003 * Searching
3006 static void search_view(struct view *view, enum request request);
3008 static bool
3009 grep_text(struct view *view, const char *text[])
3011 regmatch_t pmatch;
3012 size_t i;
3014 for (i = 0; text[i]; i++)
3015 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
3016 return TRUE;
3017 return FALSE;
3020 static void
3021 select_view_line(struct view *view, unsigned long lineno)
3023 struct position old = view->pos;
3025 if (goto_view_line(view, view->pos.offset, lineno)) {
3026 if (view_is_displayed(view)) {
3027 if (old.offset != view->pos.offset) {
3028 redraw_view(view);
3029 } else {
3030 draw_view_line(view, old.lineno - view->pos.offset);
3031 draw_view_line(view, view->pos.lineno - view->pos.offset);
3032 wnoutrefresh(view->win);
3034 } else {
3035 view->ops->select(view, &view->line[view->pos.lineno]);
3040 static void
3041 find_next(struct view *view, enum request request)
3043 unsigned long lineno = view->pos.lineno;
3044 int direction;
3046 if (!*view->grep) {
3047 if (!*opt_search)
3048 report("No previous search");
3049 else
3050 search_view(view, request);
3051 return;
3054 switch (request) {
3055 case REQ_SEARCH:
3056 case REQ_FIND_NEXT:
3057 direction = 1;
3058 break;
3060 case REQ_SEARCH_BACK:
3061 case REQ_FIND_PREV:
3062 direction = -1;
3063 break;
3065 default:
3066 return;
3069 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
3070 lineno += direction;
3072 /* Note, lineno is unsigned long so will wrap around in which case it
3073 * will become bigger than view->lines. */
3074 for (; lineno < view->lines; lineno += direction) {
3075 if (view->ops->grep(view, &view->line[lineno])) {
3076 select_view_line(view, lineno);
3077 report("Line %ld matches '%s'", lineno + 1, view->grep);
3078 return;
3082 report("No match found for '%s'", view->grep);
3085 static void
3086 search_view(struct view *view, enum request request)
3088 int regex_err;
3089 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3091 if (view->regex) {
3092 regfree(view->regex);
3093 *view->grep = 0;
3094 } else {
3095 view->regex = calloc(1, sizeof(*view->regex));
3096 if (!view->regex)
3097 return;
3100 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3101 if (regex_err != 0) {
3102 char buf[SIZEOF_STR] = "unknown error";
3104 regerror(regex_err, view->regex, buf, sizeof(buf));
3105 report("Search failed: %s", buf);
3106 return;
3109 string_copy(view->grep, opt_search);
3111 find_next(view, request);
3115 * Incremental updating
3118 static inline bool
3119 check_position(struct position *pos)
3121 return pos->lineno || pos->col || pos->offset;
3124 static inline void
3125 clear_position(struct position *pos)
3127 memset(pos, 0, sizeof(*pos));
3130 static void
3131 reset_view(struct view *view)
3133 int i;
3135 if (view->ops->done)
3136 view->ops->done(view);
3138 for (i = 0; i < view->lines; i++)
3139 free(view->line[i].data);
3140 free(view->line);
3142 view->prev_pos = view->pos;
3143 clear_position(&view->pos);
3145 view->line = NULL;
3146 view->lines = 0;
3147 view->vid[0] = 0;
3148 view->custom_lines = 0;
3149 view->update_secs = 0;
3152 struct format_context {
3153 struct view *view;
3154 char buf[SIZEOF_STR];
3155 size_t bufpos;
3156 bool file_filter;
3159 static bool
3160 format_expand_arg(struct format_context *format, const char *name)
3162 static struct {
3163 const char *name;
3164 size_t namelen;
3165 const char *value;
3166 const char *value_if_empty;
3167 } vars[] = {
3168 #define FORMAT_VAR(name, value, value_if_empty) \
3169 { name, STRING_SIZE(name), value, value_if_empty }
3170 FORMAT_VAR("%(directory)", opt_path, "."),
3171 FORMAT_VAR("%(file)", opt_file, ""),
3172 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3173 FORMAT_VAR("%(head)", ref_head, ""),
3174 FORMAT_VAR("%(commit)", ref_commit, ""),
3175 FORMAT_VAR("%(blob)", ref_blob, ""),
3176 FORMAT_VAR("%(branch)", ref_branch, ""),
3177 FORMAT_VAR("%(stash)", ref_stash, ""),
3179 int i;
3181 if (!prefixcmp(name, "%(prompt)")) {
3182 const char *value = read_prompt("Command argument: ");
3184 return string_format_from(format->buf, &format->bufpos, "%s", value);
3187 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3188 const char *value;
3190 if (strncmp(name, vars[i].name, vars[i].namelen))
3191 continue;
3193 if (vars[i].value == opt_file && !format->file_filter)
3194 return TRUE;
3196 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3197 if (!*value)
3198 return TRUE;
3200 return string_format_from(format->buf, &format->bufpos, "%s", value);
3203 report("Unknown replacement: `%s`", name);
3204 return NULL;
3207 static bool
3208 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3210 memset(format->buf, 0, sizeof(format->buf));
3211 format->bufpos = 0;
3213 while (arg) {
3214 char *next = strstr(arg, "%(");
3215 int len = next ? next - arg : strlen(arg);
3217 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3218 return FALSE;
3220 if (next && !format_expand_arg(format, next))
3221 return FALSE;
3223 arg = next ? strchr(next, ')') + 1 : NULL;
3226 return argv_append(dst_argv, format->buf);
3229 static bool
3230 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3232 int argc;
3234 if (!src_argv)
3235 return TRUE;
3237 for (argc = 0; src_argv[argc]; argc++)
3238 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3239 return FALSE;
3241 return src_argv[argc] == NULL;
3244 static bool
3245 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3247 struct format_context format = { view, "", 0, file_filter };
3248 int argc;
3250 argv_free(*dst_argv);
3252 for (argc = 0; src_argv[argc]; argc++) {
3253 const char *arg = src_argv[argc];
3255 if (!strcmp(arg, "%(fileargs)")) {
3256 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3257 break;
3259 } else if (!strcmp(arg, "%(diffargs)")) {
3260 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3261 break;
3263 } else if (!strcmp(arg, "%(blameargs)")) {
3264 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3265 break;
3267 } else if (!strcmp(arg, "%(revargs)") ||
3268 (first && !strcmp(arg, "%(commit)"))) {
3269 if (!argv_append_array(dst_argv, opt_rev_argv))
3270 break;
3272 } else if (!format_append_arg(&format, dst_argv, arg)) {
3273 break;
3277 return src_argv[argc] == NULL;
3280 static bool
3281 restore_view_position(struct view *view)
3283 /* A view without a previous view is the first view */
3284 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3285 select_view_line(view, opt_lineno - 1);
3286 opt_lineno = 0;
3289 /* Ensure that the view position is in a valid state. */
3290 if (!check_position(&view->prev_pos) ||
3291 (view->pipe && view->lines <= view->prev_pos.lineno))
3292 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3294 /* Changing the view position cancels the restoring. */
3295 /* FIXME: Changing back to the first line is not detected. */
3296 if (check_position(&view->pos)) {
3297 clear_position(&view->prev_pos);
3298 return FALSE;
3301 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3302 view_is_displayed(view))
3303 werase(view->win);
3305 view->pos.col = view->prev_pos.col;
3306 clear_position(&view->prev_pos);
3308 return TRUE;
3311 static void
3312 end_update(struct view *view, bool force)
3314 if (!view->pipe)
3315 return;
3316 while (!view->ops->read(view, NULL))
3317 if (!force)
3318 return;
3319 if (force)
3320 io_kill(view->pipe);
3321 io_done(view->pipe);
3322 view->pipe = NULL;
3325 static void
3326 setup_update(struct view *view, const char *vid)
3328 reset_view(view);
3329 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3330 string_ncopy(view->vid, vid, strlen(vid));
3331 view->pipe = &view->io;
3332 view->start_time = time(NULL);
3335 static bool
3336 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3338 bool extra = !!(flags & (OPEN_EXTRA));
3339 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3340 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3341 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3342 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3344 if ((!reload && !strcmp(view->vid, view->id)) ||
3345 ((flags & OPEN_REFRESH) && view->unrefreshable))
3346 return TRUE;
3348 if (view->pipe) {
3349 if (extra)
3350 io_done(view->pipe);
3351 else
3352 end_update(view, TRUE);
3355 view->unrefreshable = open_in_pager_mode(flags);
3357 if (!refresh && argv) {
3358 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3360 view->dir = dir;
3361 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3362 report("Failed to format %s arguments", view->name);
3363 return FALSE;
3366 /* Put the current ref_* value to the view title ref
3367 * member. This is needed by the blob view. Most other
3368 * views sets it automatically after loading because the
3369 * first line is a commit line. */
3370 string_copy_rev(view->ref, view->id);
3373 if (view->argv && view->argv[0] &&
3374 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3375 report("Failed to open %s view", view->name);
3376 return FALSE;
3379 if (open_from_stdin(flags)) {
3380 if (!io_open(&view->io, "%s", ""))
3381 die("Failed to open stdin");
3384 if (!extra)
3385 setup_update(view, view->id);
3387 return TRUE;
3390 static bool
3391 update_view(struct view *view)
3393 char *line;
3394 /* Clear the view and redraw everything since the tree sorting
3395 * might have rearranged things. */
3396 bool redraw = view->lines == 0;
3397 bool can_read = TRUE;
3398 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3400 if (!view->pipe)
3401 return TRUE;
3403 if (!io_can_read(view->pipe, FALSE)) {
3404 if (view->lines == 0 && view_is_displayed(view)) {
3405 time_t secs = time(NULL) - view->start_time;
3407 if (secs > 1 && secs > view->update_secs) {
3408 if (view->update_secs == 0)
3409 redraw_view(view);
3410 update_view_title(view);
3411 view->update_secs = secs;
3414 return TRUE;
3417 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3418 if (encoding) {
3419 line = encoding_convert(encoding, line);
3422 if (!view->ops->read(view, line)) {
3423 report("Allocation failure");
3424 end_update(view, TRUE);
3425 return FALSE;
3430 int digits = count_digits(view->lines);
3432 /* Keep the displayed view in sync with line number scaling. */
3433 if (digits != view->digits) {
3434 view->digits = digits;
3435 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3436 redraw = TRUE;
3440 if (io_error(view->pipe)) {
3441 report("Failed to read: %s", io_strerror(view->pipe));
3442 end_update(view, TRUE);
3444 } else if (io_eof(view->pipe)) {
3445 end_update(view, FALSE);
3448 if (restore_view_position(view))
3449 redraw = TRUE;
3451 if (!view_is_displayed(view))
3452 return TRUE;
3454 if (redraw || view->force_redraw)
3455 redraw_view_from(view, 0);
3456 else
3457 redraw_view_dirty(view);
3458 view->force_redraw = FALSE;
3460 /* Update the title _after_ the redraw so that if the redraw picks up a
3461 * commit reference in view->ref it'll be available here. */
3462 update_view_title(view);
3463 return TRUE;
3466 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3468 static struct line *
3469 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3471 struct line *line;
3473 if (!realloc_lines(&view->line, view->lines, 1))
3474 return NULL;
3476 if (data_size) {
3477 void *alloc_data = calloc(1, data_size);
3479 if (!alloc_data)
3480 return NULL;
3482 if (data)
3483 memcpy(alloc_data, data, data_size);
3484 data = alloc_data;
3487 line = &view->line[view->lines++];
3488 memset(line, 0, sizeof(*line));
3489 line->type = type;
3490 line->data = (void *) data;
3491 line->dirty = 1;
3493 if (custom)
3494 view->custom_lines++;
3495 else
3496 line->lineno = view->lines - view->custom_lines;
3498 return line;
3501 static struct line *
3502 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3504 struct line *line = add_line(view, NULL, type, data_size, custom);
3506 if (line)
3507 *ptr = line->data;
3508 return line;
3511 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3512 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3514 static struct line *
3515 add_line_nodata(struct view *view, enum line_type type)
3517 return add_line(view, NULL, type, 0, FALSE);
3520 static struct line *
3521 add_line_text(struct view *view, const char *text, enum line_type type)
3523 return add_line(view, text, type, strlen(text) + 1, FALSE);
3526 static struct line * PRINTF_LIKE(3, 4)
3527 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3529 char buf[SIZEOF_STR];
3530 int retval;
3532 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3533 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3537 * View opening
3540 static void
3541 split_view(struct view *prev, struct view *view)
3543 display[1] = view;
3544 current_view = opt_focus_child ? 1 : 0;
3545 view->parent = prev;
3546 resize_display();
3548 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3549 /* Take the title line into account. */
3550 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3552 /* Scroll the view that was split if the current line is
3553 * outside the new limited view. */
3554 do_scroll_view(prev, lines);
3557 if (view != prev && view_is_displayed(prev)) {
3558 /* "Blur" the previous view. */
3559 update_view_title(prev);
3563 static void
3564 maximize_view(struct view *view, bool redraw)
3566 memset(display, 0, sizeof(display));
3567 current_view = 0;
3568 display[current_view] = view;
3569 resize_display();
3570 if (redraw) {
3571 redraw_display(FALSE);
3572 report_clear();
3576 static void
3577 load_view(struct view *view, struct view *prev, enum open_flags flags)
3579 if (view->pipe)
3580 end_update(view, TRUE);
3581 if (view->ops->private_size) {
3582 if (!view->private)
3583 view->private = calloc(1, view->ops->private_size);
3584 else
3585 memset(view->private, 0, view->ops->private_size);
3588 /* When prev == view it means this is the first loaded view. */
3589 if (prev && view != prev) {
3590 view->prev = prev;
3593 if (!view->ops->open(view, flags))
3594 return;
3596 if (prev) {
3597 bool split = !!(flags & OPEN_SPLIT);
3599 if (split) {
3600 split_view(prev, view);
3601 } else {
3602 maximize_view(view, FALSE);
3606 restore_view_position(view);
3608 if (view->pipe && view->lines == 0) {
3609 /* Clear the old view and let the incremental updating refill
3610 * the screen. */
3611 werase(view->win);
3612 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3613 clear_position(&view->prev_pos);
3614 report_clear();
3615 } else if (view_is_displayed(view)) {
3616 redraw_view(view);
3617 report_clear();
3621 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3622 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3624 static void
3625 open_view(struct view *prev, enum request request, enum open_flags flags)
3627 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3628 struct view *view = VIEW(request);
3629 int nviews = displayed_views();
3631 assert(flags ^ OPEN_REFRESH);
3633 if (view == prev && nviews == 1 && !reload) {
3634 report("Already in %s view", view->name);
3635 return;
3638 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3639 report("The %s view is disabled in pager view", view->name);
3640 return;
3643 load_view(view, prev ? prev : view, flags);
3646 static void
3647 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3649 enum request request = view - views + REQ_OFFSET + 1;
3651 if (view->pipe)
3652 end_update(view, TRUE);
3653 view->dir = dir;
3655 if (!argv_copy(&view->argv, argv)) {
3656 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3657 } else {
3658 open_view(prev, request, flags | OPEN_PREPARED);
3662 static bool
3663 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3665 bool ok;
3667 def_prog_mode(); /* save current tty modes */
3668 endwin(); /* restore original tty modes */
3669 ok = io_run_fg(argv, dir);
3670 if (confirm) {
3671 if (!ok && *notice)
3672 fprintf(stderr, "%s", notice);
3673 fprintf(stderr, "Press Enter to continue");
3674 getc(opt_tty);
3676 reset_prog_mode();
3677 redraw_display(TRUE);
3678 return ok;
3681 static void
3682 open_mergetool(const char *file)
3684 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3686 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3689 #define EDITOR_LINENO_MSG \
3690 "*** Your editor reported an error while opening the file.\n" \
3691 "*** This is probably because it doesn't support the line\n" \
3692 "*** number argument added automatically. The line number\n" \
3693 "*** has been disabled for now. You can permanently disable\n" \
3694 "*** it by adding the following line to ~/.tigrc\n" \
3695 "*** set editor-line-number = no\n"
3697 static void
3698 open_editor(const char *file, unsigned int lineno)
3700 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3701 char editor_cmd[SIZEOF_STR];
3702 char lineno_cmd[SIZEOF_STR];
3703 const char *editor;
3704 int argc = 0;
3706 editor = getenv("GIT_EDITOR");
3707 if (!editor && *opt_editor)
3708 editor = opt_editor;
3709 if (!editor)
3710 editor = getenv("VISUAL");
3711 if (!editor)
3712 editor = getenv("EDITOR");
3713 if (!editor)
3714 editor = "vi";
3716 string_ncopy(editor_cmd, editor, strlen(editor));
3717 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3718 report("Failed to read editor command");
3719 return;
3722 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3723 editor_argv[argc++] = lineno_cmd;
3724 editor_argv[argc] = file;
3725 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3726 opt_editor_lineno = FALSE;
3729 static enum request run_prompt_command(struct view *view, char *cmd);
3731 static enum request
3732 open_run_request(struct view *view, enum request request)
3734 struct run_request *req = get_run_request(request);
3735 const char **argv = NULL;
3736 bool confirmed = FALSE;
3738 request = REQ_NONE;
3740 if (!req) {
3741 report("Unknown run request");
3742 return request;
3745 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3746 if (req->internal) {
3747 char cmd[SIZEOF_STR];
3749 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3750 request = run_prompt_command(view, cmd);
3753 else {
3754 confirmed = !req->confirm;
3756 if (req->confirm) {
3757 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3758 const char *and_exit = req->exit ? " and exit" : "";
3760 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3761 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3762 prompt_yesno(prompt)) {
3763 confirmed = TRUE;
3767 if (confirmed && argv_remove_quotes(argv)) {
3768 if (req->silent)
3769 io_run_bg(argv);
3770 else
3771 open_external_viewer(argv, NULL, !req->exit, "");
3776 if (argv)
3777 argv_free(argv);
3778 free(argv);
3780 if (request == REQ_NONE) {
3781 if (req->confirm && !confirmed)
3782 request = REQ_NONE;
3784 else if (req->exit)
3785 request = REQ_QUIT;
3787 else if (!view->unrefreshable)
3788 request = REQ_REFRESH;
3790 return request;
3794 * User request switch noodle
3797 static int
3798 view_driver(struct view *view, enum request request)
3800 int i;
3802 if (request == REQ_NONE)
3803 return TRUE;
3805 if (request > REQ_NONE) {
3806 request = open_run_request(view, request);
3808 // exit quickly rather than going through view_request and back
3809 if (request == REQ_QUIT)
3810 return FALSE;
3813 request = view_request(view, request);
3814 if (request == REQ_NONE)
3815 return TRUE;
3817 switch (request) {
3818 case REQ_MOVE_UP:
3819 case REQ_MOVE_DOWN:
3820 case REQ_MOVE_PAGE_UP:
3821 case REQ_MOVE_PAGE_DOWN:
3822 case REQ_MOVE_FIRST_LINE:
3823 case REQ_MOVE_LAST_LINE:
3824 move_view(view, request);
3825 break;
3827 case REQ_SCROLL_FIRST_COL:
3828 case REQ_SCROLL_LEFT:
3829 case REQ_SCROLL_RIGHT:
3830 case REQ_SCROLL_LINE_DOWN:
3831 case REQ_SCROLL_LINE_UP:
3832 case REQ_SCROLL_PAGE_DOWN:
3833 case REQ_SCROLL_PAGE_UP:
3834 scroll_view(view, request);
3835 break;
3837 case REQ_VIEW_MAIN:
3838 case REQ_VIEW_DIFF:
3839 case REQ_VIEW_LOG:
3840 case REQ_VIEW_TREE:
3841 case REQ_VIEW_HELP:
3842 case REQ_VIEW_BRANCH:
3843 case REQ_VIEW_BLAME:
3844 case REQ_VIEW_BLOB:
3845 case REQ_VIEW_STATUS:
3846 case REQ_VIEW_STAGE:
3847 case REQ_VIEW_PAGER:
3848 case REQ_VIEW_STASH:
3849 open_view(view, request, OPEN_DEFAULT);
3850 break;
3852 case REQ_NEXT:
3853 case REQ_PREVIOUS:
3854 if (view->parent) {
3855 int line;
3857 view = view->parent;
3858 line = view->pos.lineno;
3859 view_request(view, request);
3860 move_view(view, request);
3861 if (view_is_displayed(view))
3862 update_view_title(view);
3863 if (line != view->pos.lineno)
3864 view_request(view, REQ_ENTER);
3865 } else {
3866 move_view(view, request);
3868 break;
3870 case REQ_VIEW_NEXT:
3872 int nviews = displayed_views();
3873 int next_view = (current_view + 1) % nviews;
3875 if (next_view == current_view) {
3876 report("Only one view is displayed");
3877 break;
3880 current_view = next_view;
3881 /* Blur out the title of the previous view. */
3882 update_view_title(view);
3883 report_clear();
3884 break;
3886 case REQ_REFRESH:
3887 report("Refreshing is not yet supported for the %s view", view->name);
3888 break;
3890 case REQ_MAXIMIZE:
3891 if (displayed_views() == 2)
3892 maximize_view(view, TRUE);
3893 break;
3895 case REQ_OPTIONS:
3896 case REQ_TOGGLE_LINENO:
3897 case REQ_TOGGLE_DATE:
3898 case REQ_TOGGLE_AUTHOR:
3899 case REQ_TOGGLE_FILENAME:
3900 case REQ_TOGGLE_GRAPHIC:
3901 case REQ_TOGGLE_REV_GRAPH:
3902 case REQ_TOGGLE_REFS:
3903 case REQ_TOGGLE_CHANGES:
3904 case REQ_TOGGLE_IGNORE_SPACE:
3905 case REQ_TOGGLE_ID:
3906 case REQ_TOGGLE_FILES:
3907 case REQ_TOGGLE_TITLE_OVERFLOW:
3909 char action[SIZEOF_STR] = "";
3910 enum view_flag flags = toggle_option(view, request, action);
3912 foreach_displayed_view(view, i) {
3913 if (view_has_flags(view, flags) && !view->unrefreshable)
3914 reload_view(view);
3915 else
3916 redraw_view(view);
3919 if (*action)
3920 report("%s", action);
3922 break;
3924 case REQ_TOGGLE_SORT_FIELD:
3925 case REQ_TOGGLE_SORT_ORDER:
3926 report("Sorting is not yet supported for the %s view", view->name);
3927 break;
3929 case REQ_DIFF_CONTEXT_UP:
3930 case REQ_DIFF_CONTEXT_DOWN:
3931 report("Changing the diff context is not yet supported for the %s view", view->name);
3932 break;
3934 case REQ_SEARCH:
3935 case REQ_SEARCH_BACK:
3936 search_view(view, request);
3937 break;
3939 case REQ_FIND_NEXT:
3940 case REQ_FIND_PREV:
3941 find_next(view, request);
3942 break;
3944 case REQ_STOP_LOADING:
3945 foreach_view(view, i) {
3946 if (view->pipe)
3947 report("Stopped loading the %s view", view->name),
3948 end_update(view, TRUE);
3950 break;
3952 case REQ_SHOW_VERSION:
3953 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3954 return TRUE;
3956 case REQ_SCREEN_REDRAW:
3957 redraw_display(TRUE);
3958 break;
3960 case REQ_EDIT:
3961 report("Nothing to edit");
3962 break;
3964 case REQ_ENTER:
3965 report("Nothing to enter");
3966 break;
3968 case REQ_VIEW_CLOSE:
3969 /* XXX: Mark closed views by letting view->prev point to the
3970 * view itself. Parents to closed view should never be
3971 * followed. */
3972 if (view->prev && view->prev != view) {
3973 maximize_view(view->prev, TRUE);
3974 view->prev = view;
3975 break;
3977 /* Fall-through */
3978 case REQ_QUIT:
3979 return FALSE;
3981 default:
3982 report("Unknown key, press %s for help",
3983 get_view_key(view, REQ_VIEW_HELP));
3984 return TRUE;
3987 return TRUE;
3992 * View backend utilities
3995 enum sort_field {
3996 ORDERBY_NAME,
3997 ORDERBY_DATE,
3998 ORDERBY_AUTHOR,
4001 struct sort_state {
4002 const enum sort_field *fields;
4003 size_t size, current;
4004 bool reverse;
4007 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
4008 #define get_sort_field(state) ((state).fields[(state).current])
4009 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
4011 static void
4012 sort_view(struct view *view, enum request request, struct sort_state *state,
4013 int (*compare)(const void *, const void *))
4015 switch (request) {
4016 case REQ_TOGGLE_SORT_FIELD:
4017 state->current = (state->current + 1) % state->size;
4018 break;
4020 case REQ_TOGGLE_SORT_ORDER:
4021 state->reverse = !state->reverse;
4022 break;
4023 default:
4024 die("Not a sort request");
4027 qsort(view->line, view->lines, sizeof(*view->line), compare);
4028 redraw_view(view);
4031 static bool
4032 update_diff_context(enum request request)
4034 int diff_context = opt_diff_context;
4036 switch (request) {
4037 case REQ_DIFF_CONTEXT_UP:
4038 opt_diff_context += 1;
4039 update_diff_context_arg(opt_diff_context);
4040 break;
4042 case REQ_DIFF_CONTEXT_DOWN:
4043 if (opt_diff_context == 0) {
4044 report("Diff context cannot be less than zero");
4045 break;
4047 opt_diff_context -= 1;
4048 update_diff_context_arg(opt_diff_context);
4049 break;
4051 default:
4052 die("Not a diff context request");
4055 return diff_context != opt_diff_context;
4058 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4060 /* Small author cache to reduce memory consumption. It uses binary
4061 * search to lookup or find place to position new entries. No entries
4062 * are ever freed. */
4063 static struct ident *
4064 get_author(const char *name, const char *email)
4066 static struct ident **authors;
4067 static size_t authors_size;
4068 int from = 0, to = authors_size - 1;
4069 struct ident *ident;
4071 while (from <= to) {
4072 size_t pos = (to + from) / 2;
4073 int cmp = strcmp(name, authors[pos]->name);
4075 if (!cmp)
4076 return authors[pos];
4078 if (cmp < 0)
4079 to = pos - 1;
4080 else
4081 from = pos + 1;
4084 if (!realloc_authors(&authors, authors_size, 1))
4085 return NULL;
4086 ident = calloc(1, sizeof(*ident));
4087 if (!ident)
4088 return NULL;
4089 ident->name = strdup(name);
4090 ident->email = strdup(email);
4091 if (!ident->name || !ident->email) {
4092 free((void *) ident->name);
4093 free(ident);
4094 return NULL;
4097 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4098 authors[from] = ident;
4099 authors_size++;
4101 return ident;
4104 static void
4105 parse_timesec(struct time *time, const char *sec)
4107 time->sec = (time_t) atol(sec);
4110 static void
4111 parse_timezone(struct time *time, const char *zone)
4113 long tz;
4115 tz = ('0' - zone[1]) * 60 * 60 * 10;
4116 tz += ('0' - zone[2]) * 60 * 60;
4117 tz += ('0' - zone[3]) * 60 * 10;
4118 tz += ('0' - zone[4]) * 60;
4120 if (zone[0] == '-')
4121 tz = -tz;
4123 time->tz = tz;
4124 time->sec -= tz;
4127 /* Parse author lines where the name may be empty:
4128 * author <email@address.tld> 1138474660 +0100
4130 static void
4131 parse_author_line(char *ident, const struct ident **author, struct time *time)
4133 char *nameend = strchr(ident, '<');
4134 char *emailend = strchr(ident, '>');
4135 const char *name, *email = "";
4137 if (nameend && emailend)
4138 *nameend = *emailend = 0;
4139 name = chomp_string(ident);
4140 if (nameend)
4141 email = chomp_string(nameend + 1);
4142 if (!*name)
4143 name = *email ? email : unknown_ident.name;
4144 if (!*email)
4145 email = *name ? name : unknown_ident.email;
4147 *author = get_author(name, email);
4149 /* Parse epoch and timezone */
4150 if (time && emailend && emailend[1] == ' ') {
4151 char *secs = emailend + 2;
4152 char *zone = strchr(secs, ' ');
4154 parse_timesec(time, secs);
4156 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4157 parse_timezone(time, zone + 1);
4161 static struct line *
4162 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4164 for (; view_has_line(view, line); line += direction)
4165 if (line->type == type)
4166 return line;
4168 return NULL;
4171 #define find_prev_line_by_type(view, line, type) \
4172 find_line_by_type(view, line, type, -1)
4174 #define find_next_line_by_type(view, line, type) \
4175 find_line_by_type(view, line, type, 1)
4178 * Blame
4181 struct blame_commit {
4182 char id[SIZEOF_REV]; /* SHA1 ID. */
4183 char title[128]; /* First line of the commit message. */
4184 const struct ident *author; /* Author of the commit. */
4185 struct time time; /* Date from the author ident. */
4186 char filename[128]; /* Name of file. */
4187 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4188 char parent_filename[128]; /* Parent/previous name of file. */
4191 struct blame_header {
4192 char id[SIZEOF_REV]; /* SHA1 ID. */
4193 size_t orig_lineno;
4194 size_t lineno;
4195 size_t group;
4198 static bool
4199 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4201 const char *pos = *posref;
4203 *posref = NULL;
4204 pos = strchr(pos + 1, ' ');
4205 if (!pos || !isdigit(pos[1]))
4206 return FALSE;
4207 *number = atoi(pos + 1);
4208 if (*number < min || *number > max)
4209 return FALSE;
4211 *posref = pos;
4212 return TRUE;
4215 static bool
4216 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4218 const char *pos = text + SIZEOF_REV - 2;
4220 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4221 return FALSE;
4223 string_ncopy(header->id, text, SIZEOF_REV);
4225 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4226 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4227 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4228 return FALSE;
4230 return TRUE;
4233 static bool
4234 match_blame_header(const char *name, char **line)
4236 size_t namelen = strlen(name);
4237 bool matched = !strncmp(name, *line, namelen);
4239 if (matched)
4240 *line += namelen;
4242 return matched;
4245 static bool
4246 parse_blame_info(struct blame_commit *commit, char *line)
4248 if (match_blame_header("author ", &line)) {
4249 parse_author_line(line, &commit->author, NULL);
4251 } else if (match_blame_header("author-time ", &line)) {
4252 parse_timesec(&commit->time, line);
4254 } else if (match_blame_header("author-tz ", &line)) {
4255 parse_timezone(&commit->time, line);
4257 } else if (match_blame_header("summary ", &line)) {
4258 string_ncopy(commit->title, line, strlen(line));
4260 } else if (match_blame_header("previous ", &line)) {
4261 if (strlen(line) <= SIZEOF_REV)
4262 return FALSE;
4263 string_copy_rev(commit->parent_id, line);
4264 line += SIZEOF_REV;
4265 string_ncopy(commit->parent_filename, line, strlen(line));
4267 } else if (match_blame_header("filename ", &line)) {
4268 string_ncopy(commit->filename, line, strlen(line));
4269 return TRUE;
4272 return FALSE;
4276 * Pager backend
4279 static bool
4280 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4282 if (draw_lineno(view, lineno))
4283 return TRUE;
4285 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4286 return TRUE;
4288 draw_text(view, line->type, line->data);
4289 return TRUE;
4292 static bool
4293 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4295 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4296 char ref[SIZEOF_STR];
4298 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4299 return TRUE;
4301 /* This is the only fatal call, since it can "corrupt" the buffer. */
4302 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4303 return FALSE;
4305 return TRUE;
4308 static void
4309 add_pager_refs(struct view *view, const char *commit_id)
4311 char buf[SIZEOF_STR];
4312 struct ref_list *list;
4313 size_t bufpos = 0, i;
4314 const char *sep = "Refs: ";
4315 bool is_tag = FALSE;
4317 list = get_ref_list(commit_id);
4318 if (!list) {
4319 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4320 goto try_add_describe_ref;
4321 return;
4324 for (i = 0; i < list->size; i++) {
4325 struct ref *ref = list->refs[i];
4326 const char *fmt = ref->tag ? "%s[%s]" :
4327 ref->remote ? "%s<%s>" : "%s%s";
4329 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4330 return;
4331 sep = ", ";
4332 if (ref->tag)
4333 is_tag = TRUE;
4336 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4337 try_add_describe_ref:
4338 /* Add <tag>-g<commit_id> "fake" reference. */
4339 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4340 return;
4343 if (bufpos == 0)
4344 return;
4346 add_line_text(view, buf, LINE_PP_REFS);
4349 static struct line *
4350 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4352 size_t first_line = 0;
4353 bool has_first_line = FALSE;
4354 size_t datalen = strlen(data);
4355 size_t lineno = 0;
4357 while (datalen > 0 || !has_first_line) {
4358 bool wrapped = !!first_line;
4359 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4360 struct line *line;
4361 char *text;
4363 line = add_line(view, NULL, type, linelen + 1, wrapped);
4364 if (!line)
4365 break;
4366 if (!has_first_line) {
4367 first_line = view->lines - 1;
4368 has_first_line = TRUE;
4371 if (!wrapped)
4372 lineno = line->lineno;
4374 line->wrapped = wrapped;
4375 line->lineno = lineno;
4376 text = line->data;
4377 if (linelen)
4378 strncpy(text, data, linelen);
4379 text[linelen] = 0;
4381 datalen -= linelen;
4382 data += linelen;
4385 return has_first_line ? &view->line[first_line] : NULL;
4388 static bool
4389 pager_common_read(struct view *view, const char *data, enum line_type type)
4391 struct line *line;
4393 if (!data)
4394 return TRUE;
4396 if (opt_wrap_lines) {
4397 line = pager_wrap_line(view, data, type);
4398 } else {
4399 line = add_line_text(view, data, type);
4402 if (!line)
4403 return FALSE;
4405 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4406 add_pager_refs(view, data + STRING_SIZE("commit "));
4408 return TRUE;
4411 static bool
4412 pager_read(struct view *view, char *data)
4414 if (!data)
4415 return TRUE;
4417 return pager_common_read(view, data, get_line_type(data));
4420 static enum request
4421 pager_request(struct view *view, enum request request, struct line *line)
4423 int split = 0;
4425 if (request != REQ_ENTER)
4426 return request;
4428 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4429 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4430 split = 1;
4433 /* Always scroll the view even if it was split. That way
4434 * you can use Enter to scroll through the log view and
4435 * split open each commit diff. */
4436 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4438 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4439 * but if we are scrolling a non-current view this won't properly
4440 * update the view title. */
4441 if (split)
4442 update_view_title(view);
4444 return REQ_NONE;
4447 static bool
4448 pager_grep(struct view *view, struct line *line)
4450 const char *text[] = { line->data, NULL };
4452 return grep_text(view, text);
4455 static void
4456 pager_select(struct view *view, struct line *line)
4458 if (line->type == LINE_COMMIT) {
4459 string_copy_rev_from_commit_line(ref_commit, line->data);
4460 if (!view_has_flags(view, VIEW_NO_REF))
4461 string_copy_rev(view->ref, ref_commit);
4465 struct log_state {
4466 /* Used for tracking when we need to recalculate the previous
4467 * commit, for example when the user scrolls up or uses the page
4468 * up/down in the log view. */
4469 int last_lineno;
4470 enum line_type last_type;
4473 static void
4474 log_select(struct view *view, struct line *line)
4476 struct log_state *state = view->private;
4477 int last_lineno = state->last_lineno;
4479 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4480 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4481 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4483 if (commit_line)
4484 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4487 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4488 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4490 string_copy_rev(ref_commit, view->ref);
4491 state->last_lineno = line->lineno;
4492 state->last_type = line->type;
4495 static bool
4496 pager_open(struct view *view, enum open_flags flags)
4498 if (!open_from_stdin(flags) && !view->lines) {
4499 report("No pager content, press %s to run command from prompt",
4500 get_view_key(view, REQ_PROMPT));
4501 return FALSE;
4504 return begin_update(view, NULL, NULL, flags);
4507 static struct view_ops pager_ops = {
4508 "line",
4509 { "pager" },
4510 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4512 pager_open,
4513 pager_read,
4514 pager_draw,
4515 pager_request,
4516 pager_grep,
4517 pager_select,
4520 static bool
4521 log_open(struct view *view, enum open_flags flags)
4523 static const char *log_argv[] = {
4524 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4527 return begin_update(view, NULL, log_argv, flags);
4530 static enum request
4531 log_request(struct view *view, enum request request, struct line *line)
4533 switch (request) {
4534 case REQ_REFRESH:
4535 load_refs(TRUE);
4536 refresh_view(view);
4537 return REQ_NONE;
4539 case REQ_ENTER:
4540 if (!display[1] || strcmp(display[1]->vid, view->ref))
4541 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4542 return REQ_NONE;
4544 default:
4545 return request;
4549 static struct view_ops log_ops = {
4550 "line",
4551 { "log" },
4552 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4553 sizeof(struct log_state),
4554 log_open,
4555 pager_read,
4556 pager_draw,
4557 log_request,
4558 pager_grep,
4559 log_select,
4562 struct diff_state {
4563 bool after_commit_title;
4564 bool after_diff;
4565 bool reading_diff_stat;
4566 bool combined_diff;
4569 #define DIFF_LINE_COMMIT_TITLE 1
4571 static bool
4572 diff_open(struct view *view, enum open_flags flags)
4574 static const char *diff_argv[] = {
4575 "git", "show", opt_encoding_arg, "--pretty=fuller", "--root",
4576 "--patch-with-stat",
4577 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4578 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4581 return begin_update(view, NULL, diff_argv, flags);
4584 static bool
4585 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4587 enum line_type type = get_line_type(data);
4589 if (!view->lines && type != LINE_COMMIT)
4590 state->reading_diff_stat = TRUE;
4592 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4593 state->reading_diff_stat = TRUE;
4595 if (state->reading_diff_stat) {
4596 size_t len = strlen(data);
4597 char *pipe = strchr(data, '|');
4598 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4599 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4600 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4602 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4603 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4604 } else {
4605 state->reading_diff_stat = FALSE;
4608 } else if (!strcmp(data, "---")) {
4609 state->reading_diff_stat = TRUE;
4612 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4613 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4615 if (line)
4616 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4617 state->after_commit_title = TRUE;
4618 return line != NULL;
4621 if (type == LINE_DIFF_HEADER) {
4622 const int len = line_info[LINE_DIFF_HEADER].linelen;
4624 state->after_diff = TRUE;
4625 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4626 !strncmp(data + len, "cc ", strlen("cc ")))
4627 state->combined_diff = TRUE;
4629 } else if (type == LINE_PP_MERGE) {
4630 state->combined_diff = TRUE;
4633 /* ADD2 and DEL2 are only valid in combined diff hunks */
4634 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4635 type = LINE_DEFAULT;
4637 return pager_common_read(view, data, type);
4640 static bool
4641 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4643 struct line *marker = find_next_line_by_type(view, line, type);
4645 return marker &&
4646 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4649 static enum request
4650 diff_common_enter(struct view *view, enum request request, struct line *line)
4652 if (line->type == LINE_DIFF_STAT) {
4653 int file_number = 0;
4655 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4656 file_number++;
4657 line--;
4660 for (line = view->line; view_has_line(view, line); line++) {
4661 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4662 if (!line)
4663 break;
4665 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4666 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4667 if (file_number == 1) {
4668 break;
4670 file_number--;
4674 if (!line) {
4675 report("Failed to find file diff");
4676 return REQ_NONE;
4679 select_view_line(view, line - view->line);
4680 report_clear();
4681 return REQ_NONE;
4683 } else {
4684 return pager_request(view, request, line);
4688 static bool
4689 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4691 char *sep = strchr(*text, c);
4693 if (sep != NULL) {
4694 *sep = 0;
4695 draw_text(view, *type, *text);
4696 *sep = c;
4697 *text = sep;
4698 *type = next_type;
4701 return sep != NULL;
4704 static bool
4705 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4707 char *text = line->data;
4708 enum line_type type = line->type;
4710 if (draw_lineno(view, lineno))
4711 return TRUE;
4713 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4714 return TRUE;
4716 if (type == LINE_DIFF_STAT) {
4717 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4718 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4719 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4720 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4721 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4722 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4723 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4725 } else {
4726 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4727 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4731 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4732 draw_commit_title(view, text, 4);
4733 else
4734 draw_text(view, type, text);
4735 return TRUE;
4738 static bool
4739 diff_read(struct view *view, char *data)
4741 struct diff_state *state = view->private;
4743 if (!data) {
4744 /* Fall back to retry if no diff will be shown. */
4745 if (view->lines == 0 && opt_file_argv) {
4746 int pos = argv_size(view->argv)
4747 - argv_size(opt_file_argv) - 1;
4749 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4750 for (; view->argv[pos]; pos++) {
4751 free((void *) view->argv[pos]);
4752 view->argv[pos] = NULL;
4755 if (view->pipe)
4756 io_done(view->pipe);
4757 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4758 return FALSE;
4761 return TRUE;
4764 return diff_common_read(view, data, state);
4767 static bool
4768 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4769 struct blame_header *header, struct blame_commit *commit)
4771 char line_arg[SIZEOF_STR];
4772 const char *blame_argv[] = {
4773 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4775 struct io io;
4776 bool ok = FALSE;
4777 char *buf;
4779 if (!string_format(line_arg, "-L%ld,+1", lineno))
4780 return FALSE;
4782 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4783 return FALSE;
4785 while ((buf = io_get(&io, '\n', TRUE))) {
4786 if (header) {
4787 if (!parse_blame_header(header, buf, 9999999))
4788 break;
4789 header = NULL;
4791 } else if (parse_blame_info(commit, buf)) {
4792 ok = TRUE;
4793 break;
4797 if (io_error(&io))
4798 ok = FALSE;
4800 io_done(&io);
4801 return ok;
4804 static unsigned int
4805 diff_get_lineno(struct view *view, struct line *line)
4807 const struct line *header, *chunk;
4808 const char *data;
4809 unsigned int lineno;
4811 /* Verify that we are after a diff header and one of its chunks */
4812 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4813 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4814 if (!header || !chunk || chunk < header)
4815 return 0;
4818 * In a chunk header, the number after the '+' sign is the number of its
4819 * following line, in the new version of the file. We increment this
4820 * number for each non-deletion line, until the given line position.
4822 data = strchr(chunk->data, '+');
4823 if (!data)
4824 return 0;
4826 lineno = atoi(data);
4827 chunk++;
4828 while (chunk++ < line)
4829 if (chunk->type != LINE_DIFF_DEL)
4830 lineno++;
4832 return lineno;
4835 static bool
4836 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4838 return prefixcmp(chunk, "@@ -") ||
4839 !(chunk = strchr(chunk, marker)) ||
4840 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4843 static enum request
4844 diff_trace_origin(struct view *view, struct line *line)
4846 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4847 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4848 const char *chunk_data;
4849 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4850 int lineno = 0;
4851 const char *file = NULL;
4852 char ref[SIZEOF_REF];
4853 struct blame_header header;
4854 struct blame_commit commit;
4856 if (!diff || !chunk || chunk == line) {
4857 report("The line to trace must be inside a diff chunk");
4858 return REQ_NONE;
4861 for (; diff < line && !file; diff++) {
4862 const char *data = diff->data;
4864 if (!prefixcmp(data, "--- a/")) {
4865 file = data + STRING_SIZE("--- a/");
4866 break;
4870 if (diff == line || !file) {
4871 report("Failed to read the file name");
4872 return REQ_NONE;
4875 chunk_data = chunk->data;
4877 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4878 report("Failed to read the line number");
4879 return REQ_NONE;
4882 if (lineno == 0) {
4883 report("This is the origin of the line");
4884 return REQ_NONE;
4887 for (chunk += 1; chunk < line; chunk++) {
4888 if (chunk->type == LINE_DIFF_ADD) {
4889 lineno += chunk_marker == '+';
4890 } else if (chunk->type == LINE_DIFF_DEL) {
4891 lineno += chunk_marker == '-';
4892 } else {
4893 lineno++;
4897 if (chunk_marker == '+')
4898 string_copy(ref, view->vid);
4899 else
4900 string_format(ref, "%s^", view->vid);
4902 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4903 report("Failed to read blame data");
4904 return REQ_NONE;
4907 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4908 string_copy(opt_ref, header.id);
4909 opt_goto_line = header.orig_lineno - 1;
4911 return REQ_VIEW_BLAME;
4914 static const char *
4915 diff_get_pathname(struct view *view, struct line *line)
4917 const struct line *header;
4918 const char *dst = NULL;
4919 const char *prefixes[] = { " b/", "cc ", "combined " };
4920 int i;
4922 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4923 if (!header)
4924 return NULL;
4926 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4927 dst = strstr(header->data, prefixes[i]);
4929 return dst ? dst + strlen(prefixes[--i]) : NULL;
4932 static enum request
4933 diff_common_edit(struct view *view, enum request request, struct line *line)
4935 const char *file = diff_get_pathname(view, line);
4936 char path[SIZEOF_STR];
4937 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
4939 if (has_path && access(path, R_OK)) {
4940 report("Failed to open file: %s", file);
4941 return REQ_NONE;
4944 open_editor(file, diff_get_lineno(view, line));
4945 return REQ_NONE;
4948 static enum request
4949 diff_request(struct view *view, enum request request, struct line *line)
4951 switch (request) {
4952 case REQ_VIEW_BLAME:
4953 return diff_trace_origin(view, line);
4955 case REQ_DIFF_CONTEXT_UP:
4956 case REQ_DIFF_CONTEXT_DOWN:
4957 if (!update_diff_context(request))
4958 return REQ_NONE;
4959 reload_view(view);
4960 return REQ_NONE;
4963 case REQ_EDIT:
4964 return diff_common_edit(view, request, line);
4966 case REQ_ENTER:
4967 return diff_common_enter(view, request, line);
4969 case REQ_REFRESH:
4970 reload_view(view);
4971 return REQ_NONE;
4973 default:
4974 return pager_request(view, request, line);
4978 static void
4979 diff_select(struct view *view, struct line *line)
4981 if (line->type == LINE_DIFF_STAT) {
4982 string_format(view->ref, "Press '%s' to jump to file diff",
4983 get_view_key(view, REQ_ENTER));
4984 } else {
4985 const char *file = diff_get_pathname(view, line);
4987 if (file) {
4988 string_format(view->ref, "Changes to '%s'", file);
4989 string_format(opt_file, "%s", file);
4990 ref_blob[0] = 0;
4991 } else {
4992 string_ncopy(view->ref, view->id, strlen(view->id));
4993 pager_select(view, line);
4998 static struct view_ops diff_ops = {
4999 "line",
5000 { "diff" },
5001 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5002 sizeof(struct diff_state),
5003 diff_open,
5004 diff_read,
5005 diff_common_draw,
5006 diff_request,
5007 pager_grep,
5008 diff_select,
5012 * Help backend
5015 static bool
5016 help_draw(struct view *view, struct line *line, unsigned int lineno)
5018 if (line->type == LINE_HELP_KEYMAP) {
5019 struct keymap *keymap = line->data;
5021 draw_formatted(view, line->type, "[%c] %s bindings",
5022 keymap->hidden ? '+' : '-', keymap->name);
5023 return TRUE;
5024 } else {
5025 return pager_draw(view, line, lineno);
5029 static bool
5030 help_open_keymap_title(struct view *view, struct keymap *keymap)
5032 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5033 return keymap->hidden;
5036 static void
5037 help_open_keymap(struct view *view, struct keymap *keymap)
5039 const char *group = NULL;
5040 char buf[SIZEOF_STR];
5041 bool add_title = TRUE;
5042 int i;
5044 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5045 const char *key = NULL;
5047 if (req_info[i].request == REQ_NONE)
5048 continue;
5050 if (!req_info[i].request) {
5051 group = req_info[i].help;
5052 continue;
5055 key = get_keys(keymap, req_info[i].request, TRUE);
5056 if (!key || !*key)
5057 continue;
5059 if (add_title && help_open_keymap_title(view, keymap))
5060 return;
5061 add_title = FALSE;
5063 if (group) {
5064 add_line_text(view, group, LINE_HELP_GROUP);
5065 group = NULL;
5068 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5069 enum_name(req_info[i]), req_info[i].help);
5072 group = "External commands:";
5074 for (i = 0; i < run_requests; i++) {
5075 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5076 const char *key;
5078 if (!req || req->keymap != keymap)
5079 continue;
5081 key = get_key_name(req->key);
5082 if (!*key)
5083 key = "(no key defined)";
5085 if (add_title && help_open_keymap_title(view, keymap))
5086 return;
5087 add_title = FALSE;
5089 if (group) {
5090 add_line_text(view, group, LINE_HELP_GROUP);
5091 group = NULL;
5094 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5095 return;
5097 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5101 static bool
5102 help_open(struct view *view, enum open_flags flags)
5104 struct keymap *keymap;
5106 reset_view(view);
5107 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5108 add_line_text(view, "", LINE_DEFAULT);
5110 for (keymap = keymaps; keymap; keymap = keymap->next)
5111 help_open_keymap(view, keymap);
5113 return TRUE;
5116 static enum request
5117 help_request(struct view *view, enum request request, struct line *line)
5119 switch (request) {
5120 case REQ_ENTER:
5121 if (line->type == LINE_HELP_KEYMAP) {
5122 struct keymap *keymap = line->data;
5124 keymap->hidden = !keymap->hidden;
5125 refresh_view(view);
5128 return REQ_NONE;
5129 default:
5130 return pager_request(view, request, line);
5134 static void
5135 help_done(struct view *view)
5137 int i;
5139 for (i = 0; i < view->lines; i++)
5140 if (view->line[i].type == LINE_HELP_KEYMAP)
5141 view->line[i].data = NULL;
5144 static struct view_ops help_ops = {
5145 "line",
5146 { "help" },
5147 VIEW_NO_GIT_DIR,
5149 help_open,
5150 NULL,
5151 help_draw,
5152 help_request,
5153 pager_grep,
5154 pager_select,
5155 help_done,
5160 * Tree backend
5163 struct tree_stack_entry {
5164 struct tree_stack_entry *prev; /* Entry below this in the stack */
5165 unsigned long lineno; /* Line number to restore */
5166 char *name; /* Position of name in opt_path */
5169 /* The top of the path stack. */
5170 static struct tree_stack_entry *tree_stack = NULL;
5171 unsigned long tree_lineno = 0;
5173 static void
5174 pop_tree_stack_entry(void)
5176 struct tree_stack_entry *entry = tree_stack;
5178 tree_lineno = entry->lineno;
5179 entry->name[0] = 0;
5180 tree_stack = entry->prev;
5181 free(entry);
5184 static void
5185 push_tree_stack_entry(const char *name, unsigned long lineno)
5187 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
5188 size_t pathlen = strlen(opt_path);
5190 if (!entry)
5191 return;
5193 entry->prev = tree_stack;
5194 entry->name = opt_path + pathlen;
5195 tree_stack = entry;
5197 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5198 pop_tree_stack_entry();
5199 return;
5202 /* Move the current line to the first tree entry. */
5203 tree_lineno = 1;
5204 entry->lineno = lineno;
5207 /* Parse output from git-ls-tree(1):
5209 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5212 #define SIZEOF_TREE_ATTR \
5213 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5215 #define SIZEOF_TREE_MODE \
5216 STRING_SIZE("100644 ")
5218 #define TREE_ID_OFFSET \
5219 STRING_SIZE("100644 blob ")
5221 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5223 struct tree_entry {
5224 char id[SIZEOF_REV];
5225 char commit[SIZEOF_REV];
5226 mode_t mode;
5227 struct time time; /* Date from the author ident. */
5228 const struct ident *author; /* Author of the commit. */
5229 unsigned long size;
5230 char name[1];
5233 struct tree_state {
5234 char commit[SIZEOF_REV];
5235 const struct ident *author;
5236 struct time author_time;
5237 int size_width;
5238 bool read_date;
5241 static const char *
5242 tree_path(const struct line *line)
5244 return ((struct tree_entry *) line->data)->name;
5247 static int
5248 tree_compare_entry(const struct line *line1, const struct line *line2)
5250 if (line1->type != line2->type)
5251 return line1->type == LINE_TREE_DIR ? -1 : 1;
5252 return strcmp(tree_path(line1), tree_path(line2));
5255 static const enum sort_field tree_sort_fields[] = {
5256 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5258 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5260 static int
5261 tree_compare(const void *l1, const void *l2)
5263 const struct line *line1 = (const struct line *) l1;
5264 const struct line *line2 = (const struct line *) l2;
5265 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5266 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5268 if (line1->type == LINE_TREE_HEAD)
5269 return -1;
5270 if (line2->type == LINE_TREE_HEAD)
5271 return 1;
5273 switch (get_sort_field(tree_sort_state)) {
5274 case ORDERBY_DATE:
5275 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5277 case ORDERBY_AUTHOR:
5278 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5280 case ORDERBY_NAME:
5281 default:
5282 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5287 static struct line *
5288 tree_entry(struct view *view, enum line_type type, const char *path,
5289 const char *mode, const char *id, unsigned long size)
5291 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5292 struct tree_entry *entry;
5293 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5295 if (!line)
5296 return NULL;
5298 strncpy(entry->name, path, strlen(path));
5299 if (mode)
5300 entry->mode = strtoul(mode, NULL, 8);
5301 if (id)
5302 string_copy_rev(entry->id, id);
5303 entry->size = size;
5305 return line;
5308 static bool
5309 tree_read_date(struct view *view, char *text, struct tree_state *state)
5311 if (!text && state->read_date) {
5312 state->read_date = FALSE;
5313 return TRUE;
5315 } else if (!text) {
5316 /* Find next entry to process */
5317 const char *log_file[] = {
5318 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
5319 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5322 if (!view->lines) {
5323 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5324 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5325 report("Tree is empty");
5326 return TRUE;
5329 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5330 report("Failed to load tree data");
5331 return TRUE;
5334 state->read_date = TRUE;
5335 return FALSE;
5337 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5338 string_copy_rev_from_commit_line(state->commit, text);
5340 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5341 parse_author_line(text + STRING_SIZE("author "),
5342 &state->author, &state->author_time);
5344 } else if (*text == ':') {
5345 char *pos;
5346 size_t annotated = 1;
5347 size_t i;
5349 pos = strchr(text, '\t');
5350 if (!pos)
5351 return TRUE;
5352 text = pos + 1;
5353 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5354 text += strlen(opt_path);
5355 pos = strchr(text, '/');
5356 if (pos)
5357 *pos = 0;
5359 for (i = 1; i < view->lines; i++) {
5360 struct line *line = &view->line[i];
5361 struct tree_entry *entry = line->data;
5363 annotated += !!entry->author;
5364 if (entry->author || strcmp(entry->name, text))
5365 continue;
5367 string_copy_rev(entry->commit, state->commit);
5368 entry->author = state->author;
5369 entry->time = state->author_time;
5370 line->dirty = 1;
5371 break;
5374 if (annotated == view->lines)
5375 io_kill(view->pipe);
5377 return TRUE;
5380 static inline size_t
5381 parse_size(const char *text, int *max_digits)
5383 size_t size = 0;
5384 int digits = 0;
5386 while (*text == ' ')
5387 text++;
5389 while (isdigit(*text)) {
5390 size = (size * 10) + (*text++ - '0');
5391 digits++;
5394 if (digits > *max_digits)
5395 *max_digits = digits;
5397 return size;
5400 static bool
5401 tree_read(struct view *view, char *text)
5403 struct tree_state *state = view->private;
5404 struct tree_entry *data;
5405 struct line *entry, *line;
5406 enum line_type type;
5407 size_t textlen = text ? strlen(text) : 0;
5408 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5409 char *path;
5410 size_t size;
5412 if (state->read_date || !text)
5413 return tree_read_date(view, text, state);
5415 if (textlen <= SIZEOF_TREE_ATTR)
5416 return FALSE;
5417 if (view->lines == 0 &&
5418 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5419 return FALSE;
5421 size = parse_size(attr_offset, &state->size_width);
5422 path = strchr(attr_offset, '\t');
5423 if (!path)
5424 return FALSE;
5425 path++;
5427 /* Strip the path part ... */
5428 if (*opt_path) {
5429 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5430 size_t striplen = strlen(opt_path);
5432 if (pathlen > striplen)
5433 memmove(path, path + striplen,
5434 pathlen - striplen + 1);
5436 /* Insert "link" to parent directory. */
5437 if (view->lines == 1 &&
5438 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5439 return FALSE;
5442 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5443 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5444 if (!entry)
5445 return FALSE;
5446 data = entry->data;
5448 /* Skip "Directory ..." and ".." line. */
5449 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5450 if (tree_compare_entry(line, entry) <= 0)
5451 continue;
5453 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5455 line->data = data;
5456 line->type = type;
5457 for (; line <= entry; line++)
5458 line->dirty = line->cleareol = 1;
5459 return TRUE;
5462 if (tree_lineno <= view->pos.lineno)
5463 tree_lineno = view->custom_lines;
5465 if (tree_lineno > view->pos.lineno) {
5466 view->pos.lineno = tree_lineno;
5467 tree_lineno = 0;
5470 return TRUE;
5473 static bool
5474 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5476 struct tree_state *state = view->private;
5477 struct tree_entry *entry = line->data;
5479 if (line->type == LINE_TREE_HEAD) {
5480 if (draw_text(view, line->type, "Directory path /"))
5481 return TRUE;
5482 } else {
5483 if (draw_mode(view, entry->mode))
5484 return TRUE;
5486 if (draw_author(view, entry->author))
5487 return TRUE;
5489 if (draw_file_size(view, entry->size, state->size_width,
5490 line->type != LINE_TREE_FILE))
5491 return TRUE;
5493 if (draw_date(view, &entry->time))
5494 return TRUE;
5496 if (draw_id(view, entry->commit))
5497 return TRUE;
5500 draw_text(view, line->type, entry->name);
5501 return TRUE;
5504 static void
5505 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5507 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5508 char file[SIZEOF_STR];
5509 int fd;
5511 if (!name)
5512 name = "unknown";
5514 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5515 report("Temporary file name is too long");
5516 return;
5519 fd = mkstemps(file, strlen(name) + 1);
5521 if (fd == -1)
5522 report("Failed to create temporary file");
5523 else if (!io_run_append(blob_argv, fd))
5524 report("Failed to save blob data to file");
5525 else
5526 open_editor(file, lineno);
5527 if (fd != -1)
5528 unlink(file);
5531 static enum request
5532 tree_request(struct view *view, enum request request, struct line *line)
5534 enum open_flags flags;
5535 struct tree_entry *entry = line->data;
5537 switch (request) {
5538 case REQ_VIEW_BLAME:
5539 if (line->type != LINE_TREE_FILE) {
5540 report("Blame only supported for files");
5541 return REQ_NONE;
5544 string_copy(opt_ref, view->vid);
5545 return request;
5547 case REQ_EDIT:
5548 if (line->type != LINE_TREE_FILE) {
5549 report("Edit only supported for files");
5550 } else if (!is_head_commit(view->vid)) {
5551 open_blob_editor(entry->id, entry->name, 0);
5552 } else {
5553 open_editor(opt_file, 0);
5555 return REQ_NONE;
5557 case REQ_TOGGLE_SORT_FIELD:
5558 case REQ_TOGGLE_SORT_ORDER:
5559 sort_view(view, request, &tree_sort_state, tree_compare);
5560 return REQ_NONE;
5562 case REQ_PARENT:
5563 if (!*opt_path) {
5564 /* quit view if at top of tree */
5565 return REQ_VIEW_CLOSE;
5567 /* fake 'cd ..' */
5568 line = &view->line[1];
5569 break;
5571 case REQ_ENTER:
5572 break;
5574 default:
5575 return request;
5578 /* Cleanup the stack if the tree view is at a different tree. */
5579 while (!*opt_path && tree_stack)
5580 pop_tree_stack_entry();
5582 switch (line->type) {
5583 case LINE_TREE_DIR:
5584 /* Depending on whether it is a subdirectory or parent link
5585 * mangle the path buffer. */
5586 if (line == &view->line[1] && *opt_path) {
5587 pop_tree_stack_entry();
5589 } else {
5590 const char *basename = tree_path(line);
5592 push_tree_stack_entry(basename, view->pos.lineno);
5595 /* Trees and subtrees share the same ID, so they are not not
5596 * unique like blobs. */
5597 flags = OPEN_RELOAD;
5598 request = REQ_VIEW_TREE;
5599 break;
5601 case LINE_TREE_FILE:
5602 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5603 request = REQ_VIEW_BLOB;
5604 break;
5606 default:
5607 return REQ_NONE;
5610 open_view(view, request, flags);
5611 if (request == REQ_VIEW_TREE)
5612 view->pos.lineno = tree_lineno;
5614 return REQ_NONE;
5617 static bool
5618 tree_grep(struct view *view, struct line *line)
5620 struct tree_entry *entry = line->data;
5621 const char *text[] = {
5622 entry->name,
5623 mkauthor(entry->author, opt_author_width, opt_author),
5624 mkdate(&entry->time, opt_date),
5625 NULL
5628 return grep_text(view, text);
5631 static void
5632 tree_select(struct view *view, struct line *line)
5634 struct tree_entry *entry = line->data;
5636 if (line->type == LINE_TREE_HEAD) {
5637 string_format(view->ref, "Files in /%s", opt_path);
5638 return;
5641 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5642 string_copy(view->ref, "Open parent directory");
5643 ref_blob[0] = 0;
5644 return;
5647 if (line->type == LINE_TREE_FILE) {
5648 string_copy_rev(ref_blob, entry->id);
5649 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5652 string_copy_rev(view->ref, entry->id);
5655 static bool
5656 tree_open(struct view *view, enum open_flags flags)
5658 static const char *tree_argv[] = {
5659 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5662 if (string_rev_is_null(ref_commit)) {
5663 report("No tree exists for this commit");
5664 return FALSE;
5667 if (view->lines == 0 && opt_prefix[0]) {
5668 char *pos = opt_prefix;
5670 while (pos && *pos) {
5671 char *end = strchr(pos, '/');
5673 if (end)
5674 *end = 0;
5675 push_tree_stack_entry(pos, 0);
5676 pos = end;
5677 if (end) {
5678 *end = '/';
5679 pos++;
5683 } else if (strcmp(view->vid, view->id)) {
5684 opt_path[0] = 0;
5687 return begin_update(view, opt_cdup, tree_argv, flags);
5690 static struct view_ops tree_ops = {
5691 "file",
5692 { "tree" },
5693 VIEW_SEND_CHILD_ENTER,
5694 sizeof(struct tree_state),
5695 tree_open,
5696 tree_read,
5697 tree_draw,
5698 tree_request,
5699 tree_grep,
5700 tree_select,
5703 static bool
5704 blob_open(struct view *view, enum open_flags flags)
5706 static const char *blob_argv[] = {
5707 "git", "cat-file", "blob", "%(blob)", NULL
5710 if (!ref_blob[0] && opt_file[0]) {
5711 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5712 char blob_spec[SIZEOF_STR];
5713 const char *rev_parse_argv[] = {
5714 "git", "rev-parse", blob_spec, NULL
5717 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5718 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5719 report("Failed to resolve blob from file name");
5720 return FALSE;
5724 if (!ref_blob[0]) {
5725 report("No file chosen, press %s to open tree view",
5726 get_view_key(view, REQ_VIEW_TREE));
5727 return FALSE;
5730 view->encoding = get_path_encoding(opt_file, opt_encoding);
5732 return begin_update(view, NULL, blob_argv, flags);
5735 static bool
5736 blob_read(struct view *view, char *line)
5738 if (!line)
5739 return TRUE;
5740 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5743 static enum request
5744 blob_request(struct view *view, enum request request, struct line *line)
5746 switch (request) {
5747 case REQ_EDIT:
5748 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5749 return REQ_NONE;
5750 default:
5751 return pager_request(view, request, line);
5755 static struct view_ops blob_ops = {
5756 "line",
5757 { "blob" },
5758 VIEW_NO_FLAGS,
5760 blob_open,
5761 blob_read,
5762 pager_draw,
5763 blob_request,
5764 pager_grep,
5765 pager_select,
5769 * Blame backend
5771 * Loading the blame view is a two phase job:
5773 * 1. File content is read either using opt_file from the
5774 * filesystem or using git-cat-file.
5775 * 2. Then blame information is incrementally added by
5776 * reading output from git-blame.
5779 struct blame {
5780 struct blame_commit *commit;
5781 unsigned long lineno;
5782 char text[1];
5785 struct blame_state {
5786 struct blame_commit *commit;
5787 int blamed;
5788 bool done_reading;
5789 bool auto_filename_display;
5792 static bool
5793 blame_detect_filename_display(struct view *view)
5795 bool show_filenames = FALSE;
5796 const char *filename = NULL;
5797 int i;
5799 if (opt_blame_argv) {
5800 for (i = 0; opt_blame_argv[i]; i++) {
5801 if (prefixcmp(opt_blame_argv[i], "-C"))
5802 continue;
5804 show_filenames = TRUE;
5808 for (i = 0; i < view->lines; i++) {
5809 struct blame *blame = view->line[i].data;
5811 if (blame->commit && blame->commit->id[0]) {
5812 if (!filename)
5813 filename = blame->commit->filename;
5814 else if (strcmp(filename, blame->commit->filename))
5815 show_filenames = TRUE;
5819 return show_filenames;
5822 static bool
5823 blame_open(struct view *view, enum open_flags flags)
5825 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5826 char path[SIZEOF_STR];
5827 size_t i;
5829 if (!opt_file[0]) {
5830 report("No file chosen, press %s to open tree view",
5831 get_view_key(view, REQ_VIEW_TREE));
5832 return FALSE;
5835 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5836 string_copy(path, opt_file);
5837 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5838 report("Failed to setup the blame view");
5839 return FALSE;
5843 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5844 const char *blame_cat_file_argv[] = {
5845 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5848 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5849 return FALSE;
5852 /* First pass: remove multiple references to the same commit. */
5853 for (i = 0; i < view->lines; i++) {
5854 struct blame *blame = view->line[i].data;
5856 if (blame->commit && blame->commit->id[0])
5857 blame->commit->id[0] = 0;
5858 else
5859 blame->commit = NULL;
5862 /* Second pass: free existing references. */
5863 for (i = 0; i < view->lines; i++) {
5864 struct blame *blame = view->line[i].data;
5866 if (blame->commit)
5867 free(blame->commit);
5870 string_format(view->vid, "%s", opt_file);
5871 string_format(view->ref, "%s ...", opt_file);
5873 return TRUE;
5876 static struct blame_commit *
5877 get_blame_commit(struct view *view, const char *id)
5879 size_t i;
5881 for (i = 0; i < view->lines; i++) {
5882 struct blame *blame = view->line[i].data;
5884 if (!blame->commit)
5885 continue;
5887 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5888 return blame->commit;
5892 struct blame_commit *commit = calloc(1, sizeof(*commit));
5894 if (commit)
5895 string_ncopy(commit->id, id, SIZEOF_REV);
5896 return commit;
5900 static struct blame_commit *
5901 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5903 struct blame_header header;
5904 struct blame_commit *commit;
5905 struct blame *blame;
5907 if (!parse_blame_header(&header, text, view->lines))
5908 return NULL;
5910 commit = get_blame_commit(view, text);
5911 if (!commit)
5912 return NULL;
5914 state->blamed += header.group;
5915 while (header.group--) {
5916 struct line *line = &view->line[header.lineno + header.group - 1];
5918 blame = line->data;
5919 blame->commit = commit;
5920 blame->lineno = header.orig_lineno + header.group - 1;
5921 line->dirty = 1;
5924 return commit;
5927 static bool
5928 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5930 if (!text) {
5931 const char *blame_argv[] = {
5932 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5933 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5936 if (view->lines == 0 && !view->prev)
5937 die("No blame exist for %s", view->vid);
5939 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5940 report("Failed to load blame data");
5941 return TRUE;
5944 if (opt_goto_line > 0) {
5945 select_view_line(view, opt_goto_line);
5946 opt_goto_line = 0;
5949 state->done_reading = TRUE;
5950 return FALSE;
5952 } else {
5953 size_t textlen = strlen(text);
5954 struct blame *blame;
5956 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5957 return FALSE;
5959 blame->commit = NULL;
5960 strncpy(blame->text, text, textlen);
5961 blame->text[textlen] = 0;
5962 return TRUE;
5966 static bool
5967 blame_read(struct view *view, char *line)
5969 struct blame_state *state = view->private;
5971 if (!state->done_reading)
5972 return blame_read_file(view, line, state);
5974 if (!line) {
5975 state->auto_filename_display = blame_detect_filename_display(view);
5976 string_format(view->ref, "%s", view->vid);
5977 if (view_is_displayed(view)) {
5978 update_view_title(view);
5979 redraw_view_from(view, 0);
5981 return TRUE;
5984 if (!state->commit) {
5985 state->commit = read_blame_commit(view, line, state);
5986 string_format(view->ref, "%s %2zd%%", view->vid,
5987 view->lines ? state->blamed * 100 / view->lines : 0);
5989 } else if (parse_blame_info(state->commit, line)) {
5990 state->commit = NULL;
5993 return TRUE;
5996 static bool
5997 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5999 struct blame_state *state = view->private;
6000 struct blame *blame = line->data;
6001 struct time *time = NULL;
6002 const char *id = NULL, *filename = NULL;
6003 const struct ident *author = NULL;
6004 enum line_type id_type = LINE_ID;
6005 static const enum line_type blame_colors[] = {
6006 LINE_PALETTE_0,
6007 LINE_PALETTE_1,
6008 LINE_PALETTE_2,
6009 LINE_PALETTE_3,
6010 LINE_PALETTE_4,
6011 LINE_PALETTE_5,
6012 LINE_PALETTE_6,
6015 #define BLAME_COLOR(i) \
6016 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6018 if (blame->commit && *blame->commit->filename) {
6019 id = blame->commit->id;
6020 author = blame->commit->author;
6021 filename = blame->commit->filename;
6022 time = &blame->commit->time;
6023 id_type = BLAME_COLOR((long) blame->commit);
6026 if (draw_date(view, time))
6027 return TRUE;
6029 if (draw_author(view, author))
6030 return TRUE;
6032 if (draw_filename(view, filename, state->auto_filename_display))
6033 return TRUE;
6035 if (draw_id_custom(view, id_type, id, opt_id_cols))
6036 return TRUE;
6038 if (draw_lineno(view, lineno))
6039 return TRUE;
6041 draw_text(view, LINE_DEFAULT, blame->text);
6042 return TRUE;
6045 static bool
6046 check_blame_commit(struct blame *blame, bool check_null_id)
6048 if (!blame->commit)
6049 report("Commit data not loaded yet");
6050 else if (check_null_id && string_rev_is_null(blame->commit->id))
6051 report("No commit exist for the selected line");
6052 else
6053 return TRUE;
6054 return FALSE;
6057 static void
6058 setup_blame_parent_line(struct view *view, struct blame *blame)
6060 char from[SIZEOF_REF + SIZEOF_STR];
6061 char to[SIZEOF_REF + SIZEOF_STR];
6062 const char *diff_tree_argv[] = {
6063 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
6064 "--no-color", "-U0", from, to, "--", NULL
6066 struct io io;
6067 int parent_lineno = -1;
6068 int blamed_lineno = -1;
6069 char *line;
6071 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6072 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6073 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6074 return;
6076 while ((line = io_get(&io, '\n', TRUE))) {
6077 if (*line == '@') {
6078 char *pos = strchr(line, '+');
6080 parent_lineno = atoi(line + 4);
6081 if (pos)
6082 blamed_lineno = atoi(pos + 1);
6084 } else if (*line == '+' && parent_lineno != -1) {
6085 if (blame->lineno == blamed_lineno - 1 &&
6086 !strcmp(blame->text, line + 1)) {
6087 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6088 break;
6090 blamed_lineno++;
6094 io_done(&io);
6097 static enum request
6098 blame_request(struct view *view, enum request request, struct line *line)
6100 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6101 struct blame *blame = line->data;
6103 switch (request) {
6104 case REQ_VIEW_BLAME:
6105 if (check_blame_commit(blame, TRUE)) {
6106 string_copy(opt_ref, blame->commit->id);
6107 string_copy(opt_file, blame->commit->filename);
6108 if (blame->lineno)
6109 view->pos.lineno = blame->lineno;
6110 reload_view(view);
6112 break;
6114 case REQ_PARENT:
6115 if (!check_blame_commit(blame, TRUE))
6116 break;
6117 if (!*blame->commit->parent_id) {
6118 report("The selected commit has no parents");
6119 } else {
6120 string_copy_rev(opt_ref, blame->commit->parent_id);
6121 string_copy(opt_file, blame->commit->parent_filename);
6122 setup_blame_parent_line(view, blame);
6123 opt_goto_line = blame->lineno;
6124 reload_view(view);
6126 break;
6128 case REQ_ENTER:
6129 if (!check_blame_commit(blame, FALSE))
6130 break;
6132 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6133 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6134 break;
6136 if (string_rev_is_null(blame->commit->id)) {
6137 struct view *diff = VIEW(REQ_VIEW_DIFF);
6138 const char *diff_parent_argv[] = {
6139 GIT_DIFF_BLAME(opt_encoding_arg,
6140 opt_diff_context_arg,
6141 opt_ignore_space_arg, view->vid)
6143 const char *diff_no_parent_argv[] = {
6144 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
6145 opt_diff_context_arg,
6146 opt_ignore_space_arg, view->vid)
6148 const char **diff_index_argv = *blame->commit->parent_id
6149 ? diff_parent_argv : diff_no_parent_argv;
6151 open_argv(view, diff, diff_index_argv, NULL, flags);
6152 if (diff->pipe)
6153 string_copy_rev(diff->ref, NULL_ID);
6154 } else {
6155 open_view(view, REQ_VIEW_DIFF, flags);
6157 break;
6159 default:
6160 return request;
6163 return REQ_NONE;
6166 static bool
6167 blame_grep(struct view *view, struct line *line)
6169 struct blame *blame = line->data;
6170 struct blame_commit *commit = blame->commit;
6171 const char *text[] = {
6172 blame->text,
6173 commit ? commit->title : "",
6174 commit ? commit->id : "",
6175 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6176 commit ? mkdate(&commit->time, opt_date) : "",
6177 NULL
6180 return grep_text(view, text);
6183 static void
6184 blame_select(struct view *view, struct line *line)
6186 struct blame *blame = line->data;
6187 struct blame_commit *commit = blame->commit;
6189 if (!commit)
6190 return;
6192 if (string_rev_is_null(commit->id))
6193 string_ncopy(ref_commit, "HEAD", 4);
6194 else
6195 string_copy_rev(ref_commit, commit->id);
6198 static struct view_ops blame_ops = {
6199 "line",
6200 { "blame" },
6201 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6202 sizeof(struct blame_state),
6203 blame_open,
6204 blame_read,
6205 blame_draw,
6206 blame_request,
6207 blame_grep,
6208 blame_select,
6212 * Branch backend
6215 struct branch {
6216 const struct ident *author; /* Author of the last commit. */
6217 struct time time; /* Date of the last activity. */
6218 char title[128]; /* First line of the commit message. */
6219 const struct ref *ref; /* Name and commit ID information. */
6222 static const struct ref branch_all;
6223 #define BRANCH_ALL_NAME "All branches"
6224 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6226 static const enum sort_field branch_sort_fields[] = {
6227 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6229 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6231 struct branch_state {
6232 char id[SIZEOF_REV];
6233 size_t max_ref_length;
6236 static int
6237 branch_compare(const void *l1, const void *l2)
6239 const struct branch *branch1 = ((const struct line *) l1)->data;
6240 const struct branch *branch2 = ((const struct line *) l2)->data;
6242 if (branch_is_all(branch1))
6243 return -1;
6244 else if (branch_is_all(branch2))
6245 return 1;
6247 switch (get_sort_field(branch_sort_state)) {
6248 case ORDERBY_DATE:
6249 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6251 case ORDERBY_AUTHOR:
6252 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6254 case ORDERBY_NAME:
6255 default:
6256 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6260 static bool
6261 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6263 struct branch_state *state = view->private;
6264 struct branch *branch = line->data;
6265 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6266 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6268 if (draw_lineno(view, lineno))
6269 return TRUE;
6271 if (draw_date(view, &branch->time))
6272 return TRUE;
6274 if (draw_author(view, branch->author))
6275 return TRUE;
6277 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6278 return TRUE;
6280 if (draw_id(view, branch->ref->id))
6281 return TRUE;
6283 draw_text(view, LINE_DEFAULT, branch->title);
6284 return TRUE;
6287 static enum request
6288 branch_request(struct view *view, enum request request, struct line *line)
6290 struct branch *branch = line->data;
6292 switch (request) {
6293 case REQ_REFRESH:
6294 load_refs(TRUE);
6295 refresh_view(view);
6296 return REQ_NONE;
6298 case REQ_TOGGLE_SORT_FIELD:
6299 case REQ_TOGGLE_SORT_ORDER:
6300 sort_view(view, request, &branch_sort_state, branch_compare);
6301 return REQ_NONE;
6303 case REQ_ENTER:
6305 const struct ref *ref = branch->ref;
6306 const char *all_branches_argv[] = {
6307 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6309 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6311 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6312 return REQ_NONE;
6314 case REQ_JUMP_COMMIT:
6316 int lineno;
6318 for (lineno = 0; lineno < view->lines; lineno++) {
6319 struct branch *branch = view->line[lineno].data;
6321 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6322 select_view_line(view, lineno);
6323 report_clear();
6324 return REQ_NONE;
6328 default:
6329 return request;
6333 static bool
6334 branch_read(struct view *view, char *line)
6336 struct branch_state *state = view->private;
6337 const char *title = NULL;
6338 const struct ident *author = NULL;
6339 struct time time = {};
6340 size_t i;
6342 if (!line)
6343 return TRUE;
6345 switch (get_line_type(line)) {
6346 case LINE_COMMIT:
6347 string_copy_rev_from_commit_line(state->id, line);
6348 return TRUE;
6350 case LINE_AUTHOR:
6351 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6352 break;
6354 default:
6355 title = line + STRING_SIZE("title ");
6358 for (i = 0; i < view->lines; i++) {
6359 struct branch *branch = view->line[i].data;
6361 if (strcmp(branch->ref->id, state->id))
6362 continue;
6364 if (author) {
6365 branch->author = author;
6366 branch->time = time;
6369 if (title)
6370 string_expand(branch->title, sizeof(branch->title), title, 1);
6372 view->line[i].dirty = TRUE;
6375 return TRUE;
6378 static bool
6379 branch_open_visitor(void *data, const struct ref *ref)
6381 struct view *view = data;
6382 struct branch_state *state = view->private;
6383 struct branch *branch;
6384 bool is_all = ref == &branch_all;
6385 size_t ref_length;
6387 if (ref->tag || ref->ltag)
6388 return TRUE;
6390 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6391 return FALSE;
6393 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6394 if (ref_length > state->max_ref_length)
6395 state->max_ref_length = ref_length;
6397 branch->ref = ref;
6398 return TRUE;
6401 static bool
6402 branch_open(struct view *view, enum open_flags flags)
6404 const char *branch_log[] = {
6405 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
6406 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6407 "--all", "--simplify-by-decoration", NULL
6410 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6411 report("Failed to load branch data");
6412 return FALSE;
6415 branch_open_visitor(view, &branch_all);
6416 foreach_ref(branch_open_visitor, view);
6418 return TRUE;
6421 static bool
6422 branch_grep(struct view *view, struct line *line)
6424 struct branch *branch = line->data;
6425 const char *text[] = {
6426 branch->ref->name,
6427 mkauthor(branch->author, opt_author_width, opt_author),
6428 NULL
6431 return grep_text(view, text);
6434 static void
6435 branch_select(struct view *view, struct line *line)
6437 struct branch *branch = line->data;
6439 if (branch_is_all(branch)) {
6440 string_copy(view->ref, BRANCH_ALL_NAME);
6441 return;
6443 string_copy_rev(view->ref, branch->ref->id);
6444 string_copy_rev(ref_commit, branch->ref->id);
6445 string_copy_rev(ref_head, branch->ref->id);
6446 string_copy_rev(ref_branch, branch->ref->name);
6449 static struct view_ops branch_ops = {
6450 "branch",
6451 { "branch" },
6452 VIEW_NO_FLAGS,
6453 sizeof(struct branch_state),
6454 branch_open,
6455 branch_read,
6456 branch_draw,
6457 branch_request,
6458 branch_grep,
6459 branch_select,
6463 * Status backend
6466 struct status {
6467 char status;
6468 struct {
6469 mode_t mode;
6470 char rev[SIZEOF_REV];
6471 char name[SIZEOF_STR];
6472 } old;
6473 struct {
6474 mode_t mode;
6475 char rev[SIZEOF_REV];
6476 char name[SIZEOF_STR];
6477 } new;
6480 static char status_onbranch[SIZEOF_STR];
6481 static struct status stage_status;
6482 static enum line_type stage_line_type;
6484 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6486 /* This should work even for the "On branch" line. */
6487 static inline bool
6488 status_has_none(struct view *view, struct line *line)
6490 return view_has_line(view, line) && !line[1].data;
6493 /* Get fields from the diff line:
6494 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6496 static inline bool
6497 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6499 const char *old_mode = buf + 1;
6500 const char *new_mode = buf + 8;
6501 const char *old_rev = buf + 15;
6502 const char *new_rev = buf + 56;
6503 const char *status = buf + 97;
6505 if (bufsize < 98 ||
6506 old_mode[-1] != ':' ||
6507 new_mode[-1] != ' ' ||
6508 old_rev[-1] != ' ' ||
6509 new_rev[-1] != ' ' ||
6510 status[-1] != ' ')
6511 return FALSE;
6513 file->status = *status;
6515 string_copy_rev(file->old.rev, old_rev);
6516 string_copy_rev(file->new.rev, new_rev);
6518 file->old.mode = strtoul(old_mode, NULL, 8);
6519 file->new.mode = strtoul(new_mode, NULL, 8);
6521 file->old.name[0] = file->new.name[0] = 0;
6523 return TRUE;
6526 static bool
6527 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6529 struct status *unmerged = NULL;
6530 char *buf;
6531 struct io io;
6533 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6534 return FALSE;
6536 add_line_nodata(view, type);
6538 while ((buf = io_get(&io, 0, TRUE))) {
6539 struct status *file = unmerged;
6541 if (!file) {
6542 if (!add_line_alloc(view, &file, type, 0, FALSE))
6543 goto error_out;
6546 /* Parse diff info part. */
6547 if (status) {
6548 file->status = status;
6549 if (status == 'A')
6550 string_copy(file->old.rev, NULL_ID);
6552 } else if (!file->status || file == unmerged) {
6553 if (!status_get_diff(file, buf, strlen(buf)))
6554 goto error_out;
6556 buf = io_get(&io, 0, TRUE);
6557 if (!buf)
6558 break;
6560 /* Collapse all modified entries that follow an
6561 * associated unmerged entry. */
6562 if (unmerged == file) {
6563 unmerged->status = 'U';
6564 unmerged = NULL;
6565 } else if (file->status == 'U') {
6566 unmerged = file;
6570 /* Grab the old name for rename/copy. */
6571 if (!*file->old.name &&
6572 (file->status == 'R' || file->status == 'C')) {
6573 string_ncopy(file->old.name, buf, strlen(buf));
6575 buf = io_get(&io, 0, TRUE);
6576 if (!buf)
6577 break;
6580 /* git-ls-files just delivers a NUL separated list of
6581 * file names similar to the second half of the
6582 * git-diff-* output. */
6583 string_ncopy(file->new.name, buf, strlen(buf));
6584 if (!*file->old.name)
6585 string_copy(file->old.name, file->new.name);
6586 file = NULL;
6589 if (io_error(&io)) {
6590 error_out:
6591 io_done(&io);
6592 return FALSE;
6595 if (!view->line[view->lines - 1].data)
6596 add_line_nodata(view, LINE_STAT_NONE);
6598 io_done(&io);
6599 return TRUE;
6602 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6603 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6605 static const char *status_list_other_argv[] = {
6606 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6609 static const char *status_list_no_head_argv[] = {
6610 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6613 static const char *update_index_argv[] = {
6614 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6617 /* Restore the previous line number to stay in the context or select a
6618 * line with something that can be updated. */
6619 static void
6620 status_restore(struct view *view)
6622 if (!check_position(&view->prev_pos))
6623 return;
6625 if (view->prev_pos.lineno >= view->lines)
6626 view->prev_pos.lineno = view->lines - 1;
6627 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6628 view->prev_pos.lineno++;
6629 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6630 view->prev_pos.lineno--;
6632 /* If the above fails, always skip the "On branch" line. */
6633 if (view->prev_pos.lineno < view->lines)
6634 view->pos.lineno = view->prev_pos.lineno;
6635 else
6636 view->pos.lineno = 1;
6638 if (view->prev_pos.offset > view->pos.lineno)
6639 view->pos.offset = view->pos.lineno;
6640 else if (view->prev_pos.offset < view->lines)
6641 view->pos.offset = view->prev_pos.offset;
6643 clear_position(&view->prev_pos);
6646 static void
6647 status_update_onbranch(void)
6649 static const char *paths[][2] = {
6650 { "rebase-apply/rebasing", "Rebasing" },
6651 { "rebase-apply/applying", "Applying mailbox" },
6652 { "rebase-apply/", "Rebasing mailbox" },
6653 { "rebase-merge/interactive", "Interactive rebase" },
6654 { "rebase-merge/", "Rebase merge" },
6655 { "MERGE_HEAD", "Merging" },
6656 { "BISECT_LOG", "Bisecting" },
6657 { "HEAD", "On branch" },
6659 char buf[SIZEOF_STR];
6660 struct stat stat;
6661 int i;
6663 if (is_initial_commit()) {
6664 string_copy(status_onbranch, "Initial commit");
6665 return;
6668 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6669 char *head = opt_head;
6671 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6672 lstat(buf, &stat) < 0)
6673 continue;
6675 if (!*opt_head) {
6676 struct io io;
6678 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6679 io_read_buf(&io, buf, sizeof(buf))) {
6680 head = buf;
6681 if (!prefixcmp(head, "refs/heads/"))
6682 head += STRING_SIZE("refs/heads/");
6686 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6687 string_copy(status_onbranch, opt_head);
6688 return;
6691 string_copy(status_onbranch, "Not currently on any branch");
6694 /* First parse staged info using git-diff-index(1), then parse unstaged
6695 * info using git-diff-files(1), and finally untracked files using
6696 * git-ls-files(1). */
6697 static bool
6698 status_open(struct view *view, enum open_flags flags)
6700 const char **staged_argv = is_initial_commit() ?
6701 status_list_no_head_argv : status_diff_index_argv;
6702 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6704 if (opt_is_inside_work_tree == FALSE) {
6705 report("The status view requires a working tree");
6706 return FALSE;
6709 reset_view(view);
6711 add_line_nodata(view, LINE_STAT_HEAD);
6712 status_update_onbranch();
6714 io_run_bg(update_index_argv);
6716 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6717 opt_untracked_dirs_content ? NULL : "--directory";
6719 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6720 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6721 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6722 report("Failed to load status data");
6723 return FALSE;
6726 /* Restore the exact position or use the specialized restore
6727 * mode? */
6728 status_restore(view);
6729 return TRUE;
6732 static bool
6733 status_draw(struct view *view, struct line *line, unsigned int lineno)
6735 struct status *status = line->data;
6736 enum line_type type;
6737 const char *text;
6739 if (!status) {
6740 switch (line->type) {
6741 case LINE_STAT_STAGED:
6742 type = LINE_STAT_SECTION;
6743 text = "Changes to be committed:";
6744 break;
6746 case LINE_STAT_UNSTAGED:
6747 type = LINE_STAT_SECTION;
6748 text = "Changed but not updated:";
6749 break;
6751 case LINE_STAT_UNTRACKED:
6752 type = LINE_STAT_SECTION;
6753 text = "Untracked files:";
6754 break;
6756 case LINE_STAT_NONE:
6757 type = LINE_DEFAULT;
6758 text = " (no files)";
6759 break;
6761 case LINE_STAT_HEAD:
6762 type = LINE_STAT_HEAD;
6763 text = status_onbranch;
6764 break;
6766 default:
6767 return FALSE;
6769 } else {
6770 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6772 buf[0] = status->status;
6773 if (draw_text(view, line->type, buf))
6774 return TRUE;
6775 type = LINE_DEFAULT;
6776 text = status->new.name;
6779 draw_text(view, type, text);
6780 return TRUE;
6783 static enum request
6784 status_enter(struct view *view, struct line *line)
6786 struct status *status = line->data;
6787 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6789 if (line->type == LINE_STAT_NONE ||
6790 (!status && line[1].type == LINE_STAT_NONE)) {
6791 report("No file to diff");
6792 return REQ_NONE;
6795 switch (line->type) {
6796 case LINE_STAT_STAGED:
6797 case LINE_STAT_UNSTAGED:
6798 break;
6800 case LINE_STAT_UNTRACKED:
6801 if (!status) {
6802 report("No file to show");
6803 return REQ_NONE;
6806 if (!suffixcmp(status->new.name, -1, "/")) {
6807 report("Cannot display a directory");
6808 return REQ_NONE;
6810 break;
6812 case LINE_STAT_HEAD:
6813 return REQ_NONE;
6815 default:
6816 die("line type %d not handled in switch", line->type);
6819 if (status) {
6820 stage_status = *status;
6821 } else {
6822 memset(&stage_status, 0, sizeof(stage_status));
6825 stage_line_type = line->type;
6827 open_view(view, REQ_VIEW_STAGE, flags);
6828 return REQ_NONE;
6831 static bool
6832 status_exists(struct view *view, struct status *status, enum line_type type)
6834 unsigned long lineno;
6836 for (lineno = 0; lineno < view->lines; lineno++) {
6837 struct line *line = &view->line[lineno];
6838 struct status *pos = line->data;
6840 if (line->type != type)
6841 continue;
6842 if (!pos && (!status || !status->status) && line[1].data) {
6843 select_view_line(view, lineno);
6844 return TRUE;
6846 if (pos && !strcmp(status->new.name, pos->new.name)) {
6847 select_view_line(view, lineno);
6848 return TRUE;
6852 return FALSE;
6856 static bool
6857 status_update_prepare(struct io *io, enum line_type type)
6859 const char *staged_argv[] = {
6860 "git", "update-index", "-z", "--index-info", NULL
6862 const char *others_argv[] = {
6863 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6866 switch (type) {
6867 case LINE_STAT_STAGED:
6868 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6870 case LINE_STAT_UNSTAGED:
6871 case LINE_STAT_UNTRACKED:
6872 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6874 default:
6875 die("line type %d not handled in switch", type);
6876 return FALSE;
6880 static bool
6881 status_update_write(struct io *io, struct status *status, enum line_type type)
6883 switch (type) {
6884 case LINE_STAT_STAGED:
6885 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6886 status->old.rev, status->old.name, 0);
6888 case LINE_STAT_UNSTAGED:
6889 case LINE_STAT_UNTRACKED:
6890 return io_printf(io, "%s%c", status->new.name, 0);
6892 default:
6893 die("line type %d not handled in switch", type);
6894 return FALSE;
6898 static bool
6899 status_update_file(struct status *status, enum line_type type)
6901 struct io io;
6902 bool result;
6904 if (!status_update_prepare(&io, type))
6905 return FALSE;
6907 result = status_update_write(&io, status, type);
6908 return io_done(&io) && result;
6911 static bool
6912 status_update_files(struct view *view, struct line *line)
6914 char buf[sizeof(view->ref)];
6915 struct io io;
6916 bool result = TRUE;
6917 struct line *pos;
6918 int files = 0;
6919 int file, done;
6920 int cursor_y = -1, cursor_x = -1;
6922 if (!status_update_prepare(&io, line->type))
6923 return FALSE;
6925 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6926 files++;
6928 string_copy(buf, view->ref);
6929 getsyx(cursor_y, cursor_x);
6930 for (file = 0, done = 5; result && file < files; line++, file++) {
6931 int almost_done = file * 100 / files;
6933 if (almost_done > done) {
6934 done = almost_done;
6935 string_format(view->ref, "updating file %u of %u (%d%% done)",
6936 file, files, done);
6937 update_view_title(view);
6938 setsyx(cursor_y, cursor_x);
6939 doupdate();
6941 result = status_update_write(&io, line->data, line->type);
6943 string_copy(view->ref, buf);
6945 return io_done(&io) && result;
6948 static bool
6949 status_update(struct view *view)
6951 struct line *line = &view->line[view->pos.lineno];
6953 assert(view->lines);
6955 if (!line->data) {
6956 if (status_has_none(view, line)) {
6957 report("Nothing to update");
6958 return FALSE;
6961 if (!status_update_files(view, line + 1)) {
6962 report("Failed to update file status");
6963 return FALSE;
6966 } else if (!status_update_file(line->data, line->type)) {
6967 report("Failed to update file status");
6968 return FALSE;
6971 return TRUE;
6974 static bool
6975 status_revert(struct status *status, enum line_type type, bool has_none)
6977 if (!status || type != LINE_STAT_UNSTAGED) {
6978 if (type == LINE_STAT_STAGED) {
6979 report("Cannot revert changes to staged files");
6980 } else if (type == LINE_STAT_UNTRACKED) {
6981 report("Cannot revert changes to untracked files");
6982 } else if (has_none) {
6983 report("Nothing to revert");
6984 } else {
6985 report("Cannot revert changes to multiple files");
6988 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6989 char mode[10] = "100644";
6990 const char *reset_argv[] = {
6991 "git", "update-index", "--cacheinfo", mode,
6992 status->old.rev, status->old.name, NULL
6994 const char *checkout_argv[] = {
6995 "git", "checkout", "--", status->old.name, NULL
6998 if (status->status == 'U') {
6999 string_format(mode, "%5o", status->old.mode);
7001 if (status->old.mode == 0 && status->new.mode == 0) {
7002 reset_argv[2] = "--force-remove";
7003 reset_argv[3] = status->old.name;
7004 reset_argv[4] = NULL;
7007 if (!io_run_fg(reset_argv, opt_cdup))
7008 return FALSE;
7009 if (status->old.mode == 0 && status->new.mode == 0)
7010 return TRUE;
7013 return io_run_fg(checkout_argv, opt_cdup);
7016 return FALSE;
7019 static enum request
7020 status_request(struct view *view, enum request request, struct line *line)
7022 struct status *status = line->data;
7024 switch (request) {
7025 case REQ_STATUS_UPDATE:
7026 if (!status_update(view))
7027 return REQ_NONE;
7028 break;
7030 case REQ_STATUS_REVERT:
7031 if (!status_revert(status, line->type, status_has_none(view, line)))
7032 return REQ_NONE;
7033 break;
7035 case REQ_STATUS_MERGE:
7036 if (!status || status->status != 'U') {
7037 report("Merging only possible for files with unmerged status ('U').");
7038 return REQ_NONE;
7040 open_mergetool(status->new.name);
7041 break;
7043 case REQ_EDIT:
7044 if (!status)
7045 return request;
7046 if (status->status == 'D') {
7047 report("File has been deleted.");
7048 return REQ_NONE;
7051 open_editor(status->new.name, 0);
7052 break;
7054 case REQ_VIEW_BLAME:
7055 if (status)
7056 opt_ref[0] = 0;
7057 return request;
7059 case REQ_ENTER:
7060 /* After returning the status view has been split to
7061 * show the stage view. No further reloading is
7062 * necessary. */
7063 return status_enter(view, line);
7065 case REQ_REFRESH:
7066 /* Load the current branch information and then the view. */
7067 load_refs(TRUE);
7068 break;
7070 default:
7071 return request;
7074 refresh_view(view);
7076 return REQ_NONE;
7079 static bool
7080 status_stage_info_(char *buf, size_t bufsize,
7081 enum line_type type, struct status *status)
7083 const char *file = status ? status->new.name : "";
7084 const char *info;
7086 switch (type) {
7087 case LINE_STAT_STAGED:
7088 if (status && status->status)
7089 info = "Staged changes to %s";
7090 else
7091 info = "Staged changes";
7092 break;
7094 case LINE_STAT_UNSTAGED:
7095 if (status && status->status)
7096 info = "Unstaged changes to %s";
7097 else
7098 info = "Unstaged changes";
7099 break;
7101 case LINE_STAT_UNTRACKED:
7102 info = "Untracked file %s";
7103 break;
7105 case LINE_STAT_HEAD:
7106 default:
7107 info = "";
7110 return string_nformat(buf, bufsize, NULL, info, file);
7112 #define status_stage_info(buf, type, status) \
7113 status_stage_info_(buf, sizeof(buf), type, status)
7115 static void
7116 status_select(struct view *view, struct line *line)
7118 struct status *status = line->data;
7119 char file[SIZEOF_STR] = "all files";
7120 const char *text;
7121 const char *key;
7123 if (status && !string_format(file, "'%s'", status->new.name))
7124 return;
7126 if (!status && line[1].type == LINE_STAT_NONE)
7127 line++;
7129 switch (line->type) {
7130 case LINE_STAT_STAGED:
7131 text = "Press %s to unstage %s for commit";
7132 break;
7134 case LINE_STAT_UNSTAGED:
7135 text = "Press %s to stage %s for commit";
7136 break;
7138 case LINE_STAT_UNTRACKED:
7139 text = "Press %s to stage %s for addition";
7140 break;
7142 case LINE_STAT_HEAD:
7143 case LINE_STAT_NONE:
7144 text = "Nothing to update";
7145 break;
7147 default:
7148 die("line type %d not handled in switch", line->type);
7151 if (status && status->status == 'U') {
7152 text = "Press %s to resolve conflict in %s";
7153 key = get_view_key(view, REQ_STATUS_MERGE);
7155 } else {
7156 key = get_view_key(view, REQ_STATUS_UPDATE);
7159 string_format(view->ref, text, key, file);
7160 status_stage_info(ref_status, line->type, status);
7161 if (status)
7162 string_copy(opt_file, status->new.name);
7165 static bool
7166 status_grep(struct view *view, struct line *line)
7168 struct status *status = line->data;
7170 if (status) {
7171 const char buf[2] = { status->status, 0 };
7172 const char *text[] = { status->new.name, buf, NULL };
7174 return grep_text(view, text);
7177 return FALSE;
7180 static struct view_ops status_ops = {
7181 "file",
7182 { "status" },
7183 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7185 status_open,
7186 NULL,
7187 status_draw,
7188 status_request,
7189 status_grep,
7190 status_select,
7194 struct stage_state {
7195 struct diff_state diff;
7196 size_t chunks;
7197 int *chunk;
7200 static bool
7201 stage_diff_write(struct io *io, struct line *line, struct line *end)
7203 while (line < end) {
7204 if (!io_write(io, line->data, strlen(line->data)) ||
7205 !io_write(io, "\n", 1))
7206 return FALSE;
7207 line++;
7208 if (line->type == LINE_DIFF_CHUNK ||
7209 line->type == LINE_DIFF_HEADER)
7210 break;
7213 return TRUE;
7216 static bool
7217 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7219 const char *apply_argv[SIZEOF_ARG] = {
7220 "git", "apply", "--whitespace=nowarn", NULL
7222 struct line *diff_hdr;
7223 struct io io;
7224 int argc = 3;
7226 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7227 if (!diff_hdr)
7228 return FALSE;
7230 if (!revert)
7231 apply_argv[argc++] = "--cached";
7232 if (line != NULL)
7233 apply_argv[argc++] = "--unidiff-zero";
7234 if (revert || stage_line_type == LINE_STAT_STAGED)
7235 apply_argv[argc++] = "-R";
7236 apply_argv[argc++] = "-";
7237 apply_argv[argc++] = NULL;
7238 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7239 return FALSE;
7241 if (line != NULL) {
7242 int lineno = 0;
7243 struct line *context = chunk + 1;
7244 const char *markers[] = {
7245 line->type == LINE_DIFF_DEL ? "" : ",0",
7246 line->type == LINE_DIFF_DEL ? ",0" : "",
7249 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7251 while (context < line) {
7252 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7253 break;
7254 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7255 lineno++;
7257 context++;
7260 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7261 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7262 lineno, markers[0], lineno, markers[1]) ||
7263 !stage_diff_write(&io, line, line + 1)) {
7264 chunk = NULL;
7266 } else {
7267 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7268 !stage_diff_write(&io, chunk, view->line + view->lines))
7269 chunk = NULL;
7272 io_done(&io);
7274 return chunk ? TRUE : FALSE;
7277 static bool
7278 stage_update(struct view *view, struct line *line, bool single)
7280 struct line *chunk = NULL;
7282 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7283 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7285 if (chunk) {
7286 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7287 report("Failed to apply chunk");
7288 return FALSE;
7291 } else if (!stage_status.status) {
7292 view = view->parent;
7294 for (line = view->line; view_has_line(view, line); line++)
7295 if (line->type == stage_line_type)
7296 break;
7298 if (!status_update_files(view, line + 1)) {
7299 report("Failed to update files");
7300 return FALSE;
7303 } else if (!status_update_file(&stage_status, stage_line_type)) {
7304 report("Failed to update file");
7305 return FALSE;
7308 return TRUE;
7311 static bool
7312 stage_revert(struct view *view, struct line *line)
7314 struct line *chunk = NULL;
7316 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7317 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7319 if (chunk) {
7320 if (!prompt_yesno("Are you sure you want to revert changes?"))
7321 return FALSE;
7323 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7324 report("Failed to revert chunk");
7325 return FALSE;
7327 return TRUE;
7329 } else {
7330 return status_revert(stage_status.status ? &stage_status : NULL,
7331 stage_line_type, FALSE);
7336 static void
7337 stage_next(struct view *view, struct line *line)
7339 struct stage_state *state = view->private;
7340 int i;
7342 if (!state->chunks) {
7343 for (line = view->line; view_has_line(view, line); line++) {
7344 if (line->type != LINE_DIFF_CHUNK)
7345 continue;
7347 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7348 report("Allocation failure");
7349 return;
7352 state->chunk[state->chunks++] = line - view->line;
7356 for (i = 0; i < state->chunks; i++) {
7357 if (state->chunk[i] > view->pos.lineno) {
7358 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7359 report("Chunk %d of %zd", i + 1, state->chunks);
7360 return;
7364 report("No next chunk found");
7367 static enum request
7368 stage_request(struct view *view, enum request request, struct line *line)
7370 switch (request) {
7371 case REQ_STATUS_UPDATE:
7372 if (!stage_update(view, line, FALSE))
7373 return REQ_NONE;
7374 break;
7376 case REQ_STATUS_REVERT:
7377 if (!stage_revert(view, line))
7378 return REQ_NONE;
7379 break;
7381 case REQ_STAGE_UPDATE_LINE:
7382 if (stage_line_type == LINE_STAT_UNTRACKED ||
7383 stage_status.status == 'A') {
7384 report("Staging single lines is not supported for new files");
7385 return REQ_NONE;
7387 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7388 report("Please select a change to stage");
7389 return REQ_NONE;
7391 if (!stage_update(view, line, TRUE))
7392 return REQ_NONE;
7393 break;
7395 case REQ_STAGE_NEXT:
7396 if (stage_line_type == LINE_STAT_UNTRACKED) {
7397 report("File is untracked; press %s to add",
7398 get_view_key(view, REQ_STATUS_UPDATE));
7399 return REQ_NONE;
7401 stage_next(view, line);
7402 return REQ_NONE;
7404 case REQ_EDIT:
7405 if (!stage_status.new.name[0])
7406 return diff_common_edit(view, request, line);
7408 if (stage_status.status == 'D') {
7409 report("File has been deleted.");
7410 return REQ_NONE;
7413 if (stage_line_type == LINE_STAT_UNTRACKED) {
7414 open_editor(stage_status.new.name, (line - view->line) + 1);
7415 } else {
7416 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7418 break;
7420 case REQ_REFRESH:
7421 /* Reload everything(including current branch information) ... */
7422 load_refs(TRUE);
7423 break;
7425 case REQ_VIEW_BLAME:
7426 if (stage_status.new.name[0]) {
7427 string_copy(opt_file, stage_status.new.name);
7428 opt_ref[0] = 0;
7430 return request;
7432 case REQ_ENTER:
7433 return diff_common_enter(view, request, line);
7435 case REQ_DIFF_CONTEXT_UP:
7436 case REQ_DIFF_CONTEXT_DOWN:
7437 if (!update_diff_context(request))
7438 return REQ_NONE;
7439 break;
7441 default:
7442 return request;
7445 refresh_view(view->parent);
7447 /* Check whether the staged entry still exists, and close the
7448 * stage view if it doesn't. */
7449 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7450 status_restore(view->parent);
7451 return REQ_VIEW_CLOSE;
7454 refresh_view(view);
7456 return REQ_NONE;
7459 static bool
7460 stage_open(struct view *view, enum open_flags flags)
7462 static const char *no_head_diff_argv[] = {
7463 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7464 stage_status.new.name)
7466 static const char *index_show_argv[] = {
7467 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7468 stage_status.old.name, stage_status.new.name)
7470 static const char *files_show_argv[] = {
7471 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7472 stage_status.old.name, stage_status.new.name)
7474 /* Diffs for unmerged entries are empty when passing the new
7475 * path, so leave out the new path. */
7476 static const char *files_unmerged_argv[] = {
7477 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
7478 opt_diff_context_arg, opt_ignore_space_arg, "--",
7479 stage_status.old.name, NULL
7481 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7482 const char **argv = NULL;
7484 if (!stage_line_type) {
7485 report("No stage content, press %s to open the status view and choose file",
7486 get_view_key(view, REQ_VIEW_STATUS));
7487 return FALSE;
7490 view->encoding = NULL;
7492 switch (stage_line_type) {
7493 case LINE_STAT_STAGED:
7494 if (is_initial_commit()) {
7495 argv = no_head_diff_argv;
7496 } else {
7497 argv = index_show_argv;
7499 break;
7501 case LINE_STAT_UNSTAGED:
7502 if (stage_status.status != 'U')
7503 argv = files_show_argv;
7504 else
7505 argv = files_unmerged_argv;
7506 break;
7508 case LINE_STAT_UNTRACKED:
7509 argv = file_argv;
7510 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
7511 break;
7513 case LINE_STAT_HEAD:
7514 default:
7515 die("line type %d not handled in switch", stage_line_type);
7518 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7519 || !argv_copy(&view->argv, argv)) {
7520 report("Failed to open staged view");
7521 return FALSE;
7524 view->vid[0] = 0;
7525 view->dir = opt_cdup;
7526 return begin_update(view, NULL, NULL, flags);
7529 static bool
7530 stage_read(struct view *view, char *data)
7532 struct stage_state *state = view->private;
7534 if (stage_line_type == LINE_STAT_UNTRACKED)
7535 return pager_common_read(view, data, LINE_DEFAULT);
7537 if (data && diff_common_read(view, data, &state->diff))
7538 return TRUE;
7540 return pager_read(view, data);
7543 static struct view_ops stage_ops = {
7544 "line",
7545 { "stage" },
7546 VIEW_DIFF_LIKE,
7547 sizeof(struct stage_state),
7548 stage_open,
7549 stage_read,
7550 diff_common_draw,
7551 stage_request,
7552 pager_grep,
7553 pager_select,
7558 * Revision graph
7561 static const enum line_type graph_colors[] = {
7562 LINE_PALETTE_0,
7563 LINE_PALETTE_1,
7564 LINE_PALETTE_2,
7565 LINE_PALETTE_3,
7566 LINE_PALETTE_4,
7567 LINE_PALETTE_5,
7568 LINE_PALETTE_6,
7571 static enum line_type get_graph_color(struct graph_symbol *symbol)
7573 if (symbol->commit)
7574 return LINE_GRAPH_COMMIT;
7575 assert(symbol->color < ARRAY_SIZE(graph_colors));
7576 return graph_colors[symbol->color];
7579 static bool
7580 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7582 const char *chars = graph_symbol_to_utf8(symbol);
7584 return draw_text(view, color, chars + !!first);
7587 static bool
7588 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7590 const char *chars = graph_symbol_to_ascii(symbol);
7592 return draw_text(view, color, chars + !!first);
7595 static bool
7596 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7598 const chtype *chars = graph_symbol_to_chtype(symbol);
7600 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7603 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7605 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7607 static const draw_graph_fn fns[] = {
7608 draw_graph_ascii,
7609 draw_graph_chtype,
7610 draw_graph_utf8
7612 draw_graph_fn fn = fns[opt_line_graphics];
7613 int i;
7615 for (i = 0; i < canvas->size; i++) {
7616 struct graph_symbol *symbol = &canvas->symbols[i];
7617 enum line_type color = get_graph_color(symbol);
7619 if (fn(view, symbol, color, i == 0))
7620 return TRUE;
7623 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7627 * Main view backend
7630 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7632 struct commit {
7633 char id[SIZEOF_REV]; /* SHA1 ID. */
7634 const struct ident *author; /* Author of the commit. */
7635 struct time time; /* Date from the author ident. */
7636 struct graph_canvas graph; /* Ancestry chain graphics. */
7637 char title[1]; /* First line of the commit message. */
7640 struct main_state {
7641 struct graph graph;
7642 struct commit current;
7643 char **reflog;
7644 size_t reflogs;
7645 int reflog_width;
7646 char reflogmsg[SIZEOF_STR / 2];
7647 bool in_header;
7648 bool added_changes_commits;
7649 bool with_graph;
7652 static void
7653 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7655 struct main_state *state = view->private;
7657 string_copy_rev(commit->id, ids);
7658 if (state->with_graph)
7659 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7662 static struct commit *
7663 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7664 const char *title, bool custom)
7666 struct main_state *state = view->private;
7667 size_t titlelen = strlen(title);
7668 struct commit *commit;
7669 char buf[SIZEOF_STR / 2];
7671 /* FIXME: More graceful handling of titles; append "..." to
7672 * shortened titles, etc. */
7673 string_expand(buf, sizeof(buf), title, 1);
7674 title = buf;
7675 titlelen = strlen(title);
7677 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7678 return NULL;
7680 *commit = *template;
7681 strncpy(commit->title, title, titlelen);
7682 state->graph.canvas = &commit->graph;
7683 memset(template, 0, sizeof(*template));
7684 state->reflogmsg[0] = 0;
7685 return commit;
7688 static inline void
7689 main_flush_commit(struct view *view, struct commit *commit)
7691 if (*commit->id)
7692 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7695 static bool
7696 main_has_changes(const char *argv[])
7698 struct io io;
7700 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7701 return FALSE;
7702 io_done(&io);
7703 return io.status == 1;
7706 static void
7707 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7709 char ids[SIZEOF_STR] = NULL_ID " ";
7710 struct main_state *state = view->private;
7711 struct commit commit = {};
7712 struct timeval now;
7713 struct timezone tz;
7715 if (!parent)
7716 return;
7718 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7720 if (!gettimeofday(&now, &tz)) {
7721 commit.time.tz = tz.tz_minuteswest * 60;
7722 commit.time.sec = now.tv_sec - commit.time.tz;
7725 commit.author = &unknown_ident;
7726 main_register_commit(view, &commit, ids, FALSE);
7727 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7728 graph_render_parents(&state->graph);
7731 static void
7732 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7734 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7735 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7736 const char *staged_parent = NULL_ID;
7737 const char *unstaged_parent = parent;
7739 if (!is_head_commit(parent))
7740 return;
7742 state->added_changes_commits = TRUE;
7744 io_run_bg(update_index_argv);
7746 if (!main_has_changes(unstaged_argv)) {
7747 unstaged_parent = NULL;
7748 staged_parent = parent;
7751 if (!main_has_changes(staged_argv)) {
7752 staged_parent = NULL;
7755 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7756 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7759 static bool
7760 main_open(struct view *view, enum open_flags flags)
7762 static const char *main_argv[] = {
7763 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7765 struct main_state *state = view->private;
7767 state->with_graph = opt_rev_graph;
7769 if (flags & OPEN_PAGER_MODE) {
7770 state->added_changes_commits = TRUE;
7771 state->with_graph = FALSE;
7774 return begin_update(view, NULL, main_argv, flags);
7777 static void
7778 main_done(struct view *view)
7780 struct main_state *state = view->private;
7781 int i;
7783 for (i = 0; i < view->lines; i++) {
7784 struct commit *commit = view->line[i].data;
7786 free(commit->graph.symbols);
7789 for (i = 0; i < state->reflogs; i++)
7790 free(state->reflog[i]);
7791 free(state->reflog);
7794 #define MAIN_NO_COMMIT_REFS 1
7795 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
7796 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
7798 static inline struct ref_list *
7799 main_get_commit_refs(struct line *line, struct commit *commit)
7801 struct ref_list *refs = NULL;
7803 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
7804 main_mark_no_commit_refs(line);
7806 return refs;
7809 static bool
7810 main_draw(struct view *view, struct line *line, unsigned int lineno)
7812 struct main_state *state = view->private;
7813 struct commit *commit = line->data;
7814 struct ref_list *refs = NULL;
7816 if (!commit->author)
7817 return FALSE;
7819 if (draw_lineno(view, lineno))
7820 return TRUE;
7822 if (opt_show_id) {
7823 if (state->reflogs) {
7824 const char *id = state->reflog[line->lineno - 1];
7826 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
7827 return TRUE;
7828 } else if (draw_id(view, commit->id)) {
7829 return TRUE;
7833 if (draw_date(view, &commit->time))
7834 return TRUE;
7836 if (draw_author(view, commit->author))
7837 return TRUE;
7839 if (state->with_graph && draw_graph(view, &commit->graph))
7840 return TRUE;
7842 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
7843 return TRUE;
7845 if (commit->title)
7846 draw_commit_title(view, commit->title, 0);
7847 return TRUE;
7850 static bool
7851 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
7853 char *end = strchr(reflog, ' ');
7854 int id_width;
7856 if (!end)
7857 return FALSE;
7858 *end = 0;
7860 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
7861 || !(reflog = strdup(reflog)))
7862 return FALSE;
7864 state->reflog[state->reflogs++] = reflog;
7865 id_width = strlen(reflog);
7866 if (state->reflog_width < id_width) {
7867 state->reflog_width = id_width;
7868 if (opt_show_id)
7869 view->force_redraw = TRUE;
7872 return TRUE;
7875 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7876 static bool
7877 main_read(struct view *view, char *line)
7879 struct main_state *state = view->private;
7880 struct graph *graph = &state->graph;
7881 enum line_type type;
7882 struct commit *commit = &state->current;
7884 if (!line) {
7885 main_flush_commit(view, commit);
7887 if (!view->lines && !view->prev)
7888 die("No revisions match the given arguments.");
7889 if (view->lines > 0) {
7890 struct commit *last = view->line[view->lines - 1].data;
7892 view->line[view->lines - 1].dirty = 1;
7893 if (!last->author) {
7894 view->lines--;
7895 free(last);
7899 if (state->with_graph)
7900 done_graph(graph);
7901 return TRUE;
7904 type = get_line_type(line);
7905 if (type == LINE_COMMIT) {
7906 bool is_boundary;
7908 state->in_header = TRUE;
7909 line += STRING_SIZE("commit ");
7910 is_boundary = *line == '-';
7911 if (is_boundary || !isalnum(*line))
7912 line++;
7914 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7915 main_add_changes_commits(view, state, line);
7916 else
7917 main_flush_commit(view, commit);
7919 main_register_commit(view, &state->current, line, is_boundary);
7920 return TRUE;
7923 if (!*commit->id)
7924 return TRUE;
7926 /* Empty line separates the commit header from the log itself. */
7927 if (*line == '\0')
7928 state->in_header = FALSE;
7930 switch (type) {
7931 case LINE_PP_REFLOG:
7932 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
7933 return FALSE;
7934 break;
7936 case LINE_PP_REFLOGMSG:
7937 line += STRING_SIZE("Reflog message: ");
7938 string_ncopy(state->reflogmsg, line, strlen(line));
7939 break;
7941 case LINE_PARENT:
7942 if (state->with_graph && !graph->has_parents)
7943 graph_add_parent(graph, line + STRING_SIZE("parent "));
7944 break;
7946 case LINE_AUTHOR:
7947 parse_author_line(line + STRING_SIZE("author "),
7948 &commit->author, &commit->time);
7949 if (state->with_graph)
7950 graph_render_parents(graph);
7951 break;
7953 default:
7954 /* Fill in the commit title if it has not already been set. */
7955 if (*commit->title)
7956 break;
7958 /* Skip lines in the commit header. */
7959 if (state->in_header)
7960 break;
7962 /* Require titles to start with a non-space character at the
7963 * offset used by git log. */
7964 if (strncmp(line, " ", 4))
7965 break;
7966 line += 4;
7967 /* Well, if the title starts with a whitespace character,
7968 * try to be forgiving. Otherwise we end up with no title. */
7969 while (isspace(*line))
7970 line++;
7971 if (*line == '\0')
7972 break;
7973 if (*state->reflogmsg)
7974 line = state->reflogmsg;
7975 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
7978 return TRUE;
7981 static enum request
7982 main_request(struct view *view, enum request request, struct line *line)
7984 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7985 ? OPEN_SPLIT : OPEN_DEFAULT;
7987 switch (request) {
7988 case REQ_NEXT:
7989 case REQ_PREVIOUS:
7990 if (view_is_displayed(view) && display[0] != view)
7991 return request;
7992 /* Do not pass navigation requests to the branch view
7993 * when the main view is maximized. (GH #38) */
7994 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
7996 case REQ_VIEW_DIFF:
7997 case REQ_ENTER:
7998 if (view_is_displayed(view) && display[0] != view)
7999 maximize_view(view, TRUE);
8001 if (line->type == LINE_STAT_UNSTAGED
8002 || line->type == LINE_STAT_STAGED) {
8003 struct view *diff = VIEW(REQ_VIEW_DIFF);
8004 const char *diff_staged_argv[] = {
8005 GIT_DIFF_STAGED(opt_encoding_arg,
8006 opt_diff_context_arg,
8007 opt_ignore_space_arg, NULL, NULL)
8009 const char *diff_unstaged_argv[] = {
8010 GIT_DIFF_UNSTAGED(opt_encoding_arg,
8011 opt_diff_context_arg,
8012 opt_ignore_space_arg, NULL, NULL)
8014 const char **diff_argv = line->type == LINE_STAT_STAGED
8015 ? diff_staged_argv : diff_unstaged_argv;
8017 open_argv(view, diff, diff_argv, NULL, flags);
8018 break;
8021 open_view(view, REQ_VIEW_DIFF, flags);
8022 break;
8024 case REQ_REFRESH:
8025 load_refs(TRUE);
8026 refresh_view(view);
8027 break;
8029 case REQ_JUMP_COMMIT:
8031 int lineno;
8033 for (lineno = 0; lineno < view->lines; lineno++) {
8034 struct commit *commit = view->line[lineno].data;
8036 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8037 select_view_line(view, lineno);
8038 report_clear();
8039 return REQ_NONE;
8043 report("Unable to find commit '%s'", opt_search);
8044 break;
8046 default:
8047 return request;
8050 return REQ_NONE;
8053 static bool
8054 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8056 struct ref_list *list;
8057 regmatch_t pmatch;
8058 size_t i;
8060 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8061 return FALSE;
8063 for (i = 0; i < list->size; i++) {
8064 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8065 return TRUE;
8068 return FALSE;
8071 static bool
8072 main_grep(struct view *view, struct line *line)
8074 struct commit *commit = line->data;
8075 const char *text[] = {
8076 commit->id,
8077 commit->title,
8078 mkauthor(commit->author, opt_author_width, opt_author),
8079 mkdate(&commit->time, opt_date),
8080 NULL
8083 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8086 static void
8087 main_select(struct view *view, struct line *line)
8089 struct commit *commit = line->data;
8091 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8092 string_ncopy(view->ref, commit->title, strlen(commit->title));
8093 else
8094 string_copy_rev(view->ref, commit->id);
8095 string_copy_rev(ref_commit, commit->id);
8098 static struct view_ops main_ops = {
8099 "commit",
8100 { "main" },
8101 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8102 sizeof(struct main_state),
8103 main_open,
8104 main_read,
8105 main_draw,
8106 main_request,
8107 main_grep,
8108 main_select,
8109 main_done,
8112 static bool
8113 stash_open(struct view *view, enum open_flags flags)
8115 static const char *stash_argv[] = { "git", "stash", "list",
8116 opt_encoding_arg, "--no-color", "--pretty=raw", NULL };
8117 struct main_state *state = view->private;
8119 state->added_changes_commits = TRUE;
8120 state->with_graph = FALSE;
8121 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8124 static void
8125 stash_select(struct view *view, struct line *line)
8127 main_select(view, line);
8128 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8129 string_copy(view->ref, ref_stash);
8132 static struct view_ops stash_ops = {
8133 "stash",
8134 { "stash" },
8135 VIEW_SEND_CHILD_ENTER,
8136 sizeof(struct main_state),
8137 stash_open,
8138 main_read,
8139 main_draw,
8140 main_request,
8141 main_grep,
8142 stash_select,
8146 * Status management
8149 /* Whether or not the curses interface has been initialized. */
8150 static bool cursed = FALSE;
8152 /* Terminal hacks and workarounds. */
8153 static bool use_scroll_redrawwin;
8154 static bool use_scroll_status_wclear;
8156 /* The status window is used for polling keystrokes. */
8157 static WINDOW *status_win;
8159 /* Reading from the prompt? */
8160 static bool input_mode = FALSE;
8162 static bool status_empty = FALSE;
8164 /* Update status and title window. */
8165 static void
8166 report(const char *msg, ...)
8168 struct view *view = display[current_view];
8170 if (input_mode)
8171 return;
8173 if (!view) {
8174 char buf[SIZEOF_STR];
8175 int retval;
8177 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8178 die("%s", buf);
8181 if (!status_empty || *msg) {
8182 va_list args;
8184 va_start(args, msg);
8186 wmove(status_win, 0, 0);
8187 if (view->has_scrolled && use_scroll_status_wclear)
8188 wclear(status_win);
8189 if (*msg) {
8190 vwprintw(status_win, msg, args);
8191 status_empty = FALSE;
8192 } else {
8193 status_empty = TRUE;
8195 wclrtoeol(status_win);
8196 wnoutrefresh(status_win);
8198 va_end(args);
8201 update_view_title(view);
8204 static void
8205 init_display(void)
8207 const char *term;
8208 int x, y;
8210 /* Initialize the curses library */
8211 if (isatty(STDIN_FILENO)) {
8212 cursed = !!initscr();
8213 opt_tty = stdin;
8214 } else {
8215 /* Leave stdin and stdout alone when acting as a pager. */
8216 opt_tty = fopen("/dev/tty", "r+");
8217 if (!opt_tty)
8218 die("Failed to open /dev/tty");
8219 cursed = !!newterm(NULL, opt_tty, opt_tty);
8222 if (!cursed)
8223 die("Failed to initialize curses");
8225 nonl(); /* Disable conversion and detect newlines from input. */
8226 cbreak(); /* Take input chars one at a time, no wait for \n */
8227 noecho(); /* Don't echo input */
8228 leaveok(stdscr, FALSE);
8230 if (has_colors())
8231 init_colors();
8233 getmaxyx(stdscr, y, x);
8234 status_win = newwin(1, x, y - 1, 0);
8235 if (!status_win)
8236 die("Failed to create status window");
8238 /* Enable keyboard mapping */
8239 keypad(status_win, TRUE);
8240 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8242 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8243 set_tabsize(opt_tab_size);
8244 #else
8245 TABSIZE = opt_tab_size;
8246 #endif
8248 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8249 if (term && !strcmp(term, "gnome-terminal")) {
8250 /* In the gnome-terminal-emulator, the message from
8251 * scrolling up one line when impossible followed by
8252 * scrolling down one line causes corruption of the
8253 * status line. This is fixed by calling wclear. */
8254 use_scroll_status_wclear = TRUE;
8255 use_scroll_redrawwin = FALSE;
8257 } else if (term && !strcmp(term, "xrvt-xpm")) {
8258 /* No problems with full optimizations in xrvt-(unicode)
8259 * and aterm. */
8260 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8262 } else {
8263 /* When scrolling in (u)xterm the last line in the
8264 * scrolling direction will update slowly. */
8265 use_scroll_redrawwin = TRUE;
8266 use_scroll_status_wclear = FALSE;
8270 static int
8271 get_input(int prompt_position)
8273 struct view *view;
8274 int i, key, cursor_y, cursor_x;
8276 if (prompt_position)
8277 input_mode = TRUE;
8279 while (TRUE) {
8280 bool loading = FALSE;
8282 foreach_view (view, i) {
8283 update_view(view);
8284 if (view_is_displayed(view) && view->has_scrolled &&
8285 use_scroll_redrawwin)
8286 redrawwin(view->win);
8287 view->has_scrolled = FALSE;
8288 if (view->pipe)
8289 loading = TRUE;
8292 /* Update the cursor position. */
8293 if (prompt_position) {
8294 getbegyx(status_win, cursor_y, cursor_x);
8295 cursor_x = prompt_position;
8296 } else {
8297 view = display[current_view];
8298 getbegyx(view->win, cursor_y, cursor_x);
8299 cursor_x = view->width - 1;
8300 cursor_y += view->pos.lineno - view->pos.offset;
8302 setsyx(cursor_y, cursor_x);
8304 /* Refresh, accept single keystroke of input */
8305 doupdate();
8306 nodelay(status_win, loading);
8307 key = wgetch(status_win);
8309 /* wgetch() with nodelay() enabled returns ERR when
8310 * there's no input. */
8311 if (key == ERR) {
8313 } else if (key == KEY_RESIZE) {
8314 int height, width;
8316 getmaxyx(stdscr, height, width);
8318 wresize(status_win, 1, width);
8319 mvwin(status_win, height - 1, 0);
8320 wnoutrefresh(status_win);
8321 resize_display();
8322 redraw_display(TRUE);
8324 } else {
8325 input_mode = FALSE;
8326 if (key == erasechar())
8327 key = KEY_BACKSPACE;
8328 return key;
8333 static char *
8334 prompt_input(const char *prompt, input_handler handler, void *data)
8336 enum input_status status = INPUT_OK;
8337 static char buf[SIZEOF_STR];
8338 size_t pos = 0;
8340 buf[pos] = 0;
8342 while (status == INPUT_OK || status == INPUT_SKIP) {
8343 int key;
8345 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8346 wclrtoeol(status_win);
8348 key = get_input(pos + 1);
8349 switch (key) {
8350 case KEY_RETURN:
8351 case KEY_ENTER:
8352 case '\n':
8353 status = pos ? INPUT_STOP : INPUT_CANCEL;
8354 break;
8356 case KEY_BACKSPACE:
8357 if (pos > 0)
8358 buf[--pos] = 0;
8359 else
8360 status = INPUT_CANCEL;
8361 break;
8363 case KEY_ESC:
8364 status = INPUT_CANCEL;
8365 break;
8367 default:
8368 if (pos >= sizeof(buf)) {
8369 report("Input string too long");
8370 return NULL;
8373 status = handler(data, buf, key);
8374 if (status == INPUT_OK)
8375 buf[pos++] = (char) key;
8379 /* Clear the status window */
8380 status_empty = FALSE;
8381 report_clear();
8383 if (status == INPUT_CANCEL)
8384 return NULL;
8386 buf[pos++] = 0;
8388 return buf;
8391 static enum input_status
8392 prompt_yesno_handler(void *data, char *buf, int c)
8394 if (c == 'y' || c == 'Y')
8395 return INPUT_STOP;
8396 if (c == 'n' || c == 'N')
8397 return INPUT_CANCEL;
8398 return INPUT_SKIP;
8401 static bool
8402 prompt_yesno(const char *prompt)
8404 char prompt2[SIZEOF_STR];
8406 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8407 return FALSE;
8409 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8412 static enum input_status
8413 read_prompt_handler(void *data, char *buf, int c)
8415 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8418 static char *
8419 read_prompt(const char *prompt)
8421 return prompt_input(prompt, read_prompt_handler, NULL);
8424 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8426 enum input_status status = INPUT_OK;
8427 int size = 0;
8429 while (items[size].text)
8430 size++;
8432 assert(size > 0);
8434 while (status == INPUT_OK) {
8435 const struct menu_item *item = &items[*selected];
8436 int key;
8437 int i;
8439 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8440 prompt, *selected + 1, size);
8441 if (item->hotkey)
8442 wprintw(status_win, "[%c] ", (char) item->hotkey);
8443 wprintw(status_win, "%s", item->text);
8444 wclrtoeol(status_win);
8446 key = get_input(COLS - 1);
8447 switch (key) {
8448 case KEY_RETURN:
8449 case KEY_ENTER:
8450 case '\n':
8451 status = INPUT_STOP;
8452 break;
8454 case KEY_LEFT:
8455 case KEY_UP:
8456 *selected = *selected - 1;
8457 if (*selected < 0)
8458 *selected = size - 1;
8459 break;
8461 case KEY_RIGHT:
8462 case KEY_DOWN:
8463 *selected = (*selected + 1) % size;
8464 break;
8466 case KEY_ESC:
8467 status = INPUT_CANCEL;
8468 break;
8470 default:
8471 for (i = 0; items[i].text; i++)
8472 if (items[i].hotkey == key) {
8473 *selected = i;
8474 status = INPUT_STOP;
8475 break;
8480 /* Clear the status window */
8481 status_empty = FALSE;
8482 report_clear();
8484 return status != INPUT_CANCEL;
8488 * Repository properties
8492 static void
8493 set_remote_branch(const char *name, const char *value, size_t valuelen)
8495 if (!strcmp(name, ".remote")) {
8496 string_ncopy(opt_remote, value, valuelen);
8498 } else if (*opt_remote && !strcmp(name, ".merge")) {
8499 size_t from = strlen(opt_remote);
8501 if (!prefixcmp(value, "refs/heads/"))
8502 value += STRING_SIZE("refs/heads/");
8504 if (!string_format_from(opt_remote, &from, "/%s", value))
8505 opt_remote[0] = 0;
8509 static void
8510 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
8512 const char *argv[SIZEOF_ARG] = { name, "=" };
8513 int argc = 1 + (cmd == option_set_command);
8514 enum option_code error;
8516 if (!argv_from_string(argv, &argc, value))
8517 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
8518 else
8519 error = cmd(argc, argv);
8521 if (error != OPT_OK)
8522 warn("Option 'tig.%s': %s", name, option_errors[error]);
8525 static void
8526 set_work_tree(const char *value)
8528 char cwd[SIZEOF_STR];
8530 if (!getcwd(cwd, sizeof(cwd)))
8531 die("Failed to get cwd path: %s", strerror(errno));
8532 if (chdir(cwd) < 0)
8533 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8534 if (chdir(opt_git_dir) < 0)
8535 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8536 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8537 die("Failed to get git path: %s", strerror(errno));
8538 if (chdir(value) < 0)
8539 die("Failed to chdir(%s): %s", value, strerror(errno));
8540 if (!getcwd(cwd, sizeof(cwd)))
8541 die("Failed to get cwd path: %s", strerror(errno));
8542 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8543 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8544 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8545 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8546 opt_is_inside_work_tree = TRUE;
8549 static void
8550 parse_git_color_option(enum line_type type, char *value)
8552 struct line_info *info = &line_info[type];
8553 const char *argv[SIZEOF_ARG];
8554 int argc = 0;
8555 bool first_color = TRUE;
8556 int i;
8558 if (!argv_from_string(argv, &argc, value))
8559 return;
8561 info->fg = COLOR_DEFAULT;
8562 info->bg = COLOR_DEFAULT;
8563 info->attr = 0;
8565 for (i = 0; i < argc; i++) {
8566 int attr = 0;
8568 if (set_attribute(&attr, argv[i])) {
8569 info->attr |= attr;
8571 } else if (set_color(&attr, argv[i])) {
8572 if (first_color)
8573 info->fg = attr;
8574 else
8575 info->bg = attr;
8576 first_color = FALSE;
8581 static void
8582 set_git_color_option(const char *name, char *value)
8584 static const struct enum_map color_option_map[] = {
8585 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8586 ENUM_MAP("branch.local", LINE_MAIN_REF),
8587 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8588 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8590 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8591 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8592 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8593 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8594 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8595 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8596 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8598 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8600 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8601 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8602 ENUM_MAP("status.added", LINE_STAT_STAGED),
8603 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8604 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8605 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8608 int type = LINE_NONE;
8610 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8611 parse_git_color_option(type, value);
8615 static void
8616 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8618 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
8619 opt_encoding_arg[0] = 0;
8622 static int
8623 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8625 if (!strcmp(name, "i18n.commitencoding"))
8626 set_encoding(&opt_encoding, value, FALSE);
8628 else if (!strcmp(name, "gui.encoding"))
8629 set_encoding(&opt_encoding, value, TRUE);
8631 else if (!strcmp(name, "core.editor"))
8632 string_ncopy(opt_editor, value, valuelen);
8634 else if (!strcmp(name, "core.worktree"))
8635 set_work_tree(value);
8637 else if (!strcmp(name, "core.abbrev"))
8638 parse_id(&opt_id_cols, value);
8640 else if (!prefixcmp(name, "tig.color."))
8641 set_repo_config_option(name + 10, value, option_color_command);
8643 else if (!prefixcmp(name, "tig.bind."))
8644 set_repo_config_option(name + 9, value, option_bind_command);
8646 else if (!prefixcmp(name, "tig."))
8647 set_repo_config_option(name + 4, value, option_set_command);
8649 else if (!prefixcmp(name, "color."))
8650 set_git_color_option(name + STRING_SIZE("color."), value);
8652 else if (*opt_head && !prefixcmp(name, "branch.") &&
8653 !strncmp(name + 7, opt_head, strlen(opt_head)))
8654 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8656 return OK;
8659 static int
8660 load_git_config(void)
8662 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8664 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8667 #define REPO_INFO_GIT_DIR "--git-dir"
8668 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8669 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8670 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8671 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8672 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8674 struct repo_info_state {
8675 const char **argv;
8676 char head_id[SIZEOF_REV];
8679 static int
8680 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8682 struct repo_info_state *state = data;
8683 const char *arg = *state->argv ? *state->argv++ : "";
8685 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8686 string_ncopy(opt_git_dir, name, namelen);
8688 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8689 /* This can be 3 different values depending on the
8690 * version of git being used. If git-rev-parse does not
8691 * understand --is-inside-work-tree it will simply echo
8692 * the option else either "true" or "false" is printed.
8693 * Default to true for the unknown case. */
8694 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8696 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8697 string_ncopy(opt_cdup, name, namelen);
8699 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8700 string_ncopy(opt_prefix, name, namelen);
8702 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8703 string_ncopy(state->head_id, name, namelen);
8705 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8706 if (!prefixcmp(name, "refs/heads/")) {
8707 char *offset = name + STRING_SIZE("refs/heads/");
8709 string_ncopy(opt_head, offset, strlen(offset) + 1);
8710 add_ref(state->head_id, name, opt_remote, opt_head);
8712 state->argv++;
8715 return OK;
8718 static int
8719 load_repo_info(void)
8721 const char *rev_parse_argv[] = {
8722 "git", "rev-parse", REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8723 REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE, REPO_INFO_SHOW_CDUP,
8724 REPO_INFO_SHOW_PREFIX, NULL
8726 struct repo_info_state state = { rev_parse_argv + 2 };
8728 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8733 * Main
8736 static const char usage[] =
8737 "tig " TIG_VERSION " (" __DATE__ ")\n"
8738 "\n"
8739 "Usage: tig [options] [revs] [--] [paths]\n"
8740 " or: tig log [options] [revs] [--] [paths]\n"
8741 " or: tig show [options] [revs] [--] [paths]\n"
8742 " or: tig blame [options] [rev] [--] path\n"
8743 " or: tig stash\n"
8744 " or: tig status\n"
8745 " or: tig < [git command output]\n"
8746 "\n"
8747 "Options:\n"
8748 " +<number> Select line <number> in the first view\n"
8749 " -v, --version Show version and exit\n"
8750 " -h, --help Show help message and exit";
8752 static void TIG_NORETURN
8753 quit(int sig)
8755 if (sig)
8756 signal(sig, SIG_DFL);
8758 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8759 if (cursed)
8760 endwin();
8761 exit(0);
8764 static void TIG_NORETURN
8765 die(const char *err, ...)
8767 va_list args;
8769 endwin();
8771 va_start(args, err);
8772 fputs("tig: ", stderr);
8773 vfprintf(stderr, err, args);
8774 fputs("\n", stderr);
8775 va_end(args);
8777 exit(1);
8780 static void
8781 warn(const char *msg, ...)
8783 va_list args;
8785 va_start(args, msg);
8786 fputs("tig warning: ", stderr);
8787 vfprintf(stderr, msg, args);
8788 fputs("\n", stderr);
8789 va_end(args);
8792 static int
8793 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8795 const char ***filter_args = data;
8797 return argv_append(filter_args, name) ? OK : ERR;
8800 static void
8801 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8803 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8804 const char **all_argv = NULL;
8806 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8807 !argv_append_array(&all_argv, argv) ||
8808 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8809 die("Failed to split arguments");
8810 argv_free(all_argv);
8811 free(all_argv);
8814 static bool
8815 is_rev_flag(const char *flag)
8817 static const char *rev_flags[] = { GIT_REV_FLAGS };
8818 int i;
8820 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8821 if (!strcmp(flag, rev_flags[i]))
8822 return TRUE;
8824 return FALSE;
8827 static void
8828 filter_options(const char *argv[], bool blame)
8830 const char **flags = NULL;
8832 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8833 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8835 if (flags) {
8836 int next, flags_pos;
8838 for (next = flags_pos = 0; flags && flags[next]; next++) {
8839 const char *flag = flags[next];
8841 if (is_rev_flag(flag))
8842 argv_append(&opt_rev_argv, flag);
8843 else
8844 flags[flags_pos++] = flag;
8847 flags[flags_pos] = NULL;
8849 if (blame)
8850 opt_blame_argv = flags;
8851 else
8852 opt_diff_argv = flags;
8855 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8858 static enum request
8859 parse_options(int argc, const char *argv[], bool pager_mode)
8861 enum request request;
8862 const char *subcommand;
8863 bool seen_dashdash = FALSE;
8864 const char **filter_argv = NULL;
8865 int i;
8867 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8869 if (argc <= 1)
8870 return request;
8872 subcommand = argv[1];
8873 if (!strcmp(subcommand, "status")) {
8874 request = REQ_VIEW_STATUS;
8876 } else if (!strcmp(subcommand, "blame")) {
8877 request = REQ_VIEW_BLAME;
8879 } else if (!strcmp(subcommand, "show")) {
8880 request = REQ_VIEW_DIFF;
8882 } else if (!strcmp(subcommand, "log")) {
8883 request = REQ_VIEW_LOG;
8885 } else if (!strcmp(subcommand, "stash")) {
8886 request = REQ_VIEW_STASH;
8888 } else {
8889 subcommand = NULL;
8892 for (i = 1 + !!subcommand; i < argc; i++) {
8893 const char *opt = argv[i];
8895 // stop parsing our options after -- and let rev-parse handle the rest
8896 if (!seen_dashdash) {
8897 if (!strcmp(opt, "--")) {
8898 seen_dashdash = TRUE;
8899 continue;
8901 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8902 printf("tig version %s\n", TIG_VERSION);
8903 quit(0);
8905 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8906 printf("%s\n", usage);
8907 quit(0);
8909 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8910 opt_lineno = atoi(opt + 1);
8911 continue;
8916 if (!argv_append(&filter_argv, opt))
8917 die("command too long");
8920 if (filter_argv)
8921 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8923 /* Finish validating and setting up blame options */
8924 if (request == REQ_VIEW_BLAME) {
8925 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8926 die("invalid number of options to blame\n\n%s", usage);
8928 if (opt_rev_argv) {
8929 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8932 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8935 return request;
8938 static enum request
8939 open_pager_mode(enum request request)
8941 enum open_flags flags = OPEN_DEFAULT;
8943 if (request == REQ_VIEW_PAGER) {
8944 /* Detect if the user requested the main view. */
8945 if (argv_contains(opt_rev_argv, "--stdin")) {
8946 request = REQ_VIEW_MAIN;
8947 flags |= OPEN_FORWARD_STDIN;
8948 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
8949 request = REQ_VIEW_MAIN;
8950 flags |= OPEN_STDIN;
8951 } else {
8952 flags |= OPEN_STDIN;
8955 } else if (request == REQ_VIEW_DIFF) {
8956 if (argv_contains(opt_rev_argv, "--stdin"))
8957 flags |= OPEN_FORWARD_STDIN;
8960 /* Open the requested view even if the pager mode is enabled so
8961 * the warning message below is displayed correctly. */
8962 open_view(NULL, request, flags);
8964 if (!open_in_pager_mode(flags)) {
8965 close(STDIN_FILENO);
8966 report("Ignoring stdin.");
8969 return REQ_NONE;
8972 static enum request
8973 run_prompt_command(struct view *view, char *cmd) {
8974 enum request request;
8976 if (cmd && string_isnumber(cmd)) {
8977 int lineno = view->pos.lineno + 1;
8979 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8980 select_view_line(view, lineno - 1);
8981 report_clear();
8982 } else {
8983 report("Unable to parse '%s' as a line number", cmd);
8985 } else if (cmd && iscommit(cmd)) {
8986 string_ncopy(opt_search, cmd, strlen(cmd));
8988 request = view_request(view, REQ_JUMP_COMMIT);
8989 if (request == REQ_JUMP_COMMIT) {
8990 report("Jumping to commits is not supported by the '%s' view", view->name);
8993 } else if (cmd && strlen(cmd) == 1) {
8994 request = get_keybinding(&view->ops->keymap, cmd[0]);
8995 return request;
8997 } else if (cmd && cmd[0] == '!') {
8998 struct view *next = VIEW(REQ_VIEW_PAGER);
8999 const char *argv[SIZEOF_ARG];
9000 int argc = 0;
9002 cmd++;
9003 /* When running random commands, initially show the
9004 * command in the title. However, it maybe later be
9005 * overwritten if a commit line is selected. */
9006 string_ncopy(next->ref, cmd, strlen(cmd));
9008 if (!argv_from_string(argv, &argc, cmd)) {
9009 report("Too many arguments");
9010 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9011 report("Argument formatting failed");
9012 } else {
9013 next->dir = NULL;
9014 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9017 } else if (cmd) {
9018 request = get_request(cmd);
9019 if (request != REQ_UNKNOWN)
9020 return request;
9022 char *args = strchr(cmd, ' ');
9023 if (args) {
9024 *args++ = 0;
9025 if (set_option(cmd, args) == OPT_OK) {
9026 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9027 if (!strcmp(cmd, "color"))
9028 init_colors();
9031 return request;
9033 return REQ_NONE;
9037 main(int argc, const char *argv[])
9039 const char *codeset = ENCODING_UTF8;
9040 bool pager_mode = !isatty(STDIN_FILENO);
9041 enum request request = parse_options(argc, argv, pager_mode);
9042 struct view *view;
9043 int i;
9045 signal(SIGINT, quit);
9046 signal(SIGQUIT, quit);
9047 signal(SIGPIPE, SIG_IGN);
9049 if (setlocale(LC_ALL, "")) {
9050 codeset = nl_langinfo(CODESET);
9053 foreach_view(view, i) {
9054 add_keymap(&view->ops->keymap);
9057 if (load_repo_info() == ERR)
9058 die("Failed to load repo info.");
9060 if (load_options() == ERR)
9061 die("Failed to load user config.");
9063 if (load_git_config() == ERR)
9064 die("Failed to load repo config.");
9066 /* Require a git repository unless when running in pager mode. */
9067 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9068 die("Not a git repository");
9070 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9071 char translit[SIZEOF_STR];
9073 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9074 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9075 else
9076 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9077 if (opt_iconv_out == ICONV_NONE)
9078 die("Failed to initialize character set conversion");
9081 if (load_refs(FALSE) == ERR)
9082 die("Failed to load refs.");
9084 init_display();
9086 if (pager_mode)
9087 request = open_pager_mode(request);
9089 while (view_driver(display[current_view], request)) {
9090 int key = get_input(0);
9092 if (key == KEY_ESC)
9093 key = get_input(0) + 0x80;
9095 view = display[current_view];
9096 request = get_keybinding(&view->ops->keymap, key);
9098 /* Some low-level request handling. This keeps access to
9099 * status_win restricted. */
9100 switch (request) {
9101 case REQ_NONE:
9102 report("Unknown key, press %s for help",
9103 get_view_key(view, REQ_VIEW_HELP));
9104 break;
9105 case REQ_PROMPT:
9107 char *cmd = read_prompt(":");
9108 request = run_prompt_command(view, cmd);
9109 break;
9111 case REQ_SEARCH:
9112 case REQ_SEARCH_BACK:
9114 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9115 char *search = read_prompt(prompt);
9117 if (search)
9118 string_ncopy(opt_search, search, strlen(search));
9119 else if (*opt_search)
9120 request = request == REQ_SEARCH ?
9121 REQ_FIND_NEXT :
9122 REQ_FIND_PREV;
9123 else
9124 request = REQ_NONE;
9125 break;
9127 default:
9128 break;
9132 quit(0);
9134 return 0;
9137 /* vim: set ts=8 sw=8 noexpandtab: */