Use memset to clear the format buffer
[tig.git] / tig.c
blob0f28dee4e23c38224fd5a1ded672698815d97ed1
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_stdin = FALSE;
510 static bool opt_focus_child = TRUE;
511 static int opt_diff_context = 3;
512 static char opt_diff_context_arg[9] = "";
513 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
514 static char opt_ignore_space_arg[22] = "";
515 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
516 static char opt_commit_order_arg[22] = "";
517 static bool opt_notes = TRUE;
518 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
519 static int opt_num_interval = 5;
520 static double opt_hscroll = 0.50;
521 static double opt_scale_split_view = 2.0 / 3.0;
522 static double opt_scale_vsplit_view = 0.5;
523 static bool opt_vsplit = FALSE;
524 static int opt_tab_size = 8;
525 static int opt_author_width = AUTHOR_WIDTH;
526 static int opt_filename_width = FILENAME_WIDTH;
527 static char opt_path[SIZEOF_STR] = "";
528 static char opt_file[SIZEOF_STR] = "";
529 static char opt_ref[SIZEOF_REF] = "";
530 static unsigned long opt_goto_line = 0;
531 static char opt_head[SIZEOF_REF] = "";
532 static char opt_remote[SIZEOF_REF] = "";
533 static struct encoding *opt_encoding = NULL;
534 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
535 static iconv_t opt_iconv_out = ICONV_NONE;
536 static char opt_search[SIZEOF_STR] = "";
537 static char opt_cdup[SIZEOF_STR] = "";
538 static char opt_prefix[SIZEOF_STR] = "";
539 static char opt_git_dir[SIZEOF_STR] = "";
540 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
541 static char opt_editor[SIZEOF_STR] = "";
542 static bool opt_editor_lineno = TRUE;
543 static FILE *opt_tty = NULL;
544 static const char **opt_diff_argv = NULL;
545 static const char **opt_rev_argv = NULL;
546 static const char **opt_file_argv = NULL;
547 static const char **opt_blame_argv = NULL;
548 static int opt_lineno = 0;
549 static bool opt_show_id = FALSE;
550 static int opt_id_cols = ID_WIDTH;
551 static bool opt_file_filter = TRUE;
552 static bool opt_show_title_overflow = FALSE;
553 static int opt_title_overflow = 50;
554 static char opt_env_lines[64] = "";
555 static char opt_env_columns[64] = "";
556 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
558 #define is_initial_commit() (!get_ref_head())
559 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
561 static inline int
562 load_refs(bool force)
564 static bool loaded = FALSE;
566 if (force)
567 opt_head[0] = 0;
568 else if (loaded)
569 return OK;
571 loaded = TRUE;
572 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
575 static inline void
576 update_diff_context_arg(int diff_context)
578 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
579 string_ncopy(opt_diff_context_arg, "-U3", 3);
582 static inline void
583 update_ignore_space_arg()
585 if (opt_ignore_space == IGNORE_SPACE_ALL) {
586 string_copy(opt_ignore_space_arg, "--ignore-all-space");
587 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
588 string_copy(opt_ignore_space_arg, "--ignore-space-change");
589 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
590 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
591 } else {
592 string_copy(opt_ignore_space_arg, "");
596 static inline void
597 update_commit_order_arg()
599 if (opt_commit_order == COMMIT_ORDER_TOPO) {
600 string_copy(opt_commit_order_arg, "--topo-order");
601 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
602 string_copy(opt_commit_order_arg, "--date-order");
603 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
604 string_copy(opt_commit_order_arg, "--reverse");
605 } else {
606 string_copy(opt_commit_order_arg, "");
610 static inline void
611 update_notes_arg()
613 if (opt_notes) {
614 string_copy(opt_notes_arg, "--show-notes");
615 } else {
616 /* Notes are disabled by default when passing --pretty args. */
617 string_copy(opt_notes_arg, "");
622 * Line-oriented content detection.
625 #define LINE_INFO \
626 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
627 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
628 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
629 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
630 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
631 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
632 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
633 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
634 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
635 LINE(DIFF_DELETED_FILE_MODE, \
636 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
637 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
638 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
639 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
640 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
641 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
642 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
644 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
645 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
646 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
647 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
648 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
649 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
650 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
651 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
652 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
653 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
654 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
655 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
656 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
657 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
658 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
659 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
660 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
661 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
662 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
663 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
664 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
665 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
666 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
667 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
668 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
669 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
670 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
671 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
672 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
673 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
674 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
675 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
676 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
677 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
678 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
679 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
680 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
681 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
682 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
683 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
684 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
685 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
686 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
687 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
688 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
689 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
690 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
691 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
692 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
693 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
694 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
695 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
696 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
697 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
698 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
699 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
700 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
701 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
702 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
703 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
704 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
706 enum line_type {
707 #define LINE(type, line, fg, bg, attr) \
708 LINE_##type
709 LINE_INFO,
710 LINE_NONE
711 #undef LINE
714 struct line_info {
715 const char *name; /* Option name. */
716 int namelen; /* Size of option name. */
717 const char *line; /* The start of line to match. */
718 int linelen; /* Size of string to match. */
719 int fg, bg, attr; /* Color and text attributes for the lines. */
720 int color_pair;
723 static struct line_info line_info[] = {
724 #define LINE(type, line, fg, bg, attr) \
725 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
726 LINE_INFO
727 #undef LINE
730 static struct line_info **color_pair;
731 static size_t color_pairs;
733 static struct line_info *custom_color;
734 static size_t custom_colors;
736 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
737 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
739 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
740 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
742 /* Color IDs must be 1 or higher. [GH #15] */
743 #define COLOR_ID(line_type) ((line_type) + 1)
745 static enum line_type
746 get_line_type(const char *line)
748 int linelen = strlen(line);
749 enum line_type type;
751 for (type = 0; type < custom_colors; type++)
752 /* Case insensitive search matches Signed-off-by lines better. */
753 if (linelen >= custom_color[type].linelen &&
754 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
755 return TO_CUSTOM_COLOR_TYPE(type);
757 for (type = 0; type < ARRAY_SIZE(line_info); type++)
758 /* Case insensitive search matches Signed-off-by lines better. */
759 if (linelen >= line_info[type].linelen &&
760 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
761 return type;
763 return LINE_DEFAULT;
766 static enum line_type
767 get_line_type_from_ref(const struct ref *ref)
769 if (ref->head)
770 return LINE_MAIN_HEAD;
771 else if (ref->ltag)
772 return LINE_MAIN_LOCAL_TAG;
773 else if (ref->tag)
774 return LINE_MAIN_TAG;
775 else if (ref->tracked)
776 return LINE_MAIN_TRACKED;
777 else if (ref->remote)
778 return LINE_MAIN_REMOTE;
779 else if (ref->replace)
780 return LINE_MAIN_REPLACE;
782 return LINE_MAIN_REF;
785 static inline struct line_info *
786 get_line(enum line_type type)
788 if (type > LINE_NONE) {
789 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
790 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
791 } else {
792 assert(type < ARRAY_SIZE(line_info));
793 return &line_info[type];
797 static inline int
798 get_line_color(enum line_type type)
800 return COLOR_ID(get_line(type)->color_pair);
803 static inline int
804 get_line_attr(enum line_type type)
806 struct line_info *info = get_line(type);
808 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
811 static struct line_info *
812 get_line_info(const char *name)
814 size_t namelen = strlen(name);
815 enum line_type type;
817 for (type = 0; type < ARRAY_SIZE(line_info); type++)
818 if (enum_equals(line_info[type], name, namelen))
819 return &line_info[type];
821 return NULL;
824 static struct line_info *
825 add_custom_color(const char *quoted_line)
827 struct line_info *info;
828 char *line;
829 size_t linelen;
831 if (!realloc_custom_color(&custom_color, custom_colors, 1))
832 die("Failed to alloc custom line info");
834 linelen = strlen(quoted_line) - 1;
835 line = malloc(linelen);
836 if (!line)
837 return NULL;
839 strncpy(line, quoted_line + 1, linelen);
840 line[linelen - 1] = 0;
842 info = &custom_color[custom_colors++];
843 info->name = info->line = line;
844 info->namelen = info->linelen = strlen(line);
846 return info;
849 static void
850 init_line_info_color_pair(struct line_info *info, enum line_type type,
851 int default_bg, int default_fg)
853 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
854 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
855 int i;
857 for (i = 0; i < color_pairs; i++) {
858 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
859 info->color_pair = i;
860 return;
864 if (!realloc_color_pair(&color_pair, color_pairs, 1))
865 die("Failed to alloc color pair");
867 color_pair[color_pairs] = info;
868 info->color_pair = color_pairs++;
869 init_pair(COLOR_ID(info->color_pair), fg, bg);
872 static void
873 init_colors(void)
875 int default_bg = line_info[LINE_DEFAULT].bg;
876 int default_fg = line_info[LINE_DEFAULT].fg;
877 enum line_type type;
879 start_color();
881 if (assume_default_colors(default_fg, default_bg) == ERR) {
882 default_bg = COLOR_BLACK;
883 default_fg = COLOR_WHITE;
886 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
887 struct line_info *info = &line_info[type];
889 init_line_info_color_pair(info, type, default_bg, default_fg);
892 for (type = 0; type < custom_colors; type++) {
893 struct line_info *info = &custom_color[type];
895 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
896 default_bg, default_fg);
900 struct line {
901 enum line_type type;
902 unsigned int lineno:24;
904 /* State flags */
905 unsigned int selected:1;
906 unsigned int dirty:1;
907 unsigned int cleareol:1;
908 unsigned int wrapped:1;
910 unsigned int user_flags:6;
911 void *data; /* User data */
916 * Keys
919 struct keybinding {
920 int alias;
921 enum request request;
924 static struct keybinding default_keybindings[] = {
925 /* View switching */
926 { 'm', REQ_VIEW_MAIN },
927 { 'd', REQ_VIEW_DIFF },
928 { 'l', REQ_VIEW_LOG },
929 { 't', REQ_VIEW_TREE },
930 { 'f', REQ_VIEW_BLOB },
931 { 'B', REQ_VIEW_BLAME },
932 { 'H', REQ_VIEW_BRANCH },
933 { 'p', REQ_VIEW_PAGER },
934 { 'h', REQ_VIEW_HELP },
935 { 'S', REQ_VIEW_STATUS },
936 { 'c', REQ_VIEW_STAGE },
937 { 'y', REQ_VIEW_STASH },
939 /* View manipulation */
940 { 'q', REQ_VIEW_CLOSE },
941 { KEY_TAB, REQ_VIEW_NEXT },
942 { KEY_RETURN, REQ_ENTER },
943 { KEY_UP, REQ_PREVIOUS },
944 { KEY_CTL('P'), REQ_PREVIOUS },
945 { KEY_DOWN, REQ_NEXT },
946 { KEY_CTL('N'), REQ_NEXT },
947 { 'R', REQ_REFRESH },
948 { KEY_F(5), REQ_REFRESH },
949 { 'O', REQ_MAXIMIZE },
950 { ',', REQ_PARENT },
952 /* View specific */
953 { 'u', REQ_STATUS_UPDATE },
954 { '!', REQ_STATUS_REVERT },
955 { 'M', REQ_STATUS_MERGE },
956 { '1', REQ_STAGE_UPDATE_LINE },
957 { '@', REQ_STAGE_NEXT },
958 { '[', REQ_DIFF_CONTEXT_DOWN },
959 { ']', REQ_DIFF_CONTEXT_UP },
961 /* Cursor navigation */
962 { 'k', REQ_MOVE_UP },
963 { 'j', REQ_MOVE_DOWN },
964 { KEY_HOME, REQ_MOVE_FIRST_LINE },
965 { KEY_END, REQ_MOVE_LAST_LINE },
966 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
967 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
968 { ' ', REQ_MOVE_PAGE_DOWN },
969 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
970 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
971 { 'b', REQ_MOVE_PAGE_UP },
972 { '-', REQ_MOVE_PAGE_UP },
974 /* Scrolling */
975 { '|', REQ_SCROLL_FIRST_COL },
976 { KEY_LEFT, REQ_SCROLL_LEFT },
977 { KEY_RIGHT, REQ_SCROLL_RIGHT },
978 { KEY_IC, REQ_SCROLL_LINE_UP },
979 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
980 { KEY_DC, REQ_SCROLL_LINE_DOWN },
981 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
982 { 'w', REQ_SCROLL_PAGE_UP },
983 { 's', REQ_SCROLL_PAGE_DOWN },
985 /* Searching */
986 { '/', REQ_SEARCH },
987 { '?', REQ_SEARCH_BACK },
988 { 'n', REQ_FIND_NEXT },
989 { 'N', REQ_FIND_PREV },
991 /* Misc */
992 { 'Q', REQ_QUIT },
993 { 'z', REQ_STOP_LOADING },
994 { 'v', REQ_SHOW_VERSION },
995 { 'r', REQ_SCREEN_REDRAW },
996 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
997 { 'o', REQ_OPTIONS },
998 { '.', REQ_TOGGLE_LINENO },
999 { 'D', REQ_TOGGLE_DATE },
1000 { 'A', REQ_TOGGLE_AUTHOR },
1001 { 'g', REQ_TOGGLE_REV_GRAPH },
1002 { '~', REQ_TOGGLE_GRAPHIC },
1003 { '#', REQ_TOGGLE_FILENAME },
1004 { 'F', REQ_TOGGLE_REFS },
1005 { 'I', REQ_TOGGLE_SORT_ORDER },
1006 { 'i', REQ_TOGGLE_SORT_FIELD },
1007 { 'W', REQ_TOGGLE_IGNORE_SPACE },
1008 { 'X', REQ_TOGGLE_ID },
1009 { '%', REQ_TOGGLE_FILES },
1010 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
1011 { ':', REQ_PROMPT },
1012 { 'e', REQ_EDIT },
1015 struct keymap {
1016 const char *name;
1017 struct keymap *next;
1018 struct keybinding *data;
1019 size_t size;
1020 bool hidden;
1023 static struct keymap generic_keymap = { "generic" };
1024 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
1026 static struct keymap *keymaps = &generic_keymap;
1028 static void
1029 add_keymap(struct keymap *keymap)
1031 keymap->next = keymaps;
1032 keymaps = keymap;
1035 static struct keymap *
1036 get_keymap(const char *name)
1038 struct keymap *keymap = keymaps;
1040 while (keymap) {
1041 if (!strcasecmp(keymap->name, name))
1042 return keymap;
1043 keymap = keymap->next;
1046 return NULL;
1050 static void
1051 add_keybinding(struct keymap *table, enum request request, int key)
1053 size_t i;
1055 for (i = 0; i < table->size; i++) {
1056 if (table->data[i].alias == key) {
1057 table->data[i].request = request;
1058 return;
1062 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1063 if (!table->data)
1064 die("Failed to allocate keybinding");
1065 table->data[table->size].alias = key;
1066 table->data[table->size++].request = request;
1068 if (request == REQ_NONE && is_generic_keymap(table)) {
1069 int i;
1071 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1072 if (default_keybindings[i].alias == key)
1073 default_keybindings[i].request = REQ_NONE;
1077 /* Looks for a key binding first in the given map, then in the generic map, and
1078 * lastly in the default keybindings. */
1079 static enum request
1080 get_keybinding(struct keymap *keymap, int key)
1082 size_t i;
1084 for (i = 0; i < keymap->size; i++)
1085 if (keymap->data[i].alias == key)
1086 return keymap->data[i].request;
1088 for (i = 0; i < generic_keymap.size; i++)
1089 if (generic_keymap.data[i].alias == key)
1090 return generic_keymap.data[i].request;
1092 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1093 if (default_keybindings[i].alias == key)
1094 return default_keybindings[i].request;
1096 return (enum request) key;
1100 struct key {
1101 const char *name;
1102 int value;
1105 static const struct key key_table[] = {
1106 { "Enter", KEY_RETURN },
1107 { "Space", ' ' },
1108 { "Backspace", KEY_BACKSPACE },
1109 { "Tab", KEY_TAB },
1110 { "Escape", KEY_ESC },
1111 { "Left", KEY_LEFT },
1112 { "Right", KEY_RIGHT },
1113 { "Up", KEY_UP },
1114 { "Down", KEY_DOWN },
1115 { "Insert", KEY_IC },
1116 { "Delete", KEY_DC },
1117 { "Hash", '#' },
1118 { "Home", KEY_HOME },
1119 { "End", KEY_END },
1120 { "PageUp", KEY_PPAGE },
1121 { "PageDown", KEY_NPAGE },
1122 { "F1", KEY_F(1) },
1123 { "F2", KEY_F(2) },
1124 { "F3", KEY_F(3) },
1125 { "F4", KEY_F(4) },
1126 { "F5", KEY_F(5) },
1127 { "F6", KEY_F(6) },
1128 { "F7", KEY_F(7) },
1129 { "F8", KEY_F(8) },
1130 { "F9", KEY_F(9) },
1131 { "F10", KEY_F(10) },
1132 { "F11", KEY_F(11) },
1133 { "F12", KEY_F(12) },
1136 static int
1137 get_key_value(const char *name)
1139 int i;
1141 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1142 if (!strcasecmp(key_table[i].name, name))
1143 return key_table[i].value;
1145 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1146 return (int)name[2] + 0x80;
1147 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1148 return (int)name[1] & 0x1f;
1149 if (strlen(name) == 1 && isprint(*name))
1150 return (int) *name;
1151 return ERR;
1154 static const char *
1155 get_key_name(int key_value)
1157 static char key_char[] = "'X'\0";
1158 const char *seq = NULL;
1159 int key;
1161 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1162 if (key_table[key].value == key_value)
1163 seq = key_table[key].name;
1165 if (seq == NULL && key_value < 0x7f) {
1166 char *s = key_char + 1;
1168 if (key_value >= 0x20) {
1169 *s++ = key_value;
1170 } else {
1171 *s++ = '^';
1172 *s++ = 0x40 | (key_value & 0x1f);
1174 *s++ = '\'';
1175 *s++ = '\0';
1176 seq = key_char;
1179 return seq ? seq : "(no key)";
1182 static bool
1183 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1185 const char *sep = *pos > 0 ? ", " : "";
1186 const char *keyname = get_key_name(keybinding->alias);
1188 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1191 static bool
1192 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1193 struct keymap *keymap, bool all)
1195 int i;
1197 for (i = 0; i < keymap->size; i++) {
1198 if (keymap->data[i].request == request) {
1199 if (!append_key(buf, pos, &keymap->data[i]))
1200 return FALSE;
1201 if (!all)
1202 break;
1206 return TRUE;
1209 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1211 static const char *
1212 get_keys(struct keymap *keymap, enum request request, bool all)
1214 static char buf[BUFSIZ];
1215 size_t pos = 0;
1216 int i;
1218 buf[pos] = 0;
1220 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1221 return "Too many keybindings!";
1222 if (pos > 0 && !all)
1223 return buf;
1225 if (!is_generic_keymap(keymap)) {
1226 /* Only the generic keymap includes the default keybindings when
1227 * listing all keys. */
1228 if (all)
1229 return buf;
1231 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1232 return "Too many keybindings!";
1233 if (pos)
1234 return buf;
1237 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1238 if (default_keybindings[i].request == request) {
1239 if (!append_key(buf, &pos, &default_keybindings[i]))
1240 return "Too many keybindings!";
1241 if (!all)
1242 return buf;
1246 return buf;
1249 enum run_request_flag {
1250 RUN_REQUEST_DEFAULT = 0,
1251 RUN_REQUEST_FORCE = 1,
1252 RUN_REQUEST_SILENT = 2,
1253 RUN_REQUEST_CONFIRM = 4,
1254 RUN_REQUEST_EXIT = 8,
1255 RUN_REQUEST_INTERNAL = 16,
1258 struct run_request {
1259 struct keymap *keymap;
1260 int key;
1261 const char **argv;
1262 bool silent;
1263 bool confirm;
1264 bool exit;
1265 bool internal;
1268 static struct run_request *run_request;
1269 static size_t run_requests;
1271 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1273 static bool
1274 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1276 bool force = flags & RUN_REQUEST_FORCE;
1277 struct run_request *req;
1279 if (!force && get_keybinding(keymap, key) != key)
1280 return TRUE;
1282 if (!realloc_run_requests(&run_request, run_requests, 1))
1283 return FALSE;
1285 if (!argv_copy(&run_request[run_requests].argv, argv))
1286 return FALSE;
1288 req = &run_request[run_requests++];
1289 req->silent = flags & RUN_REQUEST_SILENT;
1290 req->confirm = flags & RUN_REQUEST_CONFIRM;
1291 req->exit = flags & RUN_REQUEST_EXIT;
1292 req->internal = flags & RUN_REQUEST_INTERNAL;
1293 req->keymap = keymap;
1294 req->key = key;
1296 add_keybinding(keymap, REQ_NONE + run_requests, key);
1297 return TRUE;
1300 static struct run_request *
1301 get_run_request(enum request request)
1303 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1304 return NULL;
1305 return &run_request[request - REQ_NONE - 1];
1308 static void
1309 add_builtin_run_requests(void)
1311 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1312 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1313 const char *commit[] = { "git", "commit", NULL };
1314 const char *gc[] = { "git", "gc", NULL };
1315 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1317 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1318 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1319 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1320 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1321 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1325 * User config file handling.
1328 #define OPT_ERR_INFO \
1329 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1330 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1331 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1332 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1333 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1334 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1335 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1336 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1337 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1338 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1339 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1340 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1341 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1342 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1343 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1344 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1345 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1346 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"), \
1347 OPT_ERR_(HOME_UNRESOLVABLE, "HOME environment variable could not be resolved"),
1349 enum option_code {
1350 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1351 OPT_ERR_INFO
1352 #undef OPT_ERR_
1353 OPT_OK
1356 static const char *option_errors[] = {
1357 #define OPT_ERR_(name, msg) msg
1358 OPT_ERR_INFO
1359 #undef OPT_ERR_
1362 static const struct enum_map color_map[] = {
1363 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1364 COLOR_MAP(DEFAULT),
1365 COLOR_MAP(BLACK),
1366 COLOR_MAP(BLUE),
1367 COLOR_MAP(CYAN),
1368 COLOR_MAP(GREEN),
1369 COLOR_MAP(MAGENTA),
1370 COLOR_MAP(RED),
1371 COLOR_MAP(WHITE),
1372 COLOR_MAP(YELLOW),
1375 static const struct enum_map attr_map[] = {
1376 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1377 ATTR_MAP(NORMAL),
1378 ATTR_MAP(BLINK),
1379 ATTR_MAP(BOLD),
1380 ATTR_MAP(DIM),
1381 ATTR_MAP(REVERSE),
1382 ATTR_MAP(STANDOUT),
1383 ATTR_MAP(UNDERLINE),
1386 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1388 static enum option_code
1389 parse_step(double *opt, const char *arg)
1391 *opt = atoi(arg);
1392 if (!strchr(arg, '%'))
1393 return OPT_OK;
1395 /* "Shift down" so 100% and 1 does not conflict. */
1396 *opt = (*opt - 1) / 100;
1397 if (*opt >= 1.0) {
1398 *opt = 0.99;
1399 return OPT_ERR_INVALID_STEP_VALUE;
1401 if (*opt < 0.0) {
1402 *opt = 1;
1403 return OPT_ERR_INVALID_STEP_VALUE;
1405 return OPT_OK;
1408 static enum option_code
1409 parse_int(int *opt, const char *arg, int min, int max)
1411 int value = atoi(arg);
1413 if (min <= value && value <= max) {
1414 *opt = value;
1415 return OPT_OK;
1418 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1421 #define parse_id(opt, arg) \
1422 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1424 static bool
1425 set_color(int *color, const char *name)
1427 if (map_enum(color, color_map, name))
1428 return TRUE;
1429 if (!prefixcmp(name, "color"))
1430 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1431 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1432 return parse_int(color, name, 0, 255) == OPT_OK;
1435 /* Wants: object fgcolor bgcolor [attribute] */
1436 static enum option_code
1437 option_color_command(int argc, const char *argv[])
1439 struct line_info *info;
1441 if (argc < 3)
1442 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1444 if (*argv[0] == '"' || *argv[0] == '\'') {
1445 info = add_custom_color(argv[0]);
1446 } else {
1447 info = get_line_info(argv[0]);
1449 if (!info) {
1450 static const struct enum_map obsolete[] = {
1451 ENUM_MAP("main-delim", LINE_DELIMITER),
1452 ENUM_MAP("main-date", LINE_DATE),
1453 ENUM_MAP("main-author", LINE_AUTHOR),
1454 ENUM_MAP("blame-id", LINE_ID),
1456 int index;
1458 if (!map_enum(&index, obsolete, argv[0]))
1459 return OPT_ERR_UNKNOWN_COLOR_NAME;
1460 info = &line_info[index];
1463 if (!set_color(&info->fg, argv[1]) ||
1464 !set_color(&info->bg, argv[2]))
1465 return OPT_ERR_UNKNOWN_COLOR;
1467 info->attr = 0;
1468 while (argc-- > 3) {
1469 int attr;
1471 if (!set_attribute(&attr, argv[argc]))
1472 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1473 info->attr |= attr;
1476 return OPT_OK;
1479 static enum option_code
1480 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1482 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1483 ? TRUE : FALSE;
1484 if (matched)
1485 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1486 return OPT_OK;
1489 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1491 static enum option_code
1492 parse_enum_do(unsigned int *opt, const char *arg,
1493 const struct enum_map *map, size_t map_size)
1495 bool is_true;
1497 assert(map_size > 1);
1499 if (map_enum_do(map, map_size, (int *) opt, arg))
1500 return OPT_OK;
1502 parse_bool(&is_true, arg);
1503 *opt = is_true ? map[1].value : map[0].value;
1504 return OPT_OK;
1507 #define parse_enum(opt, arg, map) \
1508 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1510 static enum option_code
1511 parse_string(char *opt, const char *arg, size_t optsize)
1513 int arglen = strlen(arg);
1515 switch (arg[0]) {
1516 case '\"':
1517 case '\'':
1518 if (arglen == 1 || arg[arglen - 1] != arg[0])
1519 return OPT_ERR_UNMATCHED_QUOTATION;
1520 arg += 1; arglen -= 2;
1521 default:
1522 string_ncopy_do(opt, optsize, arg, arglen);
1523 return OPT_OK;
1527 static enum option_code
1528 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1530 char buf[SIZEOF_STR];
1531 enum option_code code = parse_string(buf, arg, sizeof(buf));
1533 if (code == OPT_OK) {
1534 struct encoding *encoding = *encoding_ref;
1536 if (encoding && !priority)
1537 return code;
1538 encoding = encoding_open(buf);
1539 if (encoding)
1540 *encoding_ref = encoding;
1543 return code;
1546 static enum option_code
1547 parse_args(const char ***args, const char *argv[])
1549 if (!argv_copy(args, argv))
1550 return OPT_ERR_OUT_OF_MEMORY;
1551 return OPT_OK;
1554 /* Wants: name = value */
1555 static enum option_code
1556 option_set_command(int argc, const char *argv[])
1558 if (argc < 3)
1559 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1561 if (strcmp(argv[1], "="))
1562 return OPT_ERR_NO_VALUE_ASSIGNED;
1564 if (!strcmp(argv[0], "blame-options"))
1565 return parse_args(&opt_blame_argv, argv + 2);
1567 if (!strcmp(argv[0], "diff-options"))
1568 return parse_args(&opt_diff_argv, argv + 2);
1570 if (argc != 3)
1571 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1573 if (!strcmp(argv[0], "show-author"))
1574 return parse_enum(&opt_author, argv[2], author_map);
1576 if (!strcmp(argv[0], "show-date"))
1577 return parse_enum(&opt_date, argv[2], date_map);
1579 if (!strcmp(argv[0], "show-rev-graph"))
1580 return parse_bool(&opt_rev_graph, argv[2]);
1582 if (!strcmp(argv[0], "show-refs"))
1583 return parse_bool(&opt_show_refs, argv[2]);
1585 if (!strcmp(argv[0], "show-changes"))
1586 return parse_bool(&opt_show_changes, argv[2]);
1588 if (!strcmp(argv[0], "show-notes")) {
1589 bool matched = FALSE;
1590 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1592 if (res == OPT_OK && matched) {
1593 update_notes_arg();
1594 return res;
1597 opt_notes = TRUE;
1598 strcpy(opt_notes_arg, "--show-notes=");
1599 res = parse_string(opt_notes_arg + 8, argv[2],
1600 sizeof(opt_notes_arg) - 8);
1601 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1602 opt_notes_arg[7] = '\0';
1603 return res;
1606 if (!strcmp(argv[0], "show-line-numbers"))
1607 return parse_bool(&opt_line_number, argv[2]);
1609 if (!strcmp(argv[0], "line-graphics"))
1610 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1612 if (!strcmp(argv[0], "line-number-interval"))
1613 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1615 if (!strcmp(argv[0], "author-width"))
1616 return parse_int(&opt_author_width, argv[2], 0, 1024);
1618 if (!strcmp(argv[0], "filename-width"))
1619 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1621 if (!strcmp(argv[0], "show-filename"))
1622 return parse_enum(&opt_filename, argv[2], filename_map);
1624 if (!strcmp(argv[0], "show-file-size"))
1625 return parse_enum(&opt_file_size, argv[2], file_size_map);
1627 if (!strcmp(argv[0], "horizontal-scroll"))
1628 return parse_step(&opt_hscroll, argv[2]);
1630 if (!strcmp(argv[0], "split-view-height"))
1631 return parse_step(&opt_scale_split_view, argv[2]);
1633 if (!strcmp(argv[0], "vertical-split"))
1634 return parse_bool(&opt_vsplit, argv[2]);
1636 if (!strcmp(argv[0], "tab-size"))
1637 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1639 if (!strcmp(argv[0], "diff-context")) {
1640 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1642 if (code == OPT_OK)
1643 update_diff_context_arg(opt_diff_context);
1644 return code;
1647 if (!strcmp(argv[0], "ignore-space")) {
1648 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1650 if (code == OPT_OK)
1651 update_ignore_space_arg();
1652 return code;
1655 if (!strcmp(argv[0], "commit-order")) {
1656 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1658 if (code == OPT_OK)
1659 update_commit_order_arg();
1660 return code;
1663 if (!strcmp(argv[0], "status-untracked-dirs"))
1664 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1666 if (!strcmp(argv[0], "read-git-colors"))
1667 return parse_bool(&opt_read_git_colors, argv[2]);
1669 if (!strcmp(argv[0], "ignore-case"))
1670 return parse_bool(&opt_ignore_case, argv[2]);
1672 if (!strcmp(argv[0], "focus-child"))
1673 return parse_bool(&opt_focus_child, argv[2]);
1675 if (!strcmp(argv[0], "wrap-lines"))
1676 return parse_bool(&opt_wrap_lines, argv[2]);
1678 if (!strcmp(argv[0], "show-id"))
1679 return parse_bool(&opt_show_id, argv[2]);
1681 if (!strcmp(argv[0], "id-width"))
1682 return parse_id(&opt_id_cols, argv[2]);
1684 if (!strcmp(argv[0], "title-overflow")) {
1685 bool matched;
1686 enum option_code code;
1689 * "title-overflow" is considered a boolint.
1690 * We try to parse it as a boolean (and set the value to 50 if true),
1691 * otherwise we parse it as an integer and use the given value.
1693 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1694 if (code == OPT_OK && matched) {
1695 if (opt_show_title_overflow)
1696 opt_title_overflow = 50;
1697 } else {
1698 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1699 if (code == OPT_OK)
1700 opt_show_title_overflow = TRUE;
1703 return code;
1706 if (!strcmp(argv[0], "editor-line-number"))
1707 return parse_bool(&opt_editor_lineno, argv[2]);
1709 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1712 /* Wants: mode request key */
1713 static enum option_code
1714 option_bind_command(int argc, const char *argv[])
1716 enum request request;
1717 struct keymap *keymap;
1718 int key;
1720 if (argc < 3)
1721 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1723 if (!(keymap = get_keymap(argv[0])))
1724 return OPT_ERR_UNKNOWN_KEY_MAP;
1726 key = get_key_value(argv[1]);
1727 if (key == ERR)
1728 return OPT_ERR_UNKNOWN_KEY;
1730 request = get_request(argv[2]);
1731 if (request == REQ_UNKNOWN) {
1732 static const struct enum_map obsolete[] = {
1733 ENUM_MAP("cherry-pick", REQ_NONE),
1734 ENUM_MAP("screen-resize", REQ_NONE),
1735 ENUM_MAP("tree-parent", REQ_PARENT),
1737 int alias;
1739 if (map_enum(&alias, obsolete, argv[2])) {
1740 if (alias != REQ_NONE)
1741 add_keybinding(keymap, alias, key);
1742 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1746 if (request == REQ_UNKNOWN) {
1747 enum run_request_flag flags = RUN_REQUEST_FORCE;
1749 if (strchr("!?@<", *argv[2])) {
1750 while (*argv[2]) {
1751 if (*argv[2] == '@') {
1752 flags |= RUN_REQUEST_SILENT;
1753 } else if (*argv[2] == '?') {
1754 flags |= RUN_REQUEST_CONFIRM;
1755 } else if (*argv[2] == '<') {
1756 flags |= RUN_REQUEST_EXIT;
1757 } else if (*argv[2] != '!') {
1758 break;
1760 argv[2]++;
1763 } else if (*argv[2] == ':') {
1764 argv[2]++;
1765 flags |= RUN_REQUEST_INTERNAL;
1767 } else {
1768 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1771 return add_run_request(keymap, key, argv + 2, flags)
1772 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1775 add_keybinding(keymap, request, key);
1777 return OPT_OK;
1781 static enum option_code load_option_file(const char *path);
1783 static enum option_code
1784 option_source_command(int argc, const char *argv[])
1786 if (argc < 1)
1787 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1789 return load_option_file(argv[0]);
1792 static enum option_code
1793 set_option(const char *opt, char *value)
1795 const char *argv[SIZEOF_ARG];
1796 int argc = 0;
1798 if (!argv_from_string(argv, &argc, value))
1799 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1801 if (!strcmp(opt, "color"))
1802 return option_color_command(argc, argv);
1804 if (!strcmp(opt, "set"))
1805 return option_set_command(argc, argv);
1807 if (!strcmp(opt, "bind"))
1808 return option_bind_command(argc, argv);
1810 if (!strcmp(opt, "source"))
1811 return option_source_command(argc, argv);
1813 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1816 struct config_state {
1817 const char *path;
1818 int lineno;
1819 bool errors;
1822 static int
1823 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1825 struct config_state *config = data;
1826 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1828 config->lineno++;
1830 /* Check for comment markers, since read_properties() will
1831 * only ensure opt and value are split at first " \t". */
1832 optlen = strcspn(opt, "#");
1833 if (optlen == 0)
1834 return OK;
1836 if (opt[optlen] == 0) {
1837 /* Look for comment endings in the value. */
1838 size_t len = strcspn(value, "#");
1840 if (len < valuelen) {
1841 valuelen = len;
1842 value[valuelen] = 0;
1845 status = set_option(opt, value);
1848 if (status != OPT_OK) {
1849 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1850 option_errors[status], (int) optlen, opt);
1851 config->errors = TRUE;
1854 /* Always keep going if errors are encountered. */
1855 return OK;
1858 static enum option_code
1859 load_option_file(const char *path)
1861 struct config_state config = { path, 0, FALSE };
1862 struct io io;
1863 char buf[SIZEOF_STR];
1865 /* Do not read configuration from stdin if set to "" */
1866 if (!path || !strlen(path))
1867 return OPT_OK;
1869 if (!prefixcmp(path, "~/")) {
1870 const char *home = getenv("HOME");
1872 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1873 return OPT_ERR_HOME_UNRESOLVABLE;
1874 path = buf;
1877 /* It's OK that the file doesn't exist. */
1878 if (!io_open(&io, "%s", path))
1879 return OPT_ERR_FILE_DOES_NOT_EXIST;
1881 if (io_load(&io, " \t", read_option, &config) == ERR ||
1882 config.errors == TRUE)
1883 warn("Errors while loading %s.", path);
1884 return OPT_OK;
1887 static int
1888 load_options(void)
1890 const char *tigrc_user = getenv("TIGRC_USER");
1891 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1892 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1893 const bool diff_opts_from_args = !!opt_diff_argv;
1895 if (!tigrc_system)
1896 tigrc_system = SYSCONFDIR "/tigrc";
1897 load_option_file(tigrc_system);
1899 if (!tigrc_user)
1900 tigrc_user = "~/.tigrc";
1901 load_option_file(tigrc_user);
1903 /* Add _after_ loading config files to avoid adding run requests
1904 * that conflict with keybindings. */
1905 add_builtin_run_requests();
1907 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1908 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1909 char buf[SIZEOF_STR];
1910 int argc = 0;
1912 if (!string_format(buf, "%s", tig_diff_opts) ||
1913 !argv_from_string(diff_opts, &argc, buf))
1914 die("TIG_DIFF_OPTS contains too many arguments");
1915 else if (!argv_copy(&opt_diff_argv, diff_opts))
1916 die("Failed to format TIG_DIFF_OPTS arguments");
1919 return OK;
1924 * The viewer
1927 struct view;
1928 struct view_ops;
1930 /* The display array of active views and the index of the current view. */
1931 static struct view *display[2];
1932 static WINDOW *display_win[2];
1933 static WINDOW *display_title[2];
1934 static WINDOW *display_sep;
1936 static unsigned int current_view;
1938 #define foreach_displayed_view(view, i) \
1939 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1941 #define displayed_views() (display[1] != NULL ? 2 : 1)
1943 /* Current head and commit ID */
1944 static char ref_blob[SIZEOF_REF] = "";
1945 static char ref_commit[SIZEOF_REF] = "HEAD";
1946 static char ref_head[SIZEOF_REF] = "HEAD";
1947 static char ref_branch[SIZEOF_REF] = "";
1948 static char ref_status[SIZEOF_STR] = "";
1949 static char ref_stash[SIZEOF_REF] = "";
1951 enum view_flag {
1952 VIEW_NO_FLAGS = 0,
1953 VIEW_ALWAYS_LINENO = 1 << 0,
1954 VIEW_CUSTOM_STATUS = 1 << 1,
1955 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1956 VIEW_ADD_PAGER_REFS = 1 << 3,
1957 VIEW_OPEN_DIFF = 1 << 4,
1958 VIEW_NO_REF = 1 << 5,
1959 VIEW_NO_GIT_DIR = 1 << 6,
1960 VIEW_DIFF_LIKE = 1 << 7,
1961 VIEW_STDIN = 1 << 8,
1962 VIEW_SEND_CHILD_ENTER = 1 << 9,
1963 VIEW_FILE_FILTER = 1 << 10,
1964 VIEW_LOG_LIKE = 1 << 11,
1965 VIEW_STATUS_LIKE = 1 << 12,
1968 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1970 struct position {
1971 unsigned long offset; /* Offset of the window top */
1972 unsigned long col; /* Offset from the window side. */
1973 unsigned long lineno; /* Current line number */
1976 struct view {
1977 const char *name; /* View name */
1978 const char *id; /* Points to either of ref_{head,commit,blob} */
1980 struct view_ops *ops; /* View operations */
1982 char ref[SIZEOF_REF]; /* Hovered commit reference */
1983 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1985 int height, width; /* The width and height of the main window */
1986 WINDOW *win; /* The main window */
1988 /* Navigation */
1989 struct position pos; /* Current position. */
1990 struct position prev_pos; /* Previous position. */
1992 /* Searching */
1993 char grep[SIZEOF_STR]; /* Search string */
1994 regex_t *regex; /* Pre-compiled regexp */
1996 /* If non-NULL, points to the view that opened this view. If this view
1997 * is closed tig will switch back to the parent view. */
1998 struct view *parent;
1999 struct view *prev;
2001 /* Buffering */
2002 size_t lines; /* Total number of lines */
2003 struct line *line; /* Line index */
2004 unsigned int digits; /* Number of digits in the lines member. */
2006 /* Number of lines with custom status, not to be counted in the
2007 * view title. */
2008 unsigned int custom_lines;
2010 /* Drawing */
2011 struct line *curline; /* Line currently being drawn. */
2012 enum line_type curtype; /* Attribute currently used for drawing. */
2013 unsigned long col; /* Column when drawing. */
2014 bool has_scrolled; /* View was scrolled. */
2015 bool force_redraw; /* Whether to force a redraw after reading. */
2017 /* Loading */
2018 const char **argv; /* Shell command arguments. */
2019 const char *dir; /* Directory from which to execute. */
2020 struct io io;
2021 struct io *pipe;
2022 time_t start_time;
2023 time_t update_secs;
2024 struct encoding *encoding;
2025 bool unrefreshable;
2027 /* Private data */
2028 void *private;
2031 enum open_flags {
2032 OPEN_DEFAULT = 0, /* Use default view switching. */
2033 OPEN_SPLIT = 1, /* Split current view. */
2034 OPEN_RELOAD = 4, /* 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. */
2040 struct view_ops {
2041 /* What type of content being displayed. Used in the title bar. */
2042 const char *type;
2043 /* What keymap does this view have */
2044 struct keymap keymap;
2045 /* Flags to control the view behavior. */
2046 enum view_flag flags;
2047 /* Size of private data. */
2048 size_t private_size;
2049 /* Open and reads in all view content. */
2050 bool (*open)(struct view *view, enum open_flags flags);
2051 /* Read one line; updates view->line. */
2052 bool (*read)(struct view *view, char *data);
2053 /* Draw one line; @lineno must be < view->height. */
2054 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
2055 /* Depending on view handle a special requests. */
2056 enum request (*request)(struct view *view, enum request request, struct line *line);
2057 /* Search for regexp in a line. */
2058 bool (*grep)(struct view *view, struct line *line);
2059 /* Select line */
2060 void (*select)(struct view *view, struct line *line);
2061 /* Release resources when reloading the view */
2062 void (*done)(struct view *view);
2065 #define VIEW_OPS(id, name, ref) name##_ops
2066 static struct view_ops VIEW_INFO(VIEW_OPS);
2068 static struct view views[] = {
2069 #define VIEW_DATA(id, name, ref) \
2070 { #name, ref, &name##_ops }
2071 VIEW_INFO(VIEW_DATA)
2074 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2076 #define foreach_view(view, i) \
2077 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2079 #define view_is_displayed(view) \
2080 (view == display[0] || view == display[1])
2082 #define view_has_line(view, line_) \
2083 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2085 static bool
2086 forward_request_to_child(struct view *child, enum request request)
2088 return displayed_views() == 2 && view_is_displayed(child) &&
2089 !strcmp(child->vid, child->id);
2092 static enum request
2093 view_request(struct view *view, enum request request)
2095 if (!view || !view->lines)
2096 return request;
2098 if (request == REQ_ENTER && !opt_focus_child &&
2099 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2100 struct view *child = display[1];
2102 if (forward_request_to_child(child, request)) {
2103 view_request(child, request);
2104 return REQ_NONE;
2108 if (request == REQ_REFRESH && view->unrefreshable) {
2109 report("This view can not be refreshed");
2110 return REQ_NONE;
2113 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2117 * View drawing.
2120 static inline void
2121 set_view_attr(struct view *view, enum line_type type)
2123 if (!view->curline->selected && view->curtype != type) {
2124 (void) wattrset(view->win, get_line_attr(type));
2125 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2126 view->curtype = type;
2130 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2132 static bool
2133 draw_chars(struct view *view, enum line_type type, const char *string,
2134 int max_len, bool use_tilde)
2136 int len = 0;
2137 int col = 0;
2138 int trimmed = FALSE;
2139 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2141 if (max_len <= 0)
2142 return VIEW_MAX_LEN(view) <= 0;
2144 if (opt_iconv_out != ICONV_NONE) {
2145 string = encoding_iconv(opt_iconv_out, string);
2146 if (!string)
2147 return VIEW_MAX_LEN(view) <= 0;
2150 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2152 set_view_attr(view, type);
2153 if (len > 0) {
2154 waddnstr(view->win, string, len);
2156 if (trimmed && use_tilde) {
2157 set_view_attr(view, LINE_DELIMITER);
2158 waddch(view->win, '~');
2159 col++;
2163 view->col += col;
2164 return VIEW_MAX_LEN(view) <= 0;
2167 static bool
2168 draw_space(struct view *view, enum line_type type, int max, int spaces)
2170 static char space[] = " ";
2172 spaces = MIN(max, spaces);
2174 while (spaces > 0) {
2175 int len = MIN(spaces, sizeof(space) - 1);
2177 if (draw_chars(view, type, space, len, FALSE))
2178 return TRUE;
2179 spaces -= len;
2182 return VIEW_MAX_LEN(view) <= 0;
2185 static bool
2186 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2188 static char text[SIZEOF_STR];
2190 do {
2191 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2193 if (draw_chars(view, type, text, max_len, use_tilde))
2194 return TRUE;
2195 string += pos;
2196 } while (*string);
2198 return VIEW_MAX_LEN(view) <= 0;
2201 static bool
2202 draw_text(struct view *view, enum line_type type, const char *string)
2204 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2207 static bool
2208 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2210 if (on) {
2211 int max = MIN(VIEW_MAX_LEN(view), overflow);
2212 int len = strlen(text);
2214 if (draw_text_expanded(view, type, text, max, max < overflow))
2215 return TRUE;
2217 text = len > overflow ? text + overflow : "";
2218 type = LINE_OVERFLOW;
2221 if (*text && draw_text(view, type, text))
2222 return TRUE;
2224 return VIEW_MAX_LEN(view) <= 0;
2227 #define draw_commit_title(view, text, offset) \
2228 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2230 static bool PRINTF_LIKE(3, 4)
2231 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2233 char text[SIZEOF_STR];
2234 int retval;
2236 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2237 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2240 static bool
2241 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2243 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2244 int max = VIEW_MAX_LEN(view);
2245 int i;
2247 if (max < size)
2248 size = max;
2250 set_view_attr(view, type);
2251 /* Using waddch() instead of waddnstr() ensures that
2252 * they'll be rendered correctly for the cursor line. */
2253 for (i = skip; i < size; i++)
2254 waddch(view->win, graphic[i]);
2256 view->col += size;
2257 if (separator) {
2258 if (size < max && skip <= size)
2259 waddch(view->win, ' ');
2260 view->col++;
2263 return VIEW_MAX_LEN(view) <= 0;
2266 enum align {
2267 ALIGN_LEFT,
2268 ALIGN_RIGHT
2271 static bool
2272 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2274 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2275 int col = view->col;
2277 if (!text)
2278 return draw_space(view, type, max, max);
2280 if (align == ALIGN_RIGHT) {
2281 int textlen = strlen(text);
2282 int leftpad = max - textlen - 1;
2284 if (leftpad > 0) {
2285 if (draw_space(view, type, leftpad, leftpad))
2286 return TRUE;
2287 max -= leftpad;
2288 col += leftpad;;
2292 return draw_chars(view, type, text, max - 1, trim)
2293 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2296 static bool PRINTF_LIKE(4, 5)
2297 draw_formatted_field(struct view *view, enum line_type type, int width, const char *format, ...)
2299 char text[SIZEOF_STR];
2300 int retval;
2302 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2303 if (retval < 0)
2304 return VIEW_MAX_LEN(view) <= 0;
2305 return draw_field(view, type, text, width, ALIGN_LEFT, FALSE);
2308 static bool
2309 draw_date(struct view *view, struct time *time)
2311 const char *date = mkdate(time, opt_date);
2312 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2314 if (opt_date == DATE_NO)
2315 return FALSE;
2317 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2320 static bool
2321 draw_author(struct view *view, const struct ident *author)
2323 bool trim = author_trim(opt_author_width);
2324 const char *text = mkauthor(author, opt_author_width, opt_author);
2326 if (opt_author == AUTHOR_NO)
2327 return FALSE;
2329 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2332 static bool
2333 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2335 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2338 static bool
2339 draw_id(struct view *view, const char *id)
2341 if (!opt_show_id)
2342 return FALSE;
2344 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2347 static bool
2348 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2350 bool trim = filename && strlen(filename) >= opt_filename_width;
2352 if (opt_filename == FILENAME_NO)
2353 return FALSE;
2355 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2356 return FALSE;
2358 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2361 static bool
2362 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2364 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2366 if (!width || opt_file_size == FILE_SIZE_NO)
2367 return FALSE;
2369 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2372 static bool
2373 draw_mode(struct view *view, mode_t mode)
2375 const char *str = mkmode(mode);
2377 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2380 static bool
2381 draw_lineno(struct view *view, unsigned int lineno)
2383 char number[10];
2384 int digits3 = view->digits < 3 ? 3 : view->digits;
2385 int max = MIN(VIEW_MAX_LEN(view), digits3);
2386 char *text = NULL;
2387 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2389 if (!opt_line_number)
2390 return FALSE;
2392 lineno += view->pos.offset + 1;
2393 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2394 static char fmt[] = "%1ld";
2396 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2397 if (string_format(number, fmt, lineno))
2398 text = number;
2400 if (text)
2401 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2402 else
2403 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2404 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2407 static bool
2408 draw_refs(struct view *view, struct ref_list *refs)
2410 size_t i;
2412 if (!opt_show_refs || !refs)
2413 return FALSE;
2415 for (i = 0; i < refs->size; i++) {
2416 struct ref *ref = refs->refs[i];
2417 enum line_type type = get_line_type_from_ref(ref);
2419 if (draw_formatted(view, type, "[%s]", ref->name))
2420 return TRUE;
2422 if (draw_text(view, LINE_DEFAULT, " "))
2423 return TRUE;
2426 return FALSE;
2429 static bool
2430 draw_view_line(struct view *view, unsigned int lineno)
2432 struct line *line;
2433 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2435 assert(view_is_displayed(view));
2437 if (view->pos.offset + lineno >= view->lines)
2438 return FALSE;
2440 line = &view->line[view->pos.offset + lineno];
2442 wmove(view->win, lineno, 0);
2443 if (line->cleareol)
2444 wclrtoeol(view->win);
2445 view->col = 0;
2446 view->curline = line;
2447 view->curtype = LINE_NONE;
2448 line->selected = FALSE;
2449 line->dirty = line->cleareol = 0;
2451 if (selected) {
2452 set_view_attr(view, LINE_CURSOR);
2453 line->selected = TRUE;
2454 view->ops->select(view, line);
2457 return view->ops->draw(view, line, lineno);
2460 static void
2461 redraw_view_dirty(struct view *view)
2463 bool dirty = FALSE;
2464 int lineno;
2466 for (lineno = 0; lineno < view->height; lineno++) {
2467 if (view->pos.offset + lineno >= view->lines)
2468 break;
2469 if (!view->line[view->pos.offset + lineno].dirty)
2470 continue;
2471 dirty = TRUE;
2472 if (!draw_view_line(view, lineno))
2473 break;
2476 if (!dirty)
2477 return;
2478 wnoutrefresh(view->win);
2481 static void
2482 redraw_view_from(struct view *view, int lineno)
2484 assert(0 <= lineno && lineno < view->height);
2486 for (; lineno < view->height; lineno++) {
2487 if (!draw_view_line(view, lineno))
2488 break;
2491 wnoutrefresh(view->win);
2494 static void
2495 redraw_view(struct view *view)
2497 werase(view->win);
2498 redraw_view_from(view, 0);
2502 static void
2503 update_view_title(struct view *view)
2505 char buf[SIZEOF_STR];
2506 char state[SIZEOF_STR];
2507 size_t bufpos = 0, statelen = 0;
2508 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2509 struct line *line = &view->line[view->pos.lineno];
2511 assert(view_is_displayed(view));
2513 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2514 line->lineno) {
2515 unsigned int view_lines = view->pos.offset + view->height;
2516 unsigned int lines = view->lines
2517 ? MIN(view_lines, view->lines) * 100 / view->lines
2518 : 0;
2520 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2521 view->ops->type,
2522 line->lineno,
2523 view->lines - view->custom_lines,
2524 lines);
2528 if (view->pipe) {
2529 time_t secs = time(NULL) - view->start_time;
2531 /* Three git seconds are a long time ... */
2532 if (secs > 2)
2533 string_format_from(state, &statelen, " loading %lds", secs);
2536 string_format_from(buf, &bufpos, "[%s]", view->name);
2537 if (*view->ref && bufpos < view->width) {
2538 size_t refsize = strlen(view->ref);
2539 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2541 if (minsize < view->width)
2542 refsize = view->width - minsize + 7;
2543 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2546 if (statelen && bufpos < view->width) {
2547 string_format_from(buf, &bufpos, "%s", state);
2550 if (view == display[current_view])
2551 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2552 else
2553 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2555 mvwaddnstr(window, 0, 0, buf, bufpos);
2556 wclrtoeol(window);
2557 wnoutrefresh(window);
2560 static int
2561 apply_step(double step, int value)
2563 if (step >= 1)
2564 return (int) step;
2565 value *= step + 0.01;
2566 return value ? value : 1;
2569 static void
2570 apply_horizontal_split(struct view *base, struct view *view)
2572 view->width = base->width;
2573 view->height = apply_step(opt_scale_split_view, base->height);
2574 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2575 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2576 base->height -= view->height;
2579 static void
2580 apply_vertical_split(struct view *base, struct view *view)
2582 view->height = base->height;
2583 view->width = apply_step(opt_scale_vsplit_view, base->width);
2584 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2585 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2586 base->width -= view->width;
2589 static void
2590 redraw_display_separator(bool clear)
2592 if (displayed_views() > 1 && opt_vsplit) {
2593 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2595 if (clear)
2596 wclear(display_sep);
2597 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2598 wnoutrefresh(display_sep);
2602 static void
2603 resize_display(void)
2605 int x, y, i;
2606 struct view *base = display[0];
2607 struct view *view = display[1] ? display[1] : display[0];
2609 /* Setup window dimensions */
2611 getmaxyx(stdscr, base->height, base->width);
2612 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2613 string_format(opt_env_lines, "LINES=%d", base->height);
2615 /* Make room for the status window. */
2616 base->height -= 1;
2618 if (view != base) {
2619 if (opt_vsplit) {
2620 apply_vertical_split(base, view);
2622 /* Make room for the separator bar. */
2623 view->width -= 1;
2624 } else {
2625 apply_horizontal_split(base, view);
2628 /* Make room for the title bar. */
2629 view->height -= 1;
2632 /* Make room for the title bar. */
2633 base->height -= 1;
2635 x = y = 0;
2637 foreach_displayed_view (view, i) {
2638 if (!display_win[i]) {
2639 display_win[i] = newwin(view->height, view->width, y, x);
2640 if (!display_win[i])
2641 die("Failed to create %s view", view->name);
2643 scrollok(display_win[i], FALSE);
2645 display_title[i] = newwin(1, view->width, y + view->height, x);
2646 if (!display_title[i])
2647 die("Failed to create title window");
2649 } else {
2650 wresize(display_win[i], view->height, view->width);
2651 mvwin(display_win[i], y, x);
2652 wresize(display_title[i], 1, view->width);
2653 mvwin(display_title[i], y + view->height, x);
2656 if (i > 0 && opt_vsplit) {
2657 if (!display_sep) {
2658 display_sep = newwin(view->height, 1, 0, x - 1);
2659 if (!display_sep)
2660 die("Failed to create separator window");
2662 } else {
2663 wresize(display_sep, view->height, 1);
2664 mvwin(display_sep, 0, x - 1);
2668 view->win = display_win[i];
2670 if (opt_vsplit)
2671 x += view->width + 1;
2672 else
2673 y += view->height + 1;
2676 redraw_display_separator(FALSE);
2679 static void
2680 redraw_display(bool clear)
2682 struct view *view;
2683 int i;
2685 foreach_displayed_view (view, i) {
2686 if (clear)
2687 wclear(view->win);
2688 redraw_view(view);
2689 update_view_title(view);
2692 redraw_display_separator(clear);
2696 * Option management
2699 #define TOGGLE_MENU_INFO(_) \
2700 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2701 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2702 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2703 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2704 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2705 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2706 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2707 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2708 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2709 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2710 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2711 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2712 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2713 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2714 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2716 static enum view_flag
2717 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2719 const struct {
2720 enum request request;
2721 const struct enum_map *map;
2722 size_t map_size;
2723 enum view_flag reload_flags;
2724 } data[] = {
2725 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2726 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2728 const struct menu_item menu[] = {
2729 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2730 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2731 { 0 }
2733 int i = 0;
2735 if (request == REQ_OPTIONS) {
2736 if (!prompt_menu("Toggle option", menu, &i))
2737 return VIEW_NO_FLAGS;
2738 } else {
2739 while (i < ARRAY_SIZE(data) && data[i].request != request)
2740 i++;
2741 if (i >= ARRAY_SIZE(data))
2742 die("Invalid request (%d)", request);
2745 if (data[i].map != NULL) {
2746 unsigned int *opt = menu[i].data;
2748 *opt = (*opt + 1) % data[i].map_size;
2749 if (data[i].map == ignore_space_map) {
2750 update_ignore_space_arg();
2751 string_format_size(msg, SIZEOF_STR,
2752 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2754 } else if (data[i].map == commit_order_map) {
2755 update_commit_order_arg();
2756 string_format_size(msg, SIZEOF_STR,
2757 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2759 } else {
2760 string_format_size(msg, SIZEOF_STR,
2761 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2764 } else {
2765 bool *option = menu[i].data;
2767 *option = !*option;
2768 string_format_size(msg, SIZEOF_STR,
2769 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2772 return data[i].reload_flags;
2777 * Navigation
2780 static bool
2781 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2783 if (lineno >= view->lines)
2784 lineno = view->lines > 0 ? view->lines - 1 : 0;
2786 if (offset > lineno || offset + view->height <= lineno) {
2787 unsigned long half = view->height / 2;
2789 if (lineno > half)
2790 offset = lineno - half;
2791 else
2792 offset = 0;
2795 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2796 view->pos.offset = offset;
2797 view->pos.lineno = lineno;
2798 return TRUE;
2801 return FALSE;
2804 /* Scrolling backend */
2805 static void
2806 do_scroll_view(struct view *view, int lines)
2808 bool redraw_current_line = FALSE;
2810 /* The rendering expects the new offset. */
2811 view->pos.offset += lines;
2813 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2814 assert(lines);
2816 /* Move current line into the view. */
2817 if (view->pos.lineno < view->pos.offset) {
2818 view->pos.lineno = view->pos.offset;
2819 redraw_current_line = TRUE;
2820 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2821 view->pos.lineno = view->pos.offset + view->height - 1;
2822 redraw_current_line = TRUE;
2825 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2827 /* Redraw the whole screen if scrolling is pointless. */
2828 if (view->height < ABS(lines)) {
2829 redraw_view(view);
2831 } else {
2832 int line = lines > 0 ? view->height - lines : 0;
2833 int end = line + ABS(lines);
2835 scrollok(view->win, TRUE);
2836 wscrl(view->win, lines);
2837 scrollok(view->win, FALSE);
2839 while (line < end && draw_view_line(view, line))
2840 line++;
2842 if (redraw_current_line)
2843 draw_view_line(view, view->pos.lineno - view->pos.offset);
2844 wnoutrefresh(view->win);
2847 view->has_scrolled = TRUE;
2848 report_clear();
2851 /* Scroll frontend */
2852 static void
2853 scroll_view(struct view *view, enum request request)
2855 int lines = 1;
2857 assert(view_is_displayed(view));
2859 switch (request) {
2860 case REQ_SCROLL_FIRST_COL:
2861 view->pos.col = 0;
2862 redraw_view_from(view, 0);
2863 report_clear();
2864 return;
2865 case REQ_SCROLL_LEFT:
2866 if (view->pos.col == 0) {
2867 report("Cannot scroll beyond the first column");
2868 return;
2870 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2871 view->pos.col = 0;
2872 else
2873 view->pos.col -= apply_step(opt_hscroll, view->width);
2874 redraw_view_from(view, 0);
2875 report_clear();
2876 return;
2877 case REQ_SCROLL_RIGHT:
2878 view->pos.col += apply_step(opt_hscroll, view->width);
2879 redraw_view(view);
2880 report_clear();
2881 return;
2882 case REQ_SCROLL_PAGE_DOWN:
2883 lines = view->height;
2884 case REQ_SCROLL_LINE_DOWN:
2885 if (view->pos.offset + lines > view->lines)
2886 lines = view->lines - view->pos.offset;
2888 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2889 report("Cannot scroll beyond the last line");
2890 return;
2892 break;
2894 case REQ_SCROLL_PAGE_UP:
2895 lines = view->height;
2896 case REQ_SCROLL_LINE_UP:
2897 if (lines > view->pos.offset)
2898 lines = view->pos.offset;
2900 if (lines == 0) {
2901 report("Cannot scroll beyond the first line");
2902 return;
2905 lines = -lines;
2906 break;
2908 default:
2909 die("request %d not handled in switch", request);
2912 do_scroll_view(view, lines);
2915 /* Cursor moving */
2916 static void
2917 move_view(struct view *view, enum request request)
2919 int scroll_steps = 0;
2920 int steps;
2922 switch (request) {
2923 case REQ_MOVE_FIRST_LINE:
2924 steps = -view->pos.lineno;
2925 break;
2927 case REQ_MOVE_LAST_LINE:
2928 steps = view->lines - view->pos.lineno - 1;
2929 break;
2931 case REQ_MOVE_PAGE_UP:
2932 steps = view->height > view->pos.lineno
2933 ? -view->pos.lineno : -view->height;
2934 break;
2936 case REQ_MOVE_PAGE_DOWN:
2937 steps = view->pos.lineno + view->height >= view->lines
2938 ? view->lines - view->pos.lineno - 1 : view->height;
2939 break;
2941 case REQ_MOVE_UP:
2942 case REQ_PREVIOUS:
2943 steps = -1;
2944 break;
2946 case REQ_MOVE_DOWN:
2947 case REQ_NEXT:
2948 steps = 1;
2949 break;
2951 default:
2952 die("request %d not handled in switch", request);
2955 if (steps <= 0 && view->pos.lineno == 0) {
2956 report("Cannot move beyond the first line");
2957 return;
2959 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2960 report("Cannot move beyond the last line");
2961 return;
2964 /* Move the current line */
2965 view->pos.lineno += steps;
2966 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2968 /* Check whether the view needs to be scrolled */
2969 if (view->pos.lineno < view->pos.offset ||
2970 view->pos.lineno >= view->pos.offset + view->height) {
2971 scroll_steps = steps;
2972 if (steps < 0 && -steps > view->pos.offset) {
2973 scroll_steps = -view->pos.offset;
2975 } else if (steps > 0) {
2976 if (view->pos.lineno == view->lines - 1 &&
2977 view->lines > view->height) {
2978 scroll_steps = view->lines - view->pos.offset - 1;
2979 if (scroll_steps >= view->height)
2980 scroll_steps -= view->height - 1;
2985 if (!view_is_displayed(view)) {
2986 view->pos.offset += scroll_steps;
2987 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2988 view->ops->select(view, &view->line[view->pos.lineno]);
2989 return;
2992 /* Repaint the old "current" line if we be scrolling */
2993 if (ABS(steps) < view->height)
2994 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2996 if (scroll_steps) {
2997 do_scroll_view(view, scroll_steps);
2998 return;
3001 /* Draw the current line */
3002 draw_view_line(view, view->pos.lineno - view->pos.offset);
3004 wnoutrefresh(view->win);
3005 report_clear();
3010 * Searching
3013 static void search_view(struct view *view, enum request request);
3015 static bool
3016 grep_text(struct view *view, const char *text[])
3018 regmatch_t pmatch;
3019 size_t i;
3021 for (i = 0; text[i]; i++)
3022 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
3023 return TRUE;
3024 return FALSE;
3027 static void
3028 select_view_line(struct view *view, unsigned long lineno)
3030 struct position old = view->pos;
3032 if (goto_view_line(view, view->pos.offset, lineno)) {
3033 if (view_is_displayed(view)) {
3034 if (old.offset != view->pos.offset) {
3035 redraw_view(view);
3036 } else {
3037 draw_view_line(view, old.lineno - view->pos.offset);
3038 draw_view_line(view, view->pos.lineno - view->pos.offset);
3039 wnoutrefresh(view->win);
3041 } else {
3042 view->ops->select(view, &view->line[view->pos.lineno]);
3047 static void
3048 find_next(struct view *view, enum request request)
3050 unsigned long lineno = view->pos.lineno;
3051 int direction;
3053 if (!*view->grep) {
3054 if (!*opt_search)
3055 report("No previous search");
3056 else
3057 search_view(view, request);
3058 return;
3061 switch (request) {
3062 case REQ_SEARCH:
3063 case REQ_FIND_NEXT:
3064 direction = 1;
3065 break;
3067 case REQ_SEARCH_BACK:
3068 case REQ_FIND_PREV:
3069 direction = -1;
3070 break;
3072 default:
3073 return;
3076 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
3077 lineno += direction;
3079 /* Note, lineno is unsigned long so will wrap around in which case it
3080 * will become bigger than view->lines. */
3081 for (; lineno < view->lines; lineno += direction) {
3082 if (view->ops->grep(view, &view->line[lineno])) {
3083 select_view_line(view, lineno);
3084 report("Line %ld matches '%s'", lineno + 1, view->grep);
3085 return;
3089 report("No match found for '%s'", view->grep);
3092 static void
3093 search_view(struct view *view, enum request request)
3095 int regex_err;
3096 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3098 if (view->regex) {
3099 regfree(view->regex);
3100 *view->grep = 0;
3101 } else {
3102 view->regex = calloc(1, sizeof(*view->regex));
3103 if (!view->regex)
3104 return;
3107 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3108 if (regex_err != 0) {
3109 char buf[SIZEOF_STR] = "unknown error";
3111 regerror(regex_err, view->regex, buf, sizeof(buf));
3112 report("Search failed: %s", buf);
3113 return;
3116 string_copy(view->grep, opt_search);
3118 find_next(view, request);
3122 * Incremental updating
3125 static inline bool
3126 check_position(struct position *pos)
3128 return pos->lineno || pos->col || pos->offset;
3131 static inline void
3132 clear_position(struct position *pos)
3134 memset(pos, 0, sizeof(*pos));
3137 static void
3138 reset_view(struct view *view)
3140 int i;
3142 if (view->ops->done)
3143 view->ops->done(view);
3145 for (i = 0; i < view->lines; i++)
3146 free(view->line[i].data);
3147 free(view->line);
3149 view->prev_pos = view->pos;
3150 clear_position(&view->pos);
3152 view->line = NULL;
3153 view->lines = 0;
3154 view->vid[0] = 0;
3155 view->custom_lines = 0;
3156 view->update_secs = 0;
3159 struct format_context {
3160 struct view *view;
3161 char buf[SIZEOF_STR];
3162 size_t bufpos;
3163 bool file_filter;
3166 static bool
3167 format_expand_arg(struct format_context *format, const char *name)
3169 static struct {
3170 const char *name;
3171 size_t namelen;
3172 const char *value;
3173 const char *value_if_empty;
3174 } vars[] = {
3175 #define FORMAT_VAR(name, value, value_if_empty) \
3176 { name, STRING_SIZE(name), value, value_if_empty }
3177 FORMAT_VAR("%(directory)", opt_path, "."),
3178 FORMAT_VAR("%(file)", opt_file, ""),
3179 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3180 FORMAT_VAR("%(head)", ref_head, ""),
3181 FORMAT_VAR("%(commit)", ref_commit, ""),
3182 FORMAT_VAR("%(blob)", ref_blob, ""),
3183 FORMAT_VAR("%(branch)", ref_branch, ""),
3184 FORMAT_VAR("%(stash)", ref_stash, ""),
3186 int i;
3188 if (!prefixcmp(name, "%(prompt)")) {
3189 const char *value = read_prompt("Command argument: ");
3191 return string_format_from(format->buf, &format->bufpos, "%s", value);
3194 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3195 const char *value;
3197 if (strncmp(name, vars[i].name, vars[i].namelen))
3198 continue;
3200 if (vars[i].value == opt_file && !format->file_filter)
3201 return TRUE;
3203 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3204 if (!*value)
3205 return TRUE;
3207 return string_format_from(format->buf, &format->bufpos, "%s", value);
3210 report("Unknown replacement: `%s`", name);
3211 return NULL;
3214 static bool
3215 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3217 memset(format->buf, 0, sizeof(format->buf));
3218 format->bufpos = 0;
3220 while (arg) {
3221 char *next = strstr(arg, "%(");
3222 int len = next ? next - arg : strlen(arg);
3224 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3225 return FALSE;
3227 if (next && !format_expand_arg(format, next))
3228 return FALSE;
3230 arg = next ? strchr(next, ')') + 1 : NULL;
3233 return argv_append(dst_argv, format->buf);
3236 static bool
3237 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3239 int argc;
3241 if (!src_argv)
3242 return TRUE;
3244 for (argc = 0; src_argv[argc]; argc++)
3245 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3246 return FALSE;
3248 return src_argv[argc] == NULL;
3251 static bool
3252 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3254 struct format_context format = { view, "", 0, file_filter };
3255 int argc;
3257 argv_free(*dst_argv);
3259 for (argc = 0; src_argv[argc]; argc++) {
3260 const char *arg = src_argv[argc];
3262 if (!strcmp(arg, "%(fileargs)")) {
3263 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3264 break;
3266 } else if (!strcmp(arg, "%(diffargs)")) {
3267 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3268 break;
3270 } else if (!strcmp(arg, "%(blameargs)")) {
3271 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3272 break;
3274 } else if (!strcmp(arg, "%(revargs)") ||
3275 (first && !strcmp(arg, "%(commit)"))) {
3276 if (!argv_append_array(dst_argv, opt_rev_argv))
3277 break;
3279 } else if (!format_append_arg(&format, dst_argv, arg)) {
3280 break;
3284 return src_argv[argc] == NULL;
3287 static bool
3288 restore_view_position(struct view *view)
3290 /* A view without a previous view is the first view */
3291 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3292 select_view_line(view, opt_lineno - 1);
3293 opt_lineno = 0;
3296 /* Ensure that the view position is in a valid state. */
3297 if (!check_position(&view->prev_pos) ||
3298 (view->pipe && view->lines <= view->prev_pos.lineno))
3299 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3301 /* Changing the view position cancels the restoring. */
3302 /* FIXME: Changing back to the first line is not detected. */
3303 if (check_position(&view->pos)) {
3304 clear_position(&view->prev_pos);
3305 return FALSE;
3308 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3309 view_is_displayed(view))
3310 werase(view->win);
3312 view->pos.col = view->prev_pos.col;
3313 clear_position(&view->prev_pos);
3315 return TRUE;
3318 static void
3319 end_update(struct view *view, bool force)
3321 if (!view->pipe)
3322 return;
3323 while (!view->ops->read(view, NULL))
3324 if (!force)
3325 return;
3326 if (force)
3327 io_kill(view->pipe);
3328 io_done(view->pipe);
3329 view->pipe = NULL;
3332 static void
3333 setup_update(struct view *view, const char *vid)
3335 reset_view(view);
3336 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3337 string_ncopy(view->vid, vid, strlen(vid));
3338 view->pipe = &view->io;
3339 view->start_time = time(NULL);
3342 static bool
3343 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3345 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3346 bool extra = !!(flags & (OPEN_EXTRA));
3347 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3348 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3349 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3351 opt_stdin = FALSE;
3353 if ((!reload && !strcmp(view->vid, view->id)) ||
3354 ((flags & OPEN_REFRESH) && view->unrefreshable))
3355 return TRUE;
3357 if (view->pipe) {
3358 if (extra)
3359 io_done(view->pipe);
3360 else
3361 end_update(view, TRUE);
3364 view->unrefreshable = use_stdin;
3366 if (!refresh && argv) {
3367 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3369 view->dir = dir;
3370 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3371 report("Failed to format %s arguments", view->name);
3372 return FALSE;
3375 /* Put the current ref_* value to the view title ref
3376 * member. This is needed by the blob view. Most other
3377 * views sets it automatically after loading because the
3378 * first line is a commit line. */
3379 string_copy_rev(view->ref, view->id);
3382 if (view->argv && view->argv[0] &&
3383 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3384 report("Failed to open %s view", view->name);
3385 return FALSE;
3388 if (!extra)
3389 setup_update(view, view->id);
3391 return TRUE;
3394 static bool
3395 update_view(struct view *view)
3397 char *line;
3398 /* Clear the view and redraw everything since the tree sorting
3399 * might have rearranged things. */
3400 bool redraw = view->lines == 0;
3401 bool can_read = TRUE;
3402 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3404 if (!view->pipe)
3405 return TRUE;
3407 if (!io_can_read(view->pipe, FALSE)) {
3408 if (view->lines == 0 && view_is_displayed(view)) {
3409 time_t secs = time(NULL) - view->start_time;
3411 if (secs > 1 && secs > view->update_secs) {
3412 if (view->update_secs == 0)
3413 redraw_view(view);
3414 update_view_title(view);
3415 view->update_secs = secs;
3418 return TRUE;
3421 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3422 if (encoding) {
3423 line = encoding_convert(encoding, line);
3426 if (!view->ops->read(view, line)) {
3427 report("Allocation failure");
3428 end_update(view, TRUE);
3429 return FALSE;
3434 int digits = count_digits(view->lines);
3436 /* Keep the displayed view in sync with line number scaling. */
3437 if (digits != view->digits) {
3438 view->digits = digits;
3439 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3440 redraw = TRUE;
3444 if (io_error(view->pipe)) {
3445 report("Failed to read: %s", io_strerror(view->pipe));
3446 end_update(view, TRUE);
3448 } else if (io_eof(view->pipe)) {
3449 end_update(view, FALSE);
3452 if (restore_view_position(view))
3453 redraw = TRUE;
3455 if (!view_is_displayed(view))
3456 return TRUE;
3458 if (redraw || view->force_redraw)
3459 redraw_view_from(view, 0);
3460 else
3461 redraw_view_dirty(view);
3462 view->force_redraw = FALSE;
3464 /* Update the title _after_ the redraw so that if the redraw picks up a
3465 * commit reference in view->ref it'll be available here. */
3466 update_view_title(view);
3467 return TRUE;
3470 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3472 static struct line *
3473 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3475 struct line *line;
3477 if (!realloc_lines(&view->line, view->lines, 1))
3478 return NULL;
3480 if (data_size) {
3481 void *alloc_data = calloc(1, data_size);
3483 if (!alloc_data)
3484 return NULL;
3486 if (data)
3487 memcpy(alloc_data, data, data_size);
3488 data = alloc_data;
3491 line = &view->line[view->lines++];
3492 memset(line, 0, sizeof(*line));
3493 line->type = type;
3494 line->data = (void *) data;
3495 line->dirty = 1;
3497 if (custom)
3498 view->custom_lines++;
3499 else
3500 line->lineno = view->lines - view->custom_lines;
3502 return line;
3505 static struct line *
3506 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3508 struct line *line = add_line(view, NULL, type, data_size, custom);
3510 if (line)
3511 *ptr = line->data;
3512 return line;
3515 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3516 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3518 static struct line *
3519 add_line_nodata(struct view *view, enum line_type type)
3521 return add_line(view, NULL, type, 0, FALSE);
3524 static struct line *
3525 add_line_text(struct view *view, const char *text, enum line_type type)
3527 return add_line(view, text, type, strlen(text) + 1, FALSE);
3530 static struct line * PRINTF_LIKE(3, 4)
3531 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3533 char buf[SIZEOF_STR];
3534 int retval;
3536 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3537 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3541 * View opening
3544 static void
3545 split_view(struct view *prev, struct view *view)
3547 display[1] = view;
3548 current_view = opt_focus_child ? 1 : 0;
3549 view->parent = prev;
3550 resize_display();
3552 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3553 /* Take the title line into account. */
3554 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3556 /* Scroll the view that was split if the current line is
3557 * outside the new limited view. */
3558 do_scroll_view(prev, lines);
3561 if (view != prev && view_is_displayed(prev)) {
3562 /* "Blur" the previous view. */
3563 update_view_title(prev);
3567 static void
3568 maximize_view(struct view *view, bool redraw)
3570 memset(display, 0, sizeof(display));
3571 current_view = 0;
3572 display[current_view] = view;
3573 resize_display();
3574 if (redraw) {
3575 redraw_display(FALSE);
3576 report_clear();
3580 static void
3581 load_view(struct view *view, struct view *prev, enum open_flags flags)
3583 if (view->pipe)
3584 end_update(view, TRUE);
3585 if (view->ops->private_size) {
3586 if (!view->private)
3587 view->private = calloc(1, view->ops->private_size);
3588 else
3589 memset(view->private, 0, view->ops->private_size);
3592 /* When prev == view it means this is the first loaded view. */
3593 if (prev && view != prev) {
3594 view->prev = prev;
3597 if (!view->ops->open(view, flags))
3598 return;
3600 if (prev) {
3601 bool split = !!(flags & OPEN_SPLIT);
3603 if (split) {
3604 split_view(prev, view);
3605 } else {
3606 maximize_view(view, FALSE);
3610 restore_view_position(view);
3612 if (view->pipe && view->lines == 0) {
3613 /* Clear the old view and let the incremental updating refill
3614 * the screen. */
3615 werase(view->win);
3616 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3617 clear_position(&view->prev_pos);
3618 report_clear();
3619 } else if (view_is_displayed(view)) {
3620 redraw_view(view);
3621 report_clear();
3625 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3626 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3628 static void
3629 open_view(struct view *prev, enum request request, enum open_flags flags)
3631 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3632 struct view *view = VIEW(request);
3633 int nviews = displayed_views();
3635 assert(flags ^ OPEN_REFRESH);
3637 if (view == prev && nviews == 1 && !reload) {
3638 report("Already in %s view", view->name);
3639 return;
3642 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3643 report("The %s view is disabled in pager view", view->name);
3644 return;
3647 load_view(view, prev ? prev : view, flags);
3650 static void
3651 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3653 enum request request = view - views + REQ_OFFSET + 1;
3655 if (view->pipe)
3656 end_update(view, TRUE);
3657 view->dir = dir;
3659 if (!argv_copy(&view->argv, argv)) {
3660 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3661 } else {
3662 open_view(prev, request, flags | OPEN_PREPARED);
3666 static bool
3667 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3669 bool ok;
3671 def_prog_mode(); /* save current tty modes */
3672 endwin(); /* restore original tty modes */
3673 ok = io_run_fg(argv, dir);
3674 if (confirm) {
3675 if (!ok && *notice)
3676 fprintf(stderr, "%s", notice);
3677 fprintf(stderr, "Press Enter to continue");
3678 getc(opt_tty);
3680 reset_prog_mode();
3681 redraw_display(TRUE);
3682 return ok;
3685 static void
3686 open_mergetool(const char *file)
3688 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3690 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3693 #define EDITOR_LINENO_MSG \
3694 "*** Your editor reported an error while opening the file.\n" \
3695 "*** This is probably because it doesn't support the line\n" \
3696 "*** number argument added automatically. The line number\n" \
3697 "*** has been disabled for now. You can permanently disable\n" \
3698 "*** it by adding the following line to ~/.tigrc\n" \
3699 "*** set editor-line-number = no\n"
3701 static void
3702 open_editor(const char *file, unsigned int lineno)
3704 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3705 char editor_cmd[SIZEOF_STR];
3706 char lineno_cmd[SIZEOF_STR];
3707 const char *editor;
3708 int argc = 0;
3710 editor = getenv("GIT_EDITOR");
3711 if (!editor && *opt_editor)
3712 editor = opt_editor;
3713 if (!editor)
3714 editor = getenv("VISUAL");
3715 if (!editor)
3716 editor = getenv("EDITOR");
3717 if (!editor)
3718 editor = "vi";
3720 string_ncopy(editor_cmd, editor, strlen(editor));
3721 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3722 report("Failed to read editor command");
3723 return;
3726 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3727 editor_argv[argc++] = lineno_cmd;
3728 editor_argv[argc] = file;
3729 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3730 opt_editor_lineno = FALSE;
3733 static enum request run_prompt_command(struct view *view, char *cmd);
3735 static enum request
3736 open_run_request(struct view *view, enum request request)
3738 struct run_request *req = get_run_request(request);
3739 const char **argv = NULL;
3740 bool confirmed = FALSE;
3742 request = REQ_NONE;
3744 if (!req) {
3745 report("Unknown run request");
3746 return request;
3749 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3750 if (req->internal) {
3751 char cmd[SIZEOF_STR];
3753 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3754 request = run_prompt_command(view, cmd);
3757 else {
3758 confirmed = !req->confirm;
3760 if (req->confirm) {
3761 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3762 const char *and_exit = req->exit ? " and exit" : "";
3764 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3765 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3766 prompt_yesno(prompt)) {
3767 confirmed = TRUE;
3771 if (confirmed && argv_remove_quotes(argv)) {
3772 if (req->silent)
3773 io_run_bg(argv);
3774 else
3775 open_external_viewer(argv, NULL, !req->exit, "");
3780 if (argv)
3781 argv_free(argv);
3782 free(argv);
3784 if (request == REQ_NONE) {
3785 if (req->confirm && !confirmed)
3786 request = REQ_NONE;
3788 else if (req->exit)
3789 request = REQ_QUIT;
3791 else if (!view->unrefreshable)
3792 request = REQ_REFRESH;
3794 return request;
3798 * User request switch noodle
3801 static int
3802 view_driver(struct view *view, enum request request)
3804 int i;
3806 if (request == REQ_NONE)
3807 return TRUE;
3809 if (request > REQ_NONE) {
3810 request = open_run_request(view, request);
3812 // exit quickly rather than going through view_request and back
3813 if (request == REQ_QUIT)
3814 return FALSE;
3817 request = view_request(view, request);
3818 if (request == REQ_NONE)
3819 return TRUE;
3821 switch (request) {
3822 case REQ_MOVE_UP:
3823 case REQ_MOVE_DOWN:
3824 case REQ_MOVE_PAGE_UP:
3825 case REQ_MOVE_PAGE_DOWN:
3826 case REQ_MOVE_FIRST_LINE:
3827 case REQ_MOVE_LAST_LINE:
3828 move_view(view, request);
3829 break;
3831 case REQ_SCROLL_FIRST_COL:
3832 case REQ_SCROLL_LEFT:
3833 case REQ_SCROLL_RIGHT:
3834 case REQ_SCROLL_LINE_DOWN:
3835 case REQ_SCROLL_LINE_UP:
3836 case REQ_SCROLL_PAGE_DOWN:
3837 case REQ_SCROLL_PAGE_UP:
3838 scroll_view(view, request);
3839 break;
3841 case REQ_VIEW_MAIN:
3842 case REQ_VIEW_DIFF:
3843 case REQ_VIEW_LOG:
3844 case REQ_VIEW_TREE:
3845 case REQ_VIEW_HELP:
3846 case REQ_VIEW_BRANCH:
3847 case REQ_VIEW_BLAME:
3848 case REQ_VIEW_BLOB:
3849 case REQ_VIEW_STATUS:
3850 case REQ_VIEW_STAGE:
3851 case REQ_VIEW_PAGER:
3852 case REQ_VIEW_STASH:
3853 open_view(view, request, OPEN_DEFAULT);
3854 break;
3856 case REQ_NEXT:
3857 case REQ_PREVIOUS:
3858 if (view->parent) {
3859 int line;
3861 view = view->parent;
3862 line = view->pos.lineno;
3863 view_request(view, request);
3864 move_view(view, request);
3865 if (view_is_displayed(view))
3866 update_view_title(view);
3867 if (line != view->pos.lineno)
3868 view_request(view, REQ_ENTER);
3869 } else {
3870 move_view(view, request);
3872 break;
3874 case REQ_VIEW_NEXT:
3876 int nviews = displayed_views();
3877 int next_view = (current_view + 1) % nviews;
3879 if (next_view == current_view) {
3880 report("Only one view is displayed");
3881 break;
3884 current_view = next_view;
3885 /* Blur out the title of the previous view. */
3886 update_view_title(view);
3887 report_clear();
3888 break;
3890 case REQ_REFRESH:
3891 report("Refreshing is not yet supported for the %s view", view->name);
3892 break;
3894 case REQ_MAXIMIZE:
3895 if (displayed_views() == 2)
3896 maximize_view(view, TRUE);
3897 break;
3899 case REQ_OPTIONS:
3900 case REQ_TOGGLE_LINENO:
3901 case REQ_TOGGLE_DATE:
3902 case REQ_TOGGLE_AUTHOR:
3903 case REQ_TOGGLE_FILENAME:
3904 case REQ_TOGGLE_GRAPHIC:
3905 case REQ_TOGGLE_REV_GRAPH:
3906 case REQ_TOGGLE_REFS:
3907 case REQ_TOGGLE_CHANGES:
3908 case REQ_TOGGLE_IGNORE_SPACE:
3909 case REQ_TOGGLE_ID:
3910 case REQ_TOGGLE_FILES:
3911 case REQ_TOGGLE_TITLE_OVERFLOW:
3913 char action[SIZEOF_STR] = "";
3914 enum view_flag flags = toggle_option(view, request, action);
3916 foreach_displayed_view(view, i) {
3917 if (view_has_flags(view, flags))
3918 reload_view(view);
3919 else
3920 redraw_view(view);
3923 if (*action)
3924 report("%s", action);
3926 break;
3928 case REQ_TOGGLE_SORT_FIELD:
3929 case REQ_TOGGLE_SORT_ORDER:
3930 report("Sorting is not yet supported for the %s view", view->name);
3931 break;
3933 case REQ_DIFF_CONTEXT_UP:
3934 case REQ_DIFF_CONTEXT_DOWN:
3935 report("Changing the diff context is not yet supported for the %s view", view->name);
3936 break;
3938 case REQ_SEARCH:
3939 case REQ_SEARCH_BACK:
3940 search_view(view, request);
3941 break;
3943 case REQ_FIND_NEXT:
3944 case REQ_FIND_PREV:
3945 find_next(view, request);
3946 break;
3948 case REQ_STOP_LOADING:
3949 foreach_view(view, i) {
3950 if (view->pipe)
3951 report("Stopped loading the %s view", view->name),
3952 end_update(view, TRUE);
3954 break;
3956 case REQ_SHOW_VERSION:
3957 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3958 return TRUE;
3960 case REQ_SCREEN_REDRAW:
3961 redraw_display(TRUE);
3962 break;
3964 case REQ_EDIT:
3965 report("Nothing to edit");
3966 break;
3968 case REQ_ENTER:
3969 report("Nothing to enter");
3970 break;
3972 case REQ_VIEW_CLOSE:
3973 /* XXX: Mark closed views by letting view->prev point to the
3974 * view itself. Parents to closed view should never be
3975 * followed. */
3976 if (view->prev && view->prev != view) {
3977 maximize_view(view->prev, TRUE);
3978 view->prev = view;
3979 break;
3981 /* Fall-through */
3982 case REQ_QUIT:
3983 return FALSE;
3985 default:
3986 report("Unknown key, press %s for help",
3987 get_view_key(view, REQ_VIEW_HELP));
3988 return TRUE;
3991 return TRUE;
3996 * View backend utilities
3999 enum sort_field {
4000 ORDERBY_NAME,
4001 ORDERBY_DATE,
4002 ORDERBY_AUTHOR,
4005 struct sort_state {
4006 const enum sort_field *fields;
4007 size_t size, current;
4008 bool reverse;
4011 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
4012 #define get_sort_field(state) ((state).fields[(state).current])
4013 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
4015 static void
4016 sort_view(struct view *view, enum request request, struct sort_state *state,
4017 int (*compare)(const void *, const void *))
4019 switch (request) {
4020 case REQ_TOGGLE_SORT_FIELD:
4021 state->current = (state->current + 1) % state->size;
4022 break;
4024 case REQ_TOGGLE_SORT_ORDER:
4025 state->reverse = !state->reverse;
4026 break;
4027 default:
4028 die("Not a sort request");
4031 qsort(view->line, view->lines, sizeof(*view->line), compare);
4032 redraw_view(view);
4035 static bool
4036 update_diff_context(enum request request)
4038 int diff_context = opt_diff_context;
4040 switch (request) {
4041 case REQ_DIFF_CONTEXT_UP:
4042 opt_diff_context += 1;
4043 update_diff_context_arg(opt_diff_context);
4044 break;
4046 case REQ_DIFF_CONTEXT_DOWN:
4047 if (opt_diff_context == 0) {
4048 report("Diff context cannot be less than zero");
4049 break;
4051 opt_diff_context -= 1;
4052 update_diff_context_arg(opt_diff_context);
4053 break;
4055 default:
4056 die("Not a diff context request");
4059 return diff_context != opt_diff_context;
4062 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4064 /* Small author cache to reduce memory consumption. It uses binary
4065 * search to lookup or find place to position new entries. No entries
4066 * are ever freed. */
4067 static struct ident *
4068 get_author(const char *name, const char *email)
4070 static struct ident **authors;
4071 static size_t authors_size;
4072 int from = 0, to = authors_size - 1;
4073 struct ident *ident;
4075 while (from <= to) {
4076 size_t pos = (to + from) / 2;
4077 int cmp = strcmp(name, authors[pos]->name);
4079 if (!cmp)
4080 return authors[pos];
4082 if (cmp < 0)
4083 to = pos - 1;
4084 else
4085 from = pos + 1;
4088 if (!realloc_authors(&authors, authors_size, 1))
4089 return NULL;
4090 ident = calloc(1, sizeof(*ident));
4091 if (!ident)
4092 return NULL;
4093 ident->name = strdup(name);
4094 ident->email = strdup(email);
4095 if (!ident->name || !ident->email) {
4096 free((void *) ident->name);
4097 free(ident);
4098 return NULL;
4101 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4102 authors[from] = ident;
4103 authors_size++;
4105 return ident;
4108 static void
4109 parse_timesec(struct time *time, const char *sec)
4111 time->sec = (time_t) atol(sec);
4114 static void
4115 parse_timezone(struct time *time, const char *zone)
4117 long tz;
4119 tz = ('0' - zone[1]) * 60 * 60 * 10;
4120 tz += ('0' - zone[2]) * 60 * 60;
4121 tz += ('0' - zone[3]) * 60 * 10;
4122 tz += ('0' - zone[4]) * 60;
4124 if (zone[0] == '-')
4125 tz = -tz;
4127 time->tz = tz;
4128 time->sec -= tz;
4131 /* Parse author lines where the name may be empty:
4132 * author <email@address.tld> 1138474660 +0100
4134 static void
4135 parse_author_line(char *ident, const struct ident **author, struct time *time)
4137 char *nameend = strchr(ident, '<');
4138 char *emailend = strchr(ident, '>');
4139 const char *name, *email = "";
4141 if (nameend && emailend)
4142 *nameend = *emailend = 0;
4143 name = chomp_string(ident);
4144 if (nameend)
4145 email = chomp_string(nameend + 1);
4146 if (!*name)
4147 name = *email ? email : unknown_ident.name;
4148 if (!*email)
4149 email = *name ? name : unknown_ident.email;
4151 *author = get_author(name, email);
4153 /* Parse epoch and timezone */
4154 if (time && emailend && emailend[1] == ' ') {
4155 char *secs = emailend + 2;
4156 char *zone = strchr(secs, ' ');
4158 parse_timesec(time, secs);
4160 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4161 parse_timezone(time, zone + 1);
4165 static struct line *
4166 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4168 for (; view_has_line(view, line); line += direction)
4169 if (line->type == type)
4170 return line;
4172 return NULL;
4175 #define find_prev_line_by_type(view, line, type) \
4176 find_line_by_type(view, line, type, -1)
4178 #define find_next_line_by_type(view, line, type) \
4179 find_line_by_type(view, line, type, 1)
4182 * Blame
4185 struct blame_commit {
4186 char id[SIZEOF_REV]; /* SHA1 ID. */
4187 char title[128]; /* First line of the commit message. */
4188 const struct ident *author; /* Author of the commit. */
4189 struct time time; /* Date from the author ident. */
4190 char filename[128]; /* Name of file. */
4191 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4192 char parent_filename[128]; /* Parent/previous name of file. */
4195 struct blame_header {
4196 char id[SIZEOF_REV]; /* SHA1 ID. */
4197 size_t orig_lineno;
4198 size_t lineno;
4199 size_t group;
4202 static bool
4203 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4205 const char *pos = *posref;
4207 *posref = NULL;
4208 pos = strchr(pos + 1, ' ');
4209 if (!pos || !isdigit(pos[1]))
4210 return FALSE;
4211 *number = atoi(pos + 1);
4212 if (*number < min || *number > max)
4213 return FALSE;
4215 *posref = pos;
4216 return TRUE;
4219 static bool
4220 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4222 const char *pos = text + SIZEOF_REV - 2;
4224 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4225 return FALSE;
4227 string_ncopy(header->id, text, SIZEOF_REV);
4229 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4230 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4231 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4232 return FALSE;
4234 return TRUE;
4237 static bool
4238 match_blame_header(const char *name, char **line)
4240 size_t namelen = strlen(name);
4241 bool matched = !strncmp(name, *line, namelen);
4243 if (matched)
4244 *line += namelen;
4246 return matched;
4249 static bool
4250 parse_blame_info(struct blame_commit *commit, char *line)
4252 if (match_blame_header("author ", &line)) {
4253 parse_author_line(line, &commit->author, NULL);
4255 } else if (match_blame_header("author-time ", &line)) {
4256 parse_timesec(&commit->time, line);
4258 } else if (match_blame_header("author-tz ", &line)) {
4259 parse_timezone(&commit->time, line);
4261 } else if (match_blame_header("summary ", &line)) {
4262 string_ncopy(commit->title, line, strlen(line));
4264 } else if (match_blame_header("previous ", &line)) {
4265 if (strlen(line) <= SIZEOF_REV)
4266 return FALSE;
4267 string_copy_rev(commit->parent_id, line);
4268 line += SIZEOF_REV;
4269 string_ncopy(commit->parent_filename, line, strlen(line));
4271 } else if (match_blame_header("filename ", &line)) {
4272 string_ncopy(commit->filename, line, strlen(line));
4273 return TRUE;
4276 return FALSE;
4280 * Pager backend
4283 static bool
4284 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4286 if (draw_lineno(view, lineno))
4287 return TRUE;
4289 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4290 return TRUE;
4292 draw_text(view, line->type, line->data);
4293 return TRUE;
4296 static bool
4297 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4299 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4300 char ref[SIZEOF_STR];
4302 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4303 return TRUE;
4305 /* This is the only fatal call, since it can "corrupt" the buffer. */
4306 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4307 return FALSE;
4309 return TRUE;
4312 static void
4313 add_pager_refs(struct view *view, const char *commit_id)
4315 char buf[SIZEOF_STR];
4316 struct ref_list *list;
4317 size_t bufpos = 0, i;
4318 const char *sep = "Refs: ";
4319 bool is_tag = FALSE;
4321 list = get_ref_list(commit_id);
4322 if (!list) {
4323 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4324 goto try_add_describe_ref;
4325 return;
4328 for (i = 0; i < list->size; i++) {
4329 struct ref *ref = list->refs[i];
4330 const char *fmt = ref->tag ? "%s[%s]" :
4331 ref->remote ? "%s<%s>" : "%s%s";
4333 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4334 return;
4335 sep = ", ";
4336 if (ref->tag)
4337 is_tag = TRUE;
4340 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4341 try_add_describe_ref:
4342 /* Add <tag>-g<commit_id> "fake" reference. */
4343 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4344 return;
4347 if (bufpos == 0)
4348 return;
4350 add_line_text(view, buf, LINE_PP_REFS);
4353 static struct line *
4354 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4356 size_t first_line = 0;
4357 bool has_first_line = FALSE;
4358 size_t datalen = strlen(data);
4359 size_t lineno = 0;
4361 while (datalen > 0 || !has_first_line) {
4362 bool wrapped = !!first_line;
4363 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4364 struct line *line;
4365 char *text;
4367 line = add_line(view, NULL, type, linelen + 1, wrapped);
4368 if (!line)
4369 break;
4370 if (!has_first_line) {
4371 first_line = view->lines - 1;
4372 has_first_line = TRUE;
4375 if (!wrapped)
4376 lineno = line->lineno;
4378 line->wrapped = wrapped;
4379 line->lineno = lineno;
4380 text = line->data;
4381 if (linelen)
4382 strncpy(text, data, linelen);
4383 text[linelen] = 0;
4385 datalen -= linelen;
4386 data += linelen;
4389 return has_first_line ? &view->line[first_line] : NULL;
4392 static bool
4393 pager_common_read(struct view *view, const char *data, enum line_type type)
4395 struct line *line;
4397 if (!data)
4398 return TRUE;
4400 if (opt_wrap_lines) {
4401 line = pager_wrap_line(view, data, type);
4402 } else {
4403 line = add_line_text(view, data, type);
4406 if (!line)
4407 return FALSE;
4409 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4410 add_pager_refs(view, data + STRING_SIZE("commit "));
4412 return TRUE;
4415 static bool
4416 pager_read(struct view *view, char *data)
4418 if (!data)
4419 return TRUE;
4421 return pager_common_read(view, data, get_line_type(data));
4424 static enum request
4425 pager_request(struct view *view, enum request request, struct line *line)
4427 int split = 0;
4429 if (request != REQ_ENTER)
4430 return request;
4432 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4433 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4434 split = 1;
4437 /* Always scroll the view even if it was split. That way
4438 * you can use Enter to scroll through the log view and
4439 * split open each commit diff. */
4440 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4442 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4443 * but if we are scrolling a non-current view this won't properly
4444 * update the view title. */
4445 if (split)
4446 update_view_title(view);
4448 return REQ_NONE;
4451 static bool
4452 pager_grep(struct view *view, struct line *line)
4454 const char *text[] = { line->data, NULL };
4456 return grep_text(view, text);
4459 static void
4460 pager_select(struct view *view, struct line *line)
4462 if (line->type == LINE_COMMIT) {
4463 string_copy_rev_from_commit_line(ref_commit, line->data);
4464 if (!view_has_flags(view, VIEW_NO_REF))
4465 string_copy_rev(view->ref, ref_commit);
4469 struct log_state {
4470 /* Used for tracking when we need to recalculate the previous
4471 * commit, for example when the user scrolls up or uses the page
4472 * up/down in the log view. */
4473 int last_lineno;
4474 enum line_type last_type;
4477 static void
4478 log_select(struct view *view, struct line *line)
4480 struct log_state *state = view->private;
4481 int last_lineno = state->last_lineno;
4483 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4484 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4485 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4487 if (commit_line)
4488 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4491 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4492 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4494 string_copy_rev(ref_commit, view->ref);
4495 state->last_lineno = line->lineno;
4496 state->last_type = line->type;
4499 static bool
4500 pager_open(struct view *view, enum open_flags flags)
4502 if (display[0] == NULL) {
4503 if (!io_open(&view->io, "%s", ""))
4504 die("Failed to open stdin");
4505 flags = OPEN_PREPARED;
4507 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4508 report("No pager content, press %s to run command from prompt",
4509 get_view_key(view, REQ_PROMPT));
4510 return FALSE;
4513 return begin_update(view, NULL, NULL, flags);
4516 static struct view_ops pager_ops = {
4517 "line",
4518 { "pager" },
4519 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4521 pager_open,
4522 pager_read,
4523 pager_draw,
4524 pager_request,
4525 pager_grep,
4526 pager_select,
4529 static bool
4530 log_open(struct view *view, enum open_flags flags)
4532 static const char *log_argv[] = {
4533 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4536 return begin_update(view, NULL, log_argv, flags);
4539 static enum request
4540 log_request(struct view *view, enum request request, struct line *line)
4542 switch (request) {
4543 case REQ_REFRESH:
4544 load_refs(TRUE);
4545 refresh_view(view);
4546 return REQ_NONE;
4548 case REQ_ENTER:
4549 if (!display[1] || strcmp(display[1]->vid, view->ref))
4550 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4551 return REQ_NONE;
4553 default:
4554 return request;
4558 static struct view_ops log_ops = {
4559 "line",
4560 { "log" },
4561 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4562 sizeof(struct log_state),
4563 log_open,
4564 pager_read,
4565 pager_draw,
4566 log_request,
4567 pager_grep,
4568 log_select,
4571 struct diff_state {
4572 bool after_commit_title;
4573 bool after_diff;
4574 bool reading_diff_stat;
4575 bool combined_diff;
4578 #define DIFF_LINE_COMMIT_TITLE 1
4580 static bool
4581 diff_open(struct view *view, enum open_flags flags)
4583 static const char *diff_argv[] = {
4584 "git", "show", opt_encoding_arg, "--pretty=fuller", "--root",
4585 "--patch-with-stat",
4586 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4587 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4590 return begin_update(view, NULL, diff_argv, flags);
4593 static bool
4594 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4596 enum line_type type = get_line_type(data);
4598 if (!view->lines && type != LINE_COMMIT)
4599 state->reading_diff_stat = TRUE;
4601 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4602 state->reading_diff_stat = TRUE;
4604 if (state->reading_diff_stat) {
4605 size_t len = strlen(data);
4606 char *pipe = strchr(data, '|');
4607 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4608 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4609 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4611 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4612 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4613 } else {
4614 state->reading_diff_stat = FALSE;
4617 } else if (!strcmp(data, "---")) {
4618 state->reading_diff_stat = TRUE;
4621 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4622 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4624 if (line)
4625 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4626 state->after_commit_title = TRUE;
4627 return line != NULL;
4630 if (type == LINE_DIFF_HEADER) {
4631 const int len = line_info[LINE_DIFF_HEADER].linelen;
4633 state->after_diff = TRUE;
4634 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4635 !strncmp(data + len, "cc ", strlen("cc ")))
4636 state->combined_diff = TRUE;
4638 } else if (type == LINE_PP_MERGE) {
4639 state->combined_diff = TRUE;
4642 /* ADD2 and DEL2 are only valid in combined diff hunks */
4643 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4644 type = LINE_DEFAULT;
4646 return pager_common_read(view, data, type);
4649 static bool
4650 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4652 struct line *marker = find_next_line_by_type(view, line, type);
4654 return marker &&
4655 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4658 static enum request
4659 diff_common_enter(struct view *view, enum request request, struct line *line)
4661 if (line->type == LINE_DIFF_STAT) {
4662 int file_number = 0;
4664 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4665 file_number++;
4666 line--;
4669 for (line = view->line; view_has_line(view, line); line++) {
4670 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4671 if (!line)
4672 break;
4674 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4675 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4676 if (file_number == 1) {
4677 break;
4679 file_number--;
4683 if (!line) {
4684 report("Failed to find file diff");
4685 return REQ_NONE;
4688 select_view_line(view, line - view->line);
4689 report_clear();
4690 return REQ_NONE;
4692 } else {
4693 return pager_request(view, request, line);
4697 static bool
4698 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4700 char *sep = strchr(*text, c);
4702 if (sep != NULL) {
4703 *sep = 0;
4704 draw_text(view, *type, *text);
4705 *sep = c;
4706 *text = sep;
4707 *type = next_type;
4710 return sep != NULL;
4713 static bool
4714 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4716 char *text = line->data;
4717 enum line_type type = line->type;
4719 if (draw_lineno(view, lineno))
4720 return TRUE;
4722 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4723 return TRUE;
4725 if (type == LINE_DIFF_STAT) {
4726 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4727 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4728 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4729 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4730 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4731 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4732 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4734 } else {
4735 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4736 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4740 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4741 draw_commit_title(view, text, 4);
4742 else
4743 draw_text(view, type, text);
4744 return TRUE;
4747 static bool
4748 diff_read(struct view *view, char *data)
4750 struct diff_state *state = view->private;
4752 if (!data) {
4753 /* Fall back to retry if no diff will be shown. */
4754 if (view->lines == 0 && opt_file_argv) {
4755 int pos = argv_size(view->argv)
4756 - argv_size(opt_file_argv) - 1;
4758 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4759 for (; view->argv[pos]; pos++) {
4760 free((void *) view->argv[pos]);
4761 view->argv[pos] = NULL;
4764 if (view->pipe)
4765 io_done(view->pipe);
4766 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4767 return FALSE;
4770 return TRUE;
4773 return diff_common_read(view, data, state);
4776 static bool
4777 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4778 struct blame_header *header, struct blame_commit *commit)
4780 char line_arg[SIZEOF_STR];
4781 const char *blame_argv[] = {
4782 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4784 struct io io;
4785 bool ok = FALSE;
4786 char *buf;
4788 if (!string_format(line_arg, "-L%ld,+1", lineno))
4789 return FALSE;
4791 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4792 return FALSE;
4794 while ((buf = io_get(&io, '\n', TRUE))) {
4795 if (header) {
4796 if (!parse_blame_header(header, buf, 9999999))
4797 break;
4798 header = NULL;
4800 } else if (parse_blame_info(commit, buf)) {
4801 ok = TRUE;
4802 break;
4806 if (io_error(&io))
4807 ok = FALSE;
4809 io_done(&io);
4810 return ok;
4813 static unsigned int
4814 diff_get_lineno(struct view *view, struct line *line)
4816 const struct line *header, *chunk;
4817 const char *data;
4818 unsigned int lineno;
4820 /* Verify that we are after a diff header and one of its chunks */
4821 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4822 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4823 if (!header || !chunk || chunk < header)
4824 return 0;
4827 * In a chunk header, the number after the '+' sign is the number of its
4828 * following line, in the new version of the file. We increment this
4829 * number for each non-deletion line, until the given line position.
4831 data = strchr(chunk->data, '+');
4832 if (!data)
4833 return 0;
4835 lineno = atoi(data);
4836 chunk++;
4837 while (chunk++ < line)
4838 if (chunk->type != LINE_DIFF_DEL)
4839 lineno++;
4841 return lineno;
4844 static bool
4845 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4847 return prefixcmp(chunk, "@@ -") ||
4848 !(chunk = strchr(chunk, marker)) ||
4849 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4852 static enum request
4853 diff_trace_origin(struct view *view, struct line *line)
4855 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4856 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4857 const char *chunk_data;
4858 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4859 int lineno = 0;
4860 const char *file = NULL;
4861 char ref[SIZEOF_REF];
4862 struct blame_header header;
4863 struct blame_commit commit;
4865 if (!diff || !chunk || chunk == line) {
4866 report("The line to trace must be inside a diff chunk");
4867 return REQ_NONE;
4870 for (; diff < line && !file; diff++) {
4871 const char *data = diff->data;
4873 if (!prefixcmp(data, "--- a/")) {
4874 file = data + STRING_SIZE("--- a/");
4875 break;
4879 if (diff == line || !file) {
4880 report("Failed to read the file name");
4881 return REQ_NONE;
4884 chunk_data = chunk->data;
4886 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4887 report("Failed to read the line number");
4888 return REQ_NONE;
4891 if (lineno == 0) {
4892 report("This is the origin of the line");
4893 return REQ_NONE;
4896 for (chunk += 1; chunk < line; chunk++) {
4897 if (chunk->type == LINE_DIFF_ADD) {
4898 lineno += chunk_marker == '+';
4899 } else if (chunk->type == LINE_DIFF_DEL) {
4900 lineno += chunk_marker == '-';
4901 } else {
4902 lineno++;
4906 if (chunk_marker == '+')
4907 string_copy(ref, view->vid);
4908 else
4909 string_format(ref, "%s^", view->vid);
4911 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4912 report("Failed to read blame data");
4913 return REQ_NONE;
4916 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4917 string_copy(opt_ref, header.id);
4918 opt_goto_line = header.orig_lineno - 1;
4920 return REQ_VIEW_BLAME;
4923 static const char *
4924 diff_get_pathname(struct view *view, struct line *line)
4926 const struct line *header;
4927 const char *dst = NULL;
4928 const char *prefixes[] = { " b/", "cc ", "combined " };
4929 int i;
4931 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4932 if (!header)
4933 return NULL;
4935 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4936 dst = strstr(header->data, prefixes[i]);
4938 return dst ? dst + strlen(prefixes[--i]) : NULL;
4941 static enum request
4942 diff_common_edit(struct view *view, enum request request, struct line *line)
4944 const char *file = diff_get_pathname(view, line);
4945 char path[SIZEOF_STR];
4946 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
4948 if (has_path && access(path, R_OK)) {
4949 report("Failed to open file: %s", file);
4950 return REQ_NONE;
4953 open_editor(file, diff_get_lineno(view, line));
4954 return REQ_NONE;
4957 static enum request
4958 diff_request(struct view *view, enum request request, struct line *line)
4960 switch (request) {
4961 case REQ_VIEW_BLAME:
4962 return diff_trace_origin(view, line);
4964 case REQ_DIFF_CONTEXT_UP:
4965 case REQ_DIFF_CONTEXT_DOWN:
4966 if (!update_diff_context(request))
4967 return REQ_NONE;
4968 reload_view(view);
4969 return REQ_NONE;
4972 case REQ_EDIT:
4973 return diff_common_edit(view, request, line);
4975 case REQ_ENTER:
4976 return diff_common_enter(view, request, line);
4978 case REQ_REFRESH:
4979 reload_view(view);
4980 return REQ_NONE;
4982 default:
4983 return pager_request(view, request, line);
4987 static void
4988 diff_select(struct view *view, struct line *line)
4990 if (line->type == LINE_DIFF_STAT) {
4991 string_format(view->ref, "Press '%s' to jump to file diff",
4992 get_view_key(view, REQ_ENTER));
4993 } else {
4994 const char *file = diff_get_pathname(view, line);
4996 if (file) {
4997 string_format(view->ref, "Changes to '%s'", file);
4998 string_format(opt_file, "%s", file);
4999 ref_blob[0] = 0;
5000 } else {
5001 string_ncopy(view->ref, view->id, strlen(view->id));
5002 pager_select(view, line);
5007 static struct view_ops diff_ops = {
5008 "line",
5009 { "diff" },
5010 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN | VIEW_FILE_FILTER,
5011 sizeof(struct diff_state),
5012 diff_open,
5013 diff_read,
5014 diff_common_draw,
5015 diff_request,
5016 pager_grep,
5017 diff_select,
5021 * Help backend
5024 static bool
5025 help_draw(struct view *view, struct line *line, unsigned int lineno)
5027 if (line->type == LINE_HELP_KEYMAP) {
5028 struct keymap *keymap = line->data;
5030 draw_formatted(view, line->type, "[%c] %s bindings",
5031 keymap->hidden ? '+' : '-', keymap->name);
5032 return TRUE;
5033 } else {
5034 return pager_draw(view, line, lineno);
5038 static bool
5039 help_open_keymap_title(struct view *view, struct keymap *keymap)
5041 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5042 return keymap->hidden;
5045 static void
5046 help_open_keymap(struct view *view, struct keymap *keymap)
5048 const char *group = NULL;
5049 char buf[SIZEOF_STR];
5050 bool add_title = TRUE;
5051 int i;
5053 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5054 const char *key = NULL;
5056 if (req_info[i].request == REQ_NONE)
5057 continue;
5059 if (!req_info[i].request) {
5060 group = req_info[i].help;
5061 continue;
5064 key = get_keys(keymap, req_info[i].request, TRUE);
5065 if (!key || !*key)
5066 continue;
5068 if (add_title && help_open_keymap_title(view, keymap))
5069 return;
5070 add_title = FALSE;
5072 if (group) {
5073 add_line_text(view, group, LINE_HELP_GROUP);
5074 group = NULL;
5077 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5078 enum_name(req_info[i]), req_info[i].help);
5081 group = "External commands:";
5083 for (i = 0; i < run_requests; i++) {
5084 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5085 const char *key;
5087 if (!req || req->keymap != keymap)
5088 continue;
5090 key = get_key_name(req->key);
5091 if (!*key)
5092 key = "(no key defined)";
5094 if (add_title && help_open_keymap_title(view, keymap))
5095 return;
5096 add_title = FALSE;
5098 if (group) {
5099 add_line_text(view, group, LINE_HELP_GROUP);
5100 group = NULL;
5103 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5104 return;
5106 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5110 static bool
5111 help_open(struct view *view, enum open_flags flags)
5113 struct keymap *keymap;
5115 reset_view(view);
5116 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5117 add_line_text(view, "", LINE_DEFAULT);
5119 for (keymap = keymaps; keymap; keymap = keymap->next)
5120 help_open_keymap(view, keymap);
5122 return TRUE;
5125 static enum request
5126 help_request(struct view *view, enum request request, struct line *line)
5128 switch (request) {
5129 case REQ_ENTER:
5130 if (line->type == LINE_HELP_KEYMAP) {
5131 struct keymap *keymap = line->data;
5133 keymap->hidden = !keymap->hidden;
5134 refresh_view(view);
5137 return REQ_NONE;
5138 default:
5139 return pager_request(view, request, line);
5143 static void
5144 help_done(struct view *view)
5146 int i;
5148 for (i = 0; i < view->lines; i++)
5149 if (view->line[i].type == LINE_HELP_KEYMAP)
5150 view->line[i].data = NULL;
5153 static struct view_ops help_ops = {
5154 "line",
5155 { "help" },
5156 VIEW_NO_GIT_DIR,
5158 help_open,
5159 NULL,
5160 help_draw,
5161 help_request,
5162 pager_grep,
5163 pager_select,
5164 help_done,
5169 * Tree backend
5172 struct tree_stack_entry {
5173 struct tree_stack_entry *prev; /* Entry below this in the stack */
5174 unsigned long lineno; /* Line number to restore */
5175 char *name; /* Position of name in opt_path */
5178 /* The top of the path stack. */
5179 static struct tree_stack_entry *tree_stack = NULL;
5180 unsigned long tree_lineno = 0;
5182 static void
5183 pop_tree_stack_entry(void)
5185 struct tree_stack_entry *entry = tree_stack;
5187 tree_lineno = entry->lineno;
5188 entry->name[0] = 0;
5189 tree_stack = entry->prev;
5190 free(entry);
5193 static void
5194 push_tree_stack_entry(const char *name, unsigned long lineno)
5196 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
5197 size_t pathlen = strlen(opt_path);
5199 if (!entry)
5200 return;
5202 entry->prev = tree_stack;
5203 entry->name = opt_path + pathlen;
5204 tree_stack = entry;
5206 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5207 pop_tree_stack_entry();
5208 return;
5211 /* Move the current line to the first tree entry. */
5212 tree_lineno = 1;
5213 entry->lineno = lineno;
5216 /* Parse output from git-ls-tree(1):
5218 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5221 #define SIZEOF_TREE_ATTR \
5222 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5224 #define SIZEOF_TREE_MODE \
5225 STRING_SIZE("100644 ")
5227 #define TREE_ID_OFFSET \
5228 STRING_SIZE("100644 blob ")
5230 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5232 struct tree_entry {
5233 char id[SIZEOF_REV];
5234 char commit[SIZEOF_REV];
5235 mode_t mode;
5236 struct time time; /* Date from the author ident. */
5237 const struct ident *author; /* Author of the commit. */
5238 unsigned long size;
5239 char name[1];
5242 struct tree_state {
5243 char commit[SIZEOF_REV];
5244 const struct ident *author;
5245 struct time author_time;
5246 int size_width;
5247 bool read_date;
5250 static const char *
5251 tree_path(const struct line *line)
5253 return ((struct tree_entry *) line->data)->name;
5256 static int
5257 tree_compare_entry(const struct line *line1, const struct line *line2)
5259 if (line1->type != line2->type)
5260 return line1->type == LINE_TREE_DIR ? -1 : 1;
5261 return strcmp(tree_path(line1), tree_path(line2));
5264 static const enum sort_field tree_sort_fields[] = {
5265 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5267 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5269 static int
5270 tree_compare(const void *l1, const void *l2)
5272 const struct line *line1 = (const struct line *) l1;
5273 const struct line *line2 = (const struct line *) l2;
5274 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5275 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5277 if (line1->type == LINE_TREE_HEAD)
5278 return -1;
5279 if (line2->type == LINE_TREE_HEAD)
5280 return 1;
5282 switch (get_sort_field(tree_sort_state)) {
5283 case ORDERBY_DATE:
5284 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5286 case ORDERBY_AUTHOR:
5287 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5289 case ORDERBY_NAME:
5290 default:
5291 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5296 static struct line *
5297 tree_entry(struct view *view, enum line_type type, const char *path,
5298 const char *mode, const char *id, unsigned long size)
5300 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5301 struct tree_entry *entry;
5302 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5304 if (!line)
5305 return NULL;
5307 strncpy(entry->name, path, strlen(path));
5308 if (mode)
5309 entry->mode = strtoul(mode, NULL, 8);
5310 if (id)
5311 string_copy_rev(entry->id, id);
5312 entry->size = size;
5314 return line;
5317 static bool
5318 tree_read_date(struct view *view, char *text, struct tree_state *state)
5320 if (!text && state->read_date) {
5321 state->read_date = FALSE;
5322 return TRUE;
5324 } else if (!text) {
5325 /* Find next entry to process */
5326 const char *log_file[] = {
5327 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
5328 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5331 if (!view->lines) {
5332 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5333 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5334 report("Tree is empty");
5335 return TRUE;
5338 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5339 report("Failed to load tree data");
5340 return TRUE;
5343 state->read_date = TRUE;
5344 return FALSE;
5346 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5347 string_copy_rev_from_commit_line(state->commit, text);
5349 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5350 parse_author_line(text + STRING_SIZE("author "),
5351 &state->author, &state->author_time);
5353 } else if (*text == ':') {
5354 char *pos;
5355 size_t annotated = 1;
5356 size_t i;
5358 pos = strchr(text, '\t');
5359 if (!pos)
5360 return TRUE;
5361 text = pos + 1;
5362 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5363 text += strlen(opt_path);
5364 pos = strchr(text, '/');
5365 if (pos)
5366 *pos = 0;
5368 for (i = 1; i < view->lines; i++) {
5369 struct line *line = &view->line[i];
5370 struct tree_entry *entry = line->data;
5372 annotated += !!entry->author;
5373 if (entry->author || strcmp(entry->name, text))
5374 continue;
5376 string_copy_rev(entry->commit, state->commit);
5377 entry->author = state->author;
5378 entry->time = state->author_time;
5379 line->dirty = 1;
5380 break;
5383 if (annotated == view->lines)
5384 io_kill(view->pipe);
5386 return TRUE;
5389 static inline size_t
5390 parse_size(const char *text, int *max_digits)
5392 size_t size = 0;
5393 int digits = 0;
5395 while (*text == ' ')
5396 text++;
5398 while (isdigit(*text)) {
5399 size = (size * 10) + (*text++ - '0');
5400 digits++;
5403 if (digits > *max_digits)
5404 *max_digits = digits;
5406 return size;
5409 static bool
5410 tree_read(struct view *view, char *text)
5412 struct tree_state *state = view->private;
5413 struct tree_entry *data;
5414 struct line *entry, *line;
5415 enum line_type type;
5416 size_t textlen = text ? strlen(text) : 0;
5417 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5418 char *path;
5419 size_t size;
5421 if (state->read_date || !text)
5422 return tree_read_date(view, text, state);
5424 if (textlen <= SIZEOF_TREE_ATTR)
5425 return FALSE;
5426 if (view->lines == 0 &&
5427 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5428 return FALSE;
5430 size = parse_size(attr_offset, &state->size_width);
5431 path = strchr(attr_offset, '\t');
5432 if (!path)
5433 return FALSE;
5434 path++;
5436 /* Strip the path part ... */
5437 if (*opt_path) {
5438 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5439 size_t striplen = strlen(opt_path);
5441 if (pathlen > striplen)
5442 memmove(path, path + striplen,
5443 pathlen - striplen + 1);
5445 /* Insert "link" to parent directory. */
5446 if (view->lines == 1 &&
5447 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5448 return FALSE;
5451 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5452 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5453 if (!entry)
5454 return FALSE;
5455 data = entry->data;
5457 /* Skip "Directory ..." and ".." line. */
5458 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5459 if (tree_compare_entry(line, entry) <= 0)
5460 continue;
5462 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5464 line->data = data;
5465 line->type = type;
5466 for (; line <= entry; line++)
5467 line->dirty = line->cleareol = 1;
5468 return TRUE;
5471 if (tree_lineno <= view->pos.lineno)
5472 tree_lineno = view->custom_lines;
5474 if (tree_lineno > view->pos.lineno) {
5475 view->pos.lineno = tree_lineno;
5476 tree_lineno = 0;
5479 return TRUE;
5482 static bool
5483 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5485 struct tree_state *state = view->private;
5486 struct tree_entry *entry = line->data;
5488 if (line->type == LINE_TREE_HEAD) {
5489 if (draw_text(view, line->type, "Directory path /"))
5490 return TRUE;
5491 } else {
5492 if (draw_mode(view, entry->mode))
5493 return TRUE;
5495 if (draw_author(view, entry->author))
5496 return TRUE;
5498 if (draw_file_size(view, entry->size, state->size_width,
5499 line->type != LINE_TREE_FILE))
5500 return TRUE;
5502 if (draw_date(view, &entry->time))
5503 return TRUE;
5505 if (draw_id(view, entry->commit))
5506 return TRUE;
5509 draw_text(view, line->type, entry->name);
5510 return TRUE;
5513 static void
5514 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5516 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5517 char file[SIZEOF_STR];
5518 int fd;
5520 if (!name)
5521 name = "unknown";
5523 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5524 report("Temporary file name is too long");
5525 return;
5528 fd = mkstemps(file, strlen(name) + 1);
5530 if (fd == -1)
5531 report("Failed to create temporary file");
5532 else if (!io_run_append(blob_argv, fd))
5533 report("Failed to save blob data to file");
5534 else
5535 open_editor(file, lineno);
5536 if (fd != -1)
5537 unlink(file);
5540 static enum request
5541 tree_request(struct view *view, enum request request, struct line *line)
5543 enum open_flags flags;
5544 struct tree_entry *entry = line->data;
5546 switch (request) {
5547 case REQ_VIEW_BLAME:
5548 if (line->type != LINE_TREE_FILE) {
5549 report("Blame only supported for files");
5550 return REQ_NONE;
5553 string_copy(opt_ref, view->vid);
5554 return request;
5556 case REQ_EDIT:
5557 if (line->type != LINE_TREE_FILE) {
5558 report("Edit only supported for files");
5559 } else if (!is_head_commit(view->vid)) {
5560 open_blob_editor(entry->id, entry->name, 0);
5561 } else {
5562 open_editor(opt_file, 0);
5564 return REQ_NONE;
5566 case REQ_TOGGLE_SORT_FIELD:
5567 case REQ_TOGGLE_SORT_ORDER:
5568 sort_view(view, request, &tree_sort_state, tree_compare);
5569 return REQ_NONE;
5571 case REQ_PARENT:
5572 if (!*opt_path) {
5573 /* quit view if at top of tree */
5574 return REQ_VIEW_CLOSE;
5576 /* fake 'cd ..' */
5577 line = &view->line[1];
5578 break;
5580 case REQ_ENTER:
5581 break;
5583 default:
5584 return request;
5587 /* Cleanup the stack if the tree view is at a different tree. */
5588 while (!*opt_path && tree_stack)
5589 pop_tree_stack_entry();
5591 switch (line->type) {
5592 case LINE_TREE_DIR:
5593 /* Depending on whether it is a subdirectory or parent link
5594 * mangle the path buffer. */
5595 if (line == &view->line[1] && *opt_path) {
5596 pop_tree_stack_entry();
5598 } else {
5599 const char *basename = tree_path(line);
5601 push_tree_stack_entry(basename, view->pos.lineno);
5604 /* Trees and subtrees share the same ID, so they are not not
5605 * unique like blobs. */
5606 flags = OPEN_RELOAD;
5607 request = REQ_VIEW_TREE;
5608 break;
5610 case LINE_TREE_FILE:
5611 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5612 request = REQ_VIEW_BLOB;
5613 break;
5615 default:
5616 return REQ_NONE;
5619 open_view(view, request, flags);
5620 if (request == REQ_VIEW_TREE)
5621 view->pos.lineno = tree_lineno;
5623 return REQ_NONE;
5626 static bool
5627 tree_grep(struct view *view, struct line *line)
5629 struct tree_entry *entry = line->data;
5630 const char *text[] = {
5631 entry->name,
5632 mkauthor(entry->author, opt_author_width, opt_author),
5633 mkdate(&entry->time, opt_date),
5634 NULL
5637 return grep_text(view, text);
5640 static void
5641 tree_select(struct view *view, struct line *line)
5643 struct tree_entry *entry = line->data;
5645 if (line->type == LINE_TREE_HEAD) {
5646 string_format(view->ref, "Files in /%s", opt_path);
5647 return;
5650 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5651 string_copy(view->ref, "Open parent directory");
5652 ref_blob[0] = 0;
5653 return;
5656 if (line->type == LINE_TREE_FILE) {
5657 string_copy_rev(ref_blob, entry->id);
5658 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5661 string_copy_rev(view->ref, entry->id);
5664 static bool
5665 tree_open(struct view *view, enum open_flags flags)
5667 static const char *tree_argv[] = {
5668 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5671 if (string_rev_is_null(ref_commit)) {
5672 report("No tree exists for this commit");
5673 return FALSE;
5676 if (view->lines == 0 && opt_prefix[0]) {
5677 char *pos = opt_prefix;
5679 while (pos && *pos) {
5680 char *end = strchr(pos, '/');
5682 if (end)
5683 *end = 0;
5684 push_tree_stack_entry(pos, 0);
5685 pos = end;
5686 if (end) {
5687 *end = '/';
5688 pos++;
5692 } else if (strcmp(view->vid, view->id)) {
5693 opt_path[0] = 0;
5696 return begin_update(view, opt_cdup, tree_argv, flags);
5699 static struct view_ops tree_ops = {
5700 "file",
5701 { "tree" },
5702 VIEW_SEND_CHILD_ENTER,
5703 sizeof(struct tree_state),
5704 tree_open,
5705 tree_read,
5706 tree_draw,
5707 tree_request,
5708 tree_grep,
5709 tree_select,
5712 static bool
5713 blob_open(struct view *view, enum open_flags flags)
5715 static const char *blob_argv[] = {
5716 "git", "cat-file", "blob", "%(blob)", NULL
5719 if (!ref_blob[0] && opt_file[0]) {
5720 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5721 char blob_spec[SIZEOF_STR];
5722 const char *rev_parse_argv[] = {
5723 "git", "rev-parse", blob_spec, NULL
5726 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5727 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5728 report("Failed to resolve blob from file name");
5729 return FALSE;
5733 if (!ref_blob[0]) {
5734 report("No file chosen, press %s to open tree view",
5735 get_view_key(view, REQ_VIEW_TREE));
5736 return FALSE;
5739 view->encoding = get_path_encoding(opt_file, opt_encoding);
5741 return begin_update(view, NULL, blob_argv, flags);
5744 static bool
5745 blob_read(struct view *view, char *line)
5747 if (!line)
5748 return TRUE;
5749 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5752 static enum request
5753 blob_request(struct view *view, enum request request, struct line *line)
5755 switch (request) {
5756 case REQ_EDIT:
5757 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5758 return REQ_NONE;
5759 default:
5760 return pager_request(view, request, line);
5764 static struct view_ops blob_ops = {
5765 "line",
5766 { "blob" },
5767 VIEW_NO_FLAGS,
5769 blob_open,
5770 blob_read,
5771 pager_draw,
5772 blob_request,
5773 pager_grep,
5774 pager_select,
5778 * Blame backend
5780 * Loading the blame view is a two phase job:
5782 * 1. File content is read either using opt_file from the
5783 * filesystem or using git-cat-file.
5784 * 2. Then blame information is incrementally added by
5785 * reading output from git-blame.
5788 struct blame {
5789 struct blame_commit *commit;
5790 unsigned long lineno;
5791 char text[1];
5794 struct blame_state {
5795 struct blame_commit *commit;
5796 int blamed;
5797 bool done_reading;
5798 bool auto_filename_display;
5801 static bool
5802 blame_detect_filename_display(struct view *view)
5804 bool show_filenames = FALSE;
5805 const char *filename = NULL;
5806 int i;
5808 if (opt_blame_argv) {
5809 for (i = 0; opt_blame_argv[i]; i++) {
5810 if (prefixcmp(opt_blame_argv[i], "-C"))
5811 continue;
5813 show_filenames = TRUE;
5817 for (i = 0; i < view->lines; i++) {
5818 struct blame *blame = view->line[i].data;
5820 if (blame->commit && blame->commit->id[0]) {
5821 if (!filename)
5822 filename = blame->commit->filename;
5823 else if (strcmp(filename, blame->commit->filename))
5824 show_filenames = TRUE;
5828 return show_filenames;
5831 static bool
5832 blame_open(struct view *view, enum open_flags flags)
5834 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5835 char path[SIZEOF_STR];
5836 size_t i;
5838 if (!opt_file[0]) {
5839 report("No file chosen, press %s to open tree view",
5840 get_view_key(view, REQ_VIEW_TREE));
5841 return FALSE;
5844 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5845 string_copy(path, opt_file);
5846 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5847 report("Failed to setup the blame view");
5848 return FALSE;
5852 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5853 const char *blame_cat_file_argv[] = {
5854 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5857 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5858 return FALSE;
5861 /* First pass: remove multiple references to the same commit. */
5862 for (i = 0; i < view->lines; i++) {
5863 struct blame *blame = view->line[i].data;
5865 if (blame->commit && blame->commit->id[0])
5866 blame->commit->id[0] = 0;
5867 else
5868 blame->commit = NULL;
5871 /* Second pass: free existing references. */
5872 for (i = 0; i < view->lines; i++) {
5873 struct blame *blame = view->line[i].data;
5875 if (blame->commit)
5876 free(blame->commit);
5879 string_format(view->vid, "%s", opt_file);
5880 string_format(view->ref, "%s ...", opt_file);
5882 return TRUE;
5885 static struct blame_commit *
5886 get_blame_commit(struct view *view, const char *id)
5888 size_t i;
5890 for (i = 0; i < view->lines; i++) {
5891 struct blame *blame = view->line[i].data;
5893 if (!blame->commit)
5894 continue;
5896 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5897 return blame->commit;
5901 struct blame_commit *commit = calloc(1, sizeof(*commit));
5903 if (commit)
5904 string_ncopy(commit->id, id, SIZEOF_REV);
5905 return commit;
5909 static struct blame_commit *
5910 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5912 struct blame_header header;
5913 struct blame_commit *commit;
5914 struct blame *blame;
5916 if (!parse_blame_header(&header, text, view->lines))
5917 return NULL;
5919 commit = get_blame_commit(view, text);
5920 if (!commit)
5921 return NULL;
5923 state->blamed += header.group;
5924 while (header.group--) {
5925 struct line *line = &view->line[header.lineno + header.group - 1];
5927 blame = line->data;
5928 blame->commit = commit;
5929 blame->lineno = header.orig_lineno + header.group - 1;
5930 line->dirty = 1;
5933 return commit;
5936 static bool
5937 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5939 if (!text) {
5940 const char *blame_argv[] = {
5941 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5942 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5945 if (view->lines == 0 && !view->prev)
5946 die("No blame exist for %s", view->vid);
5948 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5949 report("Failed to load blame data");
5950 return TRUE;
5953 if (opt_goto_line > 0) {
5954 select_view_line(view, opt_goto_line);
5955 opt_goto_line = 0;
5958 state->done_reading = TRUE;
5959 return FALSE;
5961 } else {
5962 size_t textlen = strlen(text);
5963 struct blame *blame;
5965 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5966 return FALSE;
5968 blame->commit = NULL;
5969 strncpy(blame->text, text, textlen);
5970 blame->text[textlen] = 0;
5971 return TRUE;
5975 static bool
5976 blame_read(struct view *view, char *line)
5978 struct blame_state *state = view->private;
5980 if (!state->done_reading)
5981 return blame_read_file(view, line, state);
5983 if (!line) {
5984 state->auto_filename_display = blame_detect_filename_display(view);
5985 string_format(view->ref, "%s", view->vid);
5986 if (view_is_displayed(view)) {
5987 update_view_title(view);
5988 redraw_view_from(view, 0);
5990 return TRUE;
5993 if (!state->commit) {
5994 state->commit = read_blame_commit(view, line, state);
5995 string_format(view->ref, "%s %2zd%%", view->vid,
5996 view->lines ? state->blamed * 100 / view->lines : 0);
5998 } else if (parse_blame_info(state->commit, line)) {
5999 state->commit = NULL;
6002 return TRUE;
6005 static bool
6006 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6008 struct blame_state *state = view->private;
6009 struct blame *blame = line->data;
6010 struct time *time = NULL;
6011 const char *id = NULL, *filename = NULL;
6012 const struct ident *author = NULL;
6013 enum line_type id_type = LINE_ID;
6014 static const enum line_type blame_colors[] = {
6015 LINE_PALETTE_0,
6016 LINE_PALETTE_1,
6017 LINE_PALETTE_2,
6018 LINE_PALETTE_3,
6019 LINE_PALETTE_4,
6020 LINE_PALETTE_5,
6021 LINE_PALETTE_6,
6024 #define BLAME_COLOR(i) \
6025 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6027 if (blame->commit && *blame->commit->filename) {
6028 id = blame->commit->id;
6029 author = blame->commit->author;
6030 filename = blame->commit->filename;
6031 time = &blame->commit->time;
6032 id_type = BLAME_COLOR((long) blame->commit);
6035 if (draw_date(view, time))
6036 return TRUE;
6038 if (draw_author(view, author))
6039 return TRUE;
6041 if (draw_filename(view, filename, state->auto_filename_display))
6042 return TRUE;
6044 if (draw_id_custom(view, id_type, id, opt_id_cols))
6045 return TRUE;
6047 if (draw_lineno(view, lineno))
6048 return TRUE;
6050 draw_text(view, LINE_DEFAULT, blame->text);
6051 return TRUE;
6054 static bool
6055 check_blame_commit(struct blame *blame, bool check_null_id)
6057 if (!blame->commit)
6058 report("Commit data not loaded yet");
6059 else if (check_null_id && string_rev_is_null(blame->commit->id))
6060 report("No commit exist for the selected line");
6061 else
6062 return TRUE;
6063 return FALSE;
6066 static void
6067 setup_blame_parent_line(struct view *view, struct blame *blame)
6069 char from[SIZEOF_REF + SIZEOF_STR];
6070 char to[SIZEOF_REF + SIZEOF_STR];
6071 const char *diff_tree_argv[] = {
6072 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
6073 "--no-color", "-U0", from, to, "--", NULL
6075 struct io io;
6076 int parent_lineno = -1;
6077 int blamed_lineno = -1;
6078 char *line;
6080 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6081 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6082 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6083 return;
6085 while ((line = io_get(&io, '\n', TRUE))) {
6086 if (*line == '@') {
6087 char *pos = strchr(line, '+');
6089 parent_lineno = atoi(line + 4);
6090 if (pos)
6091 blamed_lineno = atoi(pos + 1);
6093 } else if (*line == '+' && parent_lineno != -1) {
6094 if (blame->lineno == blamed_lineno - 1 &&
6095 !strcmp(blame->text, line + 1)) {
6096 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6097 break;
6099 blamed_lineno++;
6103 io_done(&io);
6106 static enum request
6107 blame_request(struct view *view, enum request request, struct line *line)
6109 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6110 struct blame *blame = line->data;
6112 switch (request) {
6113 case REQ_VIEW_BLAME:
6114 if (check_blame_commit(blame, TRUE)) {
6115 string_copy(opt_ref, blame->commit->id);
6116 string_copy(opt_file, blame->commit->filename);
6117 if (blame->lineno)
6118 view->pos.lineno = blame->lineno;
6119 reload_view(view);
6121 break;
6123 case REQ_PARENT:
6124 if (!check_blame_commit(blame, TRUE))
6125 break;
6126 if (!*blame->commit->parent_id) {
6127 report("The selected commit has no parents");
6128 } else {
6129 string_copy_rev(opt_ref, blame->commit->parent_id);
6130 string_copy(opt_file, blame->commit->parent_filename);
6131 setup_blame_parent_line(view, blame);
6132 opt_goto_line = blame->lineno;
6133 reload_view(view);
6135 break;
6137 case REQ_ENTER:
6138 if (!check_blame_commit(blame, FALSE))
6139 break;
6141 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6142 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6143 break;
6145 if (string_rev_is_null(blame->commit->id)) {
6146 struct view *diff = VIEW(REQ_VIEW_DIFF);
6147 const char *diff_parent_argv[] = {
6148 GIT_DIFF_BLAME(opt_encoding_arg,
6149 opt_diff_context_arg,
6150 opt_ignore_space_arg, view->vid)
6152 const char *diff_no_parent_argv[] = {
6153 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
6154 opt_diff_context_arg,
6155 opt_ignore_space_arg, view->vid)
6157 const char **diff_index_argv = *blame->commit->parent_id
6158 ? diff_parent_argv : diff_no_parent_argv;
6160 open_argv(view, diff, diff_index_argv, NULL, flags);
6161 if (diff->pipe)
6162 string_copy_rev(diff->ref, NULL_ID);
6163 } else {
6164 open_view(view, REQ_VIEW_DIFF, flags);
6166 break;
6168 default:
6169 return request;
6172 return REQ_NONE;
6175 static bool
6176 blame_grep(struct view *view, struct line *line)
6178 struct blame *blame = line->data;
6179 struct blame_commit *commit = blame->commit;
6180 const char *text[] = {
6181 blame->text,
6182 commit ? commit->title : "",
6183 commit ? commit->id : "",
6184 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6185 commit ? mkdate(&commit->time, opt_date) : "",
6186 NULL
6189 return grep_text(view, text);
6192 static void
6193 blame_select(struct view *view, struct line *line)
6195 struct blame *blame = line->data;
6196 struct blame_commit *commit = blame->commit;
6198 if (!commit)
6199 return;
6201 if (string_rev_is_null(commit->id))
6202 string_ncopy(ref_commit, "HEAD", 4);
6203 else
6204 string_copy_rev(ref_commit, commit->id);
6207 static struct view_ops blame_ops = {
6208 "line",
6209 { "blame" },
6210 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6211 sizeof(struct blame_state),
6212 blame_open,
6213 blame_read,
6214 blame_draw,
6215 blame_request,
6216 blame_grep,
6217 blame_select,
6221 * Branch backend
6224 struct branch {
6225 const struct ident *author; /* Author of the last commit. */
6226 struct time time; /* Date of the last activity. */
6227 char title[128]; /* First line of the commit message. */
6228 const struct ref *ref; /* Name and commit ID information. */
6231 static const struct ref branch_all;
6232 #define BRANCH_ALL_NAME "All branches"
6233 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6235 static const enum sort_field branch_sort_fields[] = {
6236 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6238 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6240 struct branch_state {
6241 char id[SIZEOF_REV];
6242 size_t max_ref_length;
6245 static int
6246 branch_compare(const void *l1, const void *l2)
6248 const struct branch *branch1 = ((const struct line *) l1)->data;
6249 const struct branch *branch2 = ((const struct line *) l2)->data;
6251 if (branch_is_all(branch1))
6252 return -1;
6253 else if (branch_is_all(branch2))
6254 return 1;
6256 switch (get_sort_field(branch_sort_state)) {
6257 case ORDERBY_DATE:
6258 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6260 case ORDERBY_AUTHOR:
6261 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6263 case ORDERBY_NAME:
6264 default:
6265 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6269 static bool
6270 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6272 struct branch_state *state = view->private;
6273 struct branch *branch = line->data;
6274 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6275 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6277 if (draw_lineno(view, lineno))
6278 return TRUE;
6280 if (draw_date(view, &branch->time))
6281 return TRUE;
6283 if (draw_author(view, branch->author))
6284 return TRUE;
6286 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6287 return TRUE;
6289 if (draw_id(view, branch->ref->id))
6290 return TRUE;
6292 draw_text(view, LINE_DEFAULT, branch->title);
6293 return TRUE;
6296 static enum request
6297 branch_request(struct view *view, enum request request, struct line *line)
6299 struct branch *branch = line->data;
6301 switch (request) {
6302 case REQ_REFRESH:
6303 load_refs(TRUE);
6304 refresh_view(view);
6305 return REQ_NONE;
6307 case REQ_TOGGLE_SORT_FIELD:
6308 case REQ_TOGGLE_SORT_ORDER:
6309 sort_view(view, request, &branch_sort_state, branch_compare);
6310 return REQ_NONE;
6312 case REQ_ENTER:
6314 const struct ref *ref = branch->ref;
6315 const char *all_branches_argv[] = {
6316 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6318 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6320 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6321 return REQ_NONE;
6323 case REQ_JUMP_COMMIT:
6325 int lineno;
6327 for (lineno = 0; lineno < view->lines; lineno++) {
6328 struct branch *branch = view->line[lineno].data;
6330 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6331 select_view_line(view, lineno);
6332 report_clear();
6333 return REQ_NONE;
6337 default:
6338 return request;
6342 static bool
6343 branch_read(struct view *view, char *line)
6345 struct branch_state *state = view->private;
6346 const char *title = NULL;
6347 const struct ident *author = NULL;
6348 struct time time = {};
6349 size_t i;
6351 if (!line)
6352 return TRUE;
6354 switch (get_line_type(line)) {
6355 case LINE_COMMIT:
6356 string_copy_rev_from_commit_line(state->id, line);
6357 return TRUE;
6359 case LINE_AUTHOR:
6360 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6361 break;
6363 default:
6364 title = line + STRING_SIZE("title ");
6367 for (i = 0; i < view->lines; i++) {
6368 struct branch *branch = view->line[i].data;
6370 if (strcmp(branch->ref->id, state->id))
6371 continue;
6373 if (author) {
6374 branch->author = author;
6375 branch->time = time;
6378 if (title)
6379 string_expand(branch->title, sizeof(branch->title), title, 1);
6381 view->line[i].dirty = TRUE;
6384 return TRUE;
6387 static bool
6388 branch_open_visitor(void *data, const struct ref *ref)
6390 struct view *view = data;
6391 struct branch_state *state = view->private;
6392 struct branch *branch;
6393 bool is_all = ref == &branch_all;
6394 size_t ref_length;
6396 if (ref->tag || ref->ltag)
6397 return TRUE;
6399 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6400 return FALSE;
6402 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6403 if (ref_length > state->max_ref_length)
6404 state->max_ref_length = ref_length;
6406 branch->ref = ref;
6407 return TRUE;
6410 static bool
6411 branch_open(struct view *view, enum open_flags flags)
6413 const char *branch_log[] = {
6414 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
6415 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6416 "--all", "--simplify-by-decoration", NULL
6419 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6420 report("Failed to load branch data");
6421 return FALSE;
6424 branch_open_visitor(view, &branch_all);
6425 foreach_ref(branch_open_visitor, view);
6427 return TRUE;
6430 static bool
6431 branch_grep(struct view *view, struct line *line)
6433 struct branch *branch = line->data;
6434 const char *text[] = {
6435 branch->ref->name,
6436 mkauthor(branch->author, opt_author_width, opt_author),
6437 NULL
6440 return grep_text(view, text);
6443 static void
6444 branch_select(struct view *view, struct line *line)
6446 struct branch *branch = line->data;
6448 if (branch_is_all(branch)) {
6449 string_copy(view->ref, BRANCH_ALL_NAME);
6450 return;
6452 string_copy_rev(view->ref, branch->ref->id);
6453 string_copy_rev(ref_commit, branch->ref->id);
6454 string_copy_rev(ref_head, branch->ref->id);
6455 string_copy_rev(ref_branch, branch->ref->name);
6458 static struct view_ops branch_ops = {
6459 "branch",
6460 { "branch" },
6461 VIEW_NO_FLAGS,
6462 sizeof(struct branch_state),
6463 branch_open,
6464 branch_read,
6465 branch_draw,
6466 branch_request,
6467 branch_grep,
6468 branch_select,
6472 * Status backend
6475 struct status {
6476 char status;
6477 struct {
6478 mode_t mode;
6479 char rev[SIZEOF_REV];
6480 char name[SIZEOF_STR];
6481 } old;
6482 struct {
6483 mode_t mode;
6484 char rev[SIZEOF_REV];
6485 char name[SIZEOF_STR];
6486 } new;
6489 static char status_onbranch[SIZEOF_STR];
6490 static struct status stage_status;
6491 static enum line_type stage_line_type;
6493 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6495 /* This should work even for the "On branch" line. */
6496 static inline bool
6497 status_has_none(struct view *view, struct line *line)
6499 return view_has_line(view, line) && !line[1].data;
6502 /* Get fields from the diff line:
6503 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6505 static inline bool
6506 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6508 const char *old_mode = buf + 1;
6509 const char *new_mode = buf + 8;
6510 const char *old_rev = buf + 15;
6511 const char *new_rev = buf + 56;
6512 const char *status = buf + 97;
6514 if (bufsize < 98 ||
6515 old_mode[-1] != ':' ||
6516 new_mode[-1] != ' ' ||
6517 old_rev[-1] != ' ' ||
6518 new_rev[-1] != ' ' ||
6519 status[-1] != ' ')
6520 return FALSE;
6522 file->status = *status;
6524 string_copy_rev(file->old.rev, old_rev);
6525 string_copy_rev(file->new.rev, new_rev);
6527 file->old.mode = strtoul(old_mode, NULL, 8);
6528 file->new.mode = strtoul(new_mode, NULL, 8);
6530 file->old.name[0] = file->new.name[0] = 0;
6532 return TRUE;
6535 static bool
6536 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6538 struct status *unmerged = NULL;
6539 char *buf;
6540 struct io io;
6542 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6543 return FALSE;
6545 add_line_nodata(view, type);
6547 while ((buf = io_get(&io, 0, TRUE))) {
6548 struct status *file = unmerged;
6550 if (!file) {
6551 if (!add_line_alloc(view, &file, type, 0, FALSE))
6552 goto error_out;
6555 /* Parse diff info part. */
6556 if (status) {
6557 file->status = status;
6558 if (status == 'A')
6559 string_copy(file->old.rev, NULL_ID);
6561 } else if (!file->status || file == unmerged) {
6562 if (!status_get_diff(file, buf, strlen(buf)))
6563 goto error_out;
6565 buf = io_get(&io, 0, TRUE);
6566 if (!buf)
6567 break;
6569 /* Collapse all modified entries that follow an
6570 * associated unmerged entry. */
6571 if (unmerged == file) {
6572 unmerged->status = 'U';
6573 unmerged = NULL;
6574 } else if (file->status == 'U') {
6575 unmerged = file;
6579 /* Grab the old name for rename/copy. */
6580 if (!*file->old.name &&
6581 (file->status == 'R' || file->status == 'C')) {
6582 string_ncopy(file->old.name, buf, strlen(buf));
6584 buf = io_get(&io, 0, TRUE);
6585 if (!buf)
6586 break;
6589 /* git-ls-files just delivers a NUL separated list of
6590 * file names similar to the second half of the
6591 * git-diff-* output. */
6592 string_ncopy(file->new.name, buf, strlen(buf));
6593 if (!*file->old.name)
6594 string_copy(file->old.name, file->new.name);
6595 file = NULL;
6598 if (io_error(&io)) {
6599 error_out:
6600 io_done(&io);
6601 return FALSE;
6604 if (!view->line[view->lines - 1].data)
6605 add_line_nodata(view, LINE_STAT_NONE);
6607 io_done(&io);
6608 return TRUE;
6611 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6612 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6614 static const char *status_list_other_argv[] = {
6615 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6618 static const char *status_list_no_head_argv[] = {
6619 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6622 static const char *update_index_argv[] = {
6623 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6626 /* Restore the previous line number to stay in the context or select a
6627 * line with something that can be updated. */
6628 static void
6629 status_restore(struct view *view)
6631 if (!check_position(&view->prev_pos))
6632 return;
6634 if (view->prev_pos.lineno >= view->lines)
6635 view->prev_pos.lineno = view->lines - 1;
6636 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6637 view->prev_pos.lineno++;
6638 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6639 view->prev_pos.lineno--;
6641 /* If the above fails, always skip the "On branch" line. */
6642 if (view->prev_pos.lineno < view->lines)
6643 view->pos.lineno = view->prev_pos.lineno;
6644 else
6645 view->pos.lineno = 1;
6647 if (view->prev_pos.offset > view->pos.lineno)
6648 view->pos.offset = view->pos.lineno;
6649 else if (view->prev_pos.offset < view->lines)
6650 view->pos.offset = view->prev_pos.offset;
6652 clear_position(&view->prev_pos);
6655 static void
6656 status_update_onbranch(void)
6658 static const char *paths[][2] = {
6659 { "rebase-apply/rebasing", "Rebasing" },
6660 { "rebase-apply/applying", "Applying mailbox" },
6661 { "rebase-apply/", "Rebasing mailbox" },
6662 { "rebase-merge/interactive", "Interactive rebase" },
6663 { "rebase-merge/", "Rebase merge" },
6664 { "MERGE_HEAD", "Merging" },
6665 { "BISECT_LOG", "Bisecting" },
6666 { "HEAD", "On branch" },
6668 char buf[SIZEOF_STR];
6669 struct stat stat;
6670 int i;
6672 if (is_initial_commit()) {
6673 string_copy(status_onbranch, "Initial commit");
6674 return;
6677 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6678 char *head = opt_head;
6680 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6681 lstat(buf, &stat) < 0)
6682 continue;
6684 if (!*opt_head) {
6685 struct io io;
6687 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6688 io_read_buf(&io, buf, sizeof(buf))) {
6689 head = buf;
6690 if (!prefixcmp(head, "refs/heads/"))
6691 head += STRING_SIZE("refs/heads/");
6695 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6696 string_copy(status_onbranch, opt_head);
6697 return;
6700 string_copy(status_onbranch, "Not currently on any branch");
6703 /* First parse staged info using git-diff-index(1), then parse unstaged
6704 * info using git-diff-files(1), and finally untracked files using
6705 * git-ls-files(1). */
6706 static bool
6707 status_open(struct view *view, enum open_flags flags)
6709 const char **staged_argv = is_initial_commit() ?
6710 status_list_no_head_argv : status_diff_index_argv;
6711 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6713 if (opt_is_inside_work_tree == FALSE) {
6714 report("The status view requires a working tree");
6715 return FALSE;
6718 reset_view(view);
6720 add_line_nodata(view, LINE_STAT_HEAD);
6721 status_update_onbranch();
6723 io_run_bg(update_index_argv);
6725 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6726 opt_untracked_dirs_content ? NULL : "--directory";
6728 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6729 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6730 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6731 report("Failed to load status data");
6732 return FALSE;
6735 /* Restore the exact position or use the specialized restore
6736 * mode? */
6737 status_restore(view);
6738 return TRUE;
6741 static bool
6742 status_draw(struct view *view, struct line *line, unsigned int lineno)
6744 struct status *status = line->data;
6745 enum line_type type;
6746 const char *text;
6748 if (!status) {
6749 switch (line->type) {
6750 case LINE_STAT_STAGED:
6751 type = LINE_STAT_SECTION;
6752 text = "Changes to be committed:";
6753 break;
6755 case LINE_STAT_UNSTAGED:
6756 type = LINE_STAT_SECTION;
6757 text = "Changed but not updated:";
6758 break;
6760 case LINE_STAT_UNTRACKED:
6761 type = LINE_STAT_SECTION;
6762 text = "Untracked files:";
6763 break;
6765 case LINE_STAT_NONE:
6766 type = LINE_DEFAULT;
6767 text = " (no files)";
6768 break;
6770 case LINE_STAT_HEAD:
6771 type = LINE_STAT_HEAD;
6772 text = status_onbranch;
6773 break;
6775 default:
6776 return FALSE;
6778 } else {
6779 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6781 buf[0] = status->status;
6782 if (draw_text(view, line->type, buf))
6783 return TRUE;
6784 type = LINE_DEFAULT;
6785 text = status->new.name;
6788 draw_text(view, type, text);
6789 return TRUE;
6792 static enum request
6793 status_enter(struct view *view, struct line *line)
6795 struct status *status = line->data;
6796 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6798 if (line->type == LINE_STAT_NONE ||
6799 (!status && line[1].type == LINE_STAT_NONE)) {
6800 report("No file to diff");
6801 return REQ_NONE;
6804 switch (line->type) {
6805 case LINE_STAT_STAGED:
6806 case LINE_STAT_UNSTAGED:
6807 break;
6809 case LINE_STAT_UNTRACKED:
6810 if (!status) {
6811 report("No file to show");
6812 return REQ_NONE;
6815 if (!suffixcmp(status->new.name, -1, "/")) {
6816 report("Cannot display a directory");
6817 return REQ_NONE;
6819 break;
6821 case LINE_STAT_HEAD:
6822 return REQ_NONE;
6824 default:
6825 die("line type %d not handled in switch", line->type);
6828 if (status) {
6829 stage_status = *status;
6830 } else {
6831 memset(&stage_status, 0, sizeof(stage_status));
6834 stage_line_type = line->type;
6836 open_view(view, REQ_VIEW_STAGE, flags);
6837 return REQ_NONE;
6840 static bool
6841 status_exists(struct view *view, struct status *status, enum line_type type)
6843 unsigned long lineno;
6845 for (lineno = 0; lineno < view->lines; lineno++) {
6846 struct line *line = &view->line[lineno];
6847 struct status *pos = line->data;
6849 if (line->type != type)
6850 continue;
6851 if (!pos && (!status || !status->status) && line[1].data) {
6852 select_view_line(view, lineno);
6853 return TRUE;
6855 if (pos && !strcmp(status->new.name, pos->new.name)) {
6856 select_view_line(view, lineno);
6857 return TRUE;
6861 return FALSE;
6865 static bool
6866 status_update_prepare(struct io *io, enum line_type type)
6868 const char *staged_argv[] = {
6869 "git", "update-index", "-z", "--index-info", NULL
6871 const char *others_argv[] = {
6872 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6875 switch (type) {
6876 case LINE_STAT_STAGED:
6877 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6879 case LINE_STAT_UNSTAGED:
6880 case LINE_STAT_UNTRACKED:
6881 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6883 default:
6884 die("line type %d not handled in switch", type);
6885 return FALSE;
6889 static bool
6890 status_update_write(struct io *io, struct status *status, enum line_type type)
6892 switch (type) {
6893 case LINE_STAT_STAGED:
6894 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6895 status->old.rev, status->old.name, 0);
6897 case LINE_STAT_UNSTAGED:
6898 case LINE_STAT_UNTRACKED:
6899 return io_printf(io, "%s%c", status->new.name, 0);
6901 default:
6902 die("line type %d not handled in switch", type);
6903 return FALSE;
6907 static bool
6908 status_update_file(struct status *status, enum line_type type)
6910 struct io io;
6911 bool result;
6913 if (!status_update_prepare(&io, type))
6914 return FALSE;
6916 result = status_update_write(&io, status, type);
6917 return io_done(&io) && result;
6920 static bool
6921 status_update_files(struct view *view, struct line *line)
6923 char buf[sizeof(view->ref)];
6924 struct io io;
6925 bool result = TRUE;
6926 struct line *pos;
6927 int files = 0;
6928 int file, done;
6929 int cursor_y = -1, cursor_x = -1;
6931 if (!status_update_prepare(&io, line->type))
6932 return FALSE;
6934 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6935 files++;
6937 string_copy(buf, view->ref);
6938 getsyx(cursor_y, cursor_x);
6939 for (file = 0, done = 5; result && file < files; line++, file++) {
6940 int almost_done = file * 100 / files;
6942 if (almost_done > done) {
6943 done = almost_done;
6944 string_format(view->ref, "updating file %u of %u (%d%% done)",
6945 file, files, done);
6946 update_view_title(view);
6947 setsyx(cursor_y, cursor_x);
6948 doupdate();
6950 result = status_update_write(&io, line->data, line->type);
6952 string_copy(view->ref, buf);
6954 return io_done(&io) && result;
6957 static bool
6958 status_update(struct view *view)
6960 struct line *line = &view->line[view->pos.lineno];
6962 assert(view->lines);
6964 if (!line->data) {
6965 if (status_has_none(view, line)) {
6966 report("Nothing to update");
6967 return FALSE;
6970 if (!status_update_files(view, line + 1)) {
6971 report("Failed to update file status");
6972 return FALSE;
6975 } else if (!status_update_file(line->data, line->type)) {
6976 report("Failed to update file status");
6977 return FALSE;
6980 return TRUE;
6983 static bool
6984 status_revert(struct status *status, enum line_type type, bool has_none)
6986 if (!status || type != LINE_STAT_UNSTAGED) {
6987 if (type == LINE_STAT_STAGED) {
6988 report("Cannot revert changes to staged files");
6989 } else if (type == LINE_STAT_UNTRACKED) {
6990 report("Cannot revert changes to untracked files");
6991 } else if (has_none) {
6992 report("Nothing to revert");
6993 } else {
6994 report("Cannot revert changes to multiple files");
6997 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6998 char mode[10] = "100644";
6999 const char *reset_argv[] = {
7000 "git", "update-index", "--cacheinfo", mode,
7001 status->old.rev, status->old.name, NULL
7003 const char *checkout_argv[] = {
7004 "git", "checkout", "--", status->old.name, NULL
7007 if (status->status == 'U') {
7008 string_format(mode, "%5o", status->old.mode);
7010 if (status->old.mode == 0 && status->new.mode == 0) {
7011 reset_argv[2] = "--force-remove";
7012 reset_argv[3] = status->old.name;
7013 reset_argv[4] = NULL;
7016 if (!io_run_fg(reset_argv, opt_cdup))
7017 return FALSE;
7018 if (status->old.mode == 0 && status->new.mode == 0)
7019 return TRUE;
7022 return io_run_fg(checkout_argv, opt_cdup);
7025 return FALSE;
7028 static enum request
7029 status_request(struct view *view, enum request request, struct line *line)
7031 struct status *status = line->data;
7033 switch (request) {
7034 case REQ_STATUS_UPDATE:
7035 if (!status_update(view))
7036 return REQ_NONE;
7037 break;
7039 case REQ_STATUS_REVERT:
7040 if (!status_revert(status, line->type, status_has_none(view, line)))
7041 return REQ_NONE;
7042 break;
7044 case REQ_STATUS_MERGE:
7045 if (!status || status->status != 'U') {
7046 report("Merging only possible for files with unmerged status ('U').");
7047 return REQ_NONE;
7049 open_mergetool(status->new.name);
7050 break;
7052 case REQ_EDIT:
7053 if (!status)
7054 return request;
7055 if (status->status == 'D') {
7056 report("File has been deleted.");
7057 return REQ_NONE;
7060 open_editor(status->new.name, 0);
7061 break;
7063 case REQ_VIEW_BLAME:
7064 if (status)
7065 opt_ref[0] = 0;
7066 return request;
7068 case REQ_ENTER:
7069 /* After returning the status view has been split to
7070 * show the stage view. No further reloading is
7071 * necessary. */
7072 return status_enter(view, line);
7074 case REQ_REFRESH:
7075 /* Load the current branch information and then the view. */
7076 load_refs(TRUE);
7077 break;
7079 default:
7080 return request;
7083 refresh_view(view);
7085 return REQ_NONE;
7088 static bool
7089 status_stage_info_(char *buf, size_t bufsize,
7090 enum line_type type, struct status *status)
7092 const char *file = status ? status->new.name : "";
7093 const char *info;
7095 switch (type) {
7096 case LINE_STAT_STAGED:
7097 if (status && status->status)
7098 info = "Staged changes to %s";
7099 else
7100 info = "Staged changes";
7101 break;
7103 case LINE_STAT_UNSTAGED:
7104 if (status && status->status)
7105 info = "Unstaged changes to %s";
7106 else
7107 info = "Unstaged changes";
7108 break;
7110 case LINE_STAT_UNTRACKED:
7111 info = "Untracked file %s";
7112 break;
7114 case LINE_STAT_HEAD:
7115 default:
7116 info = "";
7119 return string_nformat(buf, bufsize, NULL, info, file);
7121 #define status_stage_info(buf, type, status) \
7122 status_stage_info_(buf, sizeof(buf), type, status)
7124 static void
7125 status_select(struct view *view, struct line *line)
7127 struct status *status = line->data;
7128 char file[SIZEOF_STR] = "all files";
7129 const char *text;
7130 const char *key;
7132 if (status && !string_format(file, "'%s'", status->new.name))
7133 return;
7135 if (!status && line[1].type == LINE_STAT_NONE)
7136 line++;
7138 switch (line->type) {
7139 case LINE_STAT_STAGED:
7140 text = "Press %s to unstage %s for commit";
7141 break;
7143 case LINE_STAT_UNSTAGED:
7144 text = "Press %s to stage %s for commit";
7145 break;
7147 case LINE_STAT_UNTRACKED:
7148 text = "Press %s to stage %s for addition";
7149 break;
7151 case LINE_STAT_HEAD:
7152 case LINE_STAT_NONE:
7153 text = "Nothing to update";
7154 break;
7156 default:
7157 die("line type %d not handled in switch", line->type);
7160 if (status && status->status == 'U') {
7161 text = "Press %s to resolve conflict in %s";
7162 key = get_view_key(view, REQ_STATUS_MERGE);
7164 } else {
7165 key = get_view_key(view, REQ_STATUS_UPDATE);
7168 string_format(view->ref, text, key, file);
7169 status_stage_info(ref_status, line->type, status);
7170 if (status)
7171 string_copy(opt_file, status->new.name);
7174 static bool
7175 status_grep(struct view *view, struct line *line)
7177 struct status *status = line->data;
7179 if (status) {
7180 const char buf[2] = { status->status, 0 };
7181 const char *text[] = { status->new.name, buf, NULL };
7183 return grep_text(view, text);
7186 return FALSE;
7189 static struct view_ops status_ops = {
7190 "file",
7191 { "status" },
7192 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7194 status_open,
7195 NULL,
7196 status_draw,
7197 status_request,
7198 status_grep,
7199 status_select,
7203 struct stage_state {
7204 struct diff_state diff;
7205 size_t chunks;
7206 int *chunk;
7209 static bool
7210 stage_diff_write(struct io *io, struct line *line, struct line *end)
7212 while (line < end) {
7213 if (!io_write(io, line->data, strlen(line->data)) ||
7214 !io_write(io, "\n", 1))
7215 return FALSE;
7216 line++;
7217 if (line->type == LINE_DIFF_CHUNK ||
7218 line->type == LINE_DIFF_HEADER)
7219 break;
7222 return TRUE;
7225 static bool
7226 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7228 const char *apply_argv[SIZEOF_ARG] = {
7229 "git", "apply", "--whitespace=nowarn", NULL
7231 struct line *diff_hdr;
7232 struct io io;
7233 int argc = 3;
7235 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7236 if (!diff_hdr)
7237 return FALSE;
7239 if (!revert)
7240 apply_argv[argc++] = "--cached";
7241 if (line != NULL)
7242 apply_argv[argc++] = "--unidiff-zero";
7243 if (revert || stage_line_type == LINE_STAT_STAGED)
7244 apply_argv[argc++] = "-R";
7245 apply_argv[argc++] = "-";
7246 apply_argv[argc++] = NULL;
7247 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7248 return FALSE;
7250 if (line != NULL) {
7251 int lineno = 0;
7252 struct line *context = chunk + 1;
7253 const char *markers[] = {
7254 line->type == LINE_DIFF_DEL ? "" : ",0",
7255 line->type == LINE_DIFF_DEL ? ",0" : "",
7258 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7260 while (context < line) {
7261 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7262 break;
7263 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7264 lineno++;
7266 context++;
7269 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7270 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7271 lineno, markers[0], lineno, markers[1]) ||
7272 !stage_diff_write(&io, line, line + 1)) {
7273 chunk = NULL;
7275 } else {
7276 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7277 !stage_diff_write(&io, chunk, view->line + view->lines))
7278 chunk = NULL;
7281 io_done(&io);
7283 return chunk ? TRUE : FALSE;
7286 static bool
7287 stage_update(struct view *view, struct line *line, bool single)
7289 struct line *chunk = NULL;
7291 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7292 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7294 if (chunk) {
7295 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7296 report("Failed to apply chunk");
7297 return FALSE;
7300 } else if (!stage_status.status) {
7301 view = view->parent;
7303 for (line = view->line; view_has_line(view, line); line++)
7304 if (line->type == stage_line_type)
7305 break;
7307 if (!status_update_files(view, line + 1)) {
7308 report("Failed to update files");
7309 return FALSE;
7312 } else if (!status_update_file(&stage_status, stage_line_type)) {
7313 report("Failed to update file");
7314 return FALSE;
7317 return TRUE;
7320 static bool
7321 stage_revert(struct view *view, struct line *line)
7323 struct line *chunk = NULL;
7325 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7326 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7328 if (chunk) {
7329 if (!prompt_yesno("Are you sure you want to revert changes?"))
7330 return FALSE;
7332 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7333 report("Failed to revert chunk");
7334 return FALSE;
7336 return TRUE;
7338 } else {
7339 return status_revert(stage_status.status ? &stage_status : NULL,
7340 stage_line_type, FALSE);
7345 static void
7346 stage_next(struct view *view, struct line *line)
7348 struct stage_state *state = view->private;
7349 int i;
7351 if (!state->chunks) {
7352 for (line = view->line; view_has_line(view, line); line++) {
7353 if (line->type != LINE_DIFF_CHUNK)
7354 continue;
7356 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7357 report("Allocation failure");
7358 return;
7361 state->chunk[state->chunks++] = line - view->line;
7365 for (i = 0; i < state->chunks; i++) {
7366 if (state->chunk[i] > view->pos.lineno) {
7367 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7368 report("Chunk %d of %zd", i + 1, state->chunks);
7369 return;
7373 report("No next chunk found");
7376 static enum request
7377 stage_request(struct view *view, enum request request, struct line *line)
7379 switch (request) {
7380 case REQ_STATUS_UPDATE:
7381 if (!stage_update(view, line, FALSE))
7382 return REQ_NONE;
7383 break;
7385 case REQ_STATUS_REVERT:
7386 if (!stage_revert(view, line))
7387 return REQ_NONE;
7388 break;
7390 case REQ_STAGE_UPDATE_LINE:
7391 if (stage_line_type == LINE_STAT_UNTRACKED ||
7392 stage_status.status == 'A') {
7393 report("Staging single lines is not supported for new files");
7394 return REQ_NONE;
7396 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7397 report("Please select a change to stage");
7398 return REQ_NONE;
7400 if (!stage_update(view, line, TRUE))
7401 return REQ_NONE;
7402 break;
7404 case REQ_STAGE_NEXT:
7405 if (stage_line_type == LINE_STAT_UNTRACKED) {
7406 report("File is untracked; press %s to add",
7407 get_view_key(view, REQ_STATUS_UPDATE));
7408 return REQ_NONE;
7410 stage_next(view, line);
7411 return REQ_NONE;
7413 case REQ_EDIT:
7414 if (!stage_status.new.name[0])
7415 return diff_common_edit(view, request, line);
7417 if (stage_status.status == 'D') {
7418 report("File has been deleted.");
7419 return REQ_NONE;
7422 if (stage_line_type == LINE_STAT_UNTRACKED) {
7423 open_editor(stage_status.new.name, (line - view->line) + 1);
7424 } else {
7425 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7427 break;
7429 case REQ_REFRESH:
7430 /* Reload everything(including current branch information) ... */
7431 load_refs(TRUE);
7432 break;
7434 case REQ_VIEW_BLAME:
7435 if (stage_status.new.name[0]) {
7436 string_copy(opt_file, stage_status.new.name);
7437 opt_ref[0] = 0;
7439 return request;
7441 case REQ_ENTER:
7442 return diff_common_enter(view, request, line);
7444 case REQ_DIFF_CONTEXT_UP:
7445 case REQ_DIFF_CONTEXT_DOWN:
7446 if (!update_diff_context(request))
7447 return REQ_NONE;
7448 break;
7450 default:
7451 return request;
7454 refresh_view(view->parent);
7456 /* Check whether the staged entry still exists, and close the
7457 * stage view if it doesn't. */
7458 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7459 status_restore(view->parent);
7460 return REQ_VIEW_CLOSE;
7463 refresh_view(view);
7465 return REQ_NONE;
7468 static bool
7469 stage_open(struct view *view, enum open_flags flags)
7471 static const char *no_head_diff_argv[] = {
7472 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7473 stage_status.new.name)
7475 static const char *index_show_argv[] = {
7476 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7477 stage_status.old.name, stage_status.new.name)
7479 static const char *files_show_argv[] = {
7480 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7481 stage_status.old.name, stage_status.new.name)
7483 /* Diffs for unmerged entries are empty when passing the new
7484 * path, so leave out the new path. */
7485 static const char *files_unmerged_argv[] = {
7486 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
7487 opt_diff_context_arg, opt_ignore_space_arg, "--",
7488 stage_status.old.name, NULL
7490 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7491 const char **argv = NULL;
7493 if (!stage_line_type) {
7494 report("No stage content, press %s to open the status view and choose file",
7495 get_view_key(view, REQ_VIEW_STATUS));
7496 return FALSE;
7499 view->encoding = NULL;
7501 switch (stage_line_type) {
7502 case LINE_STAT_STAGED:
7503 if (is_initial_commit()) {
7504 argv = no_head_diff_argv;
7505 } else {
7506 argv = index_show_argv;
7508 break;
7510 case LINE_STAT_UNSTAGED:
7511 if (stage_status.status != 'U')
7512 argv = files_show_argv;
7513 else
7514 argv = files_unmerged_argv;
7515 break;
7517 case LINE_STAT_UNTRACKED:
7518 argv = file_argv;
7519 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
7520 break;
7522 case LINE_STAT_HEAD:
7523 default:
7524 die("line type %d not handled in switch", stage_line_type);
7527 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7528 || !argv_copy(&view->argv, argv)) {
7529 report("Failed to open staged view");
7530 return FALSE;
7533 view->vid[0] = 0;
7534 view->dir = opt_cdup;
7535 return begin_update(view, NULL, NULL, flags);
7538 static bool
7539 stage_read(struct view *view, char *data)
7541 struct stage_state *state = view->private;
7543 if (stage_line_type == LINE_STAT_UNTRACKED)
7544 return pager_common_read(view, data, LINE_DEFAULT);
7546 if (data && diff_common_read(view, data, &state->diff))
7547 return TRUE;
7549 return pager_read(view, data);
7552 static struct view_ops stage_ops = {
7553 "line",
7554 { "stage" },
7555 VIEW_DIFF_LIKE,
7556 sizeof(struct stage_state),
7557 stage_open,
7558 stage_read,
7559 diff_common_draw,
7560 stage_request,
7561 pager_grep,
7562 pager_select,
7567 * Revision graph
7570 static const enum line_type graph_colors[] = {
7571 LINE_PALETTE_0,
7572 LINE_PALETTE_1,
7573 LINE_PALETTE_2,
7574 LINE_PALETTE_3,
7575 LINE_PALETTE_4,
7576 LINE_PALETTE_5,
7577 LINE_PALETTE_6,
7580 static enum line_type get_graph_color(struct graph_symbol *symbol)
7582 if (symbol->commit)
7583 return LINE_GRAPH_COMMIT;
7584 assert(symbol->color < ARRAY_SIZE(graph_colors));
7585 return graph_colors[symbol->color];
7588 static bool
7589 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7591 const char *chars = graph_symbol_to_utf8(symbol);
7593 return draw_text(view, color, chars + !!first);
7596 static bool
7597 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7599 const char *chars = graph_symbol_to_ascii(symbol);
7601 return draw_text(view, color, chars + !!first);
7604 static bool
7605 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7607 const chtype *chars = graph_symbol_to_chtype(symbol);
7609 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7612 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7614 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7616 static const draw_graph_fn fns[] = {
7617 draw_graph_ascii,
7618 draw_graph_chtype,
7619 draw_graph_utf8
7621 draw_graph_fn fn = fns[opt_line_graphics];
7622 int i;
7624 for (i = 0; i < canvas->size; i++) {
7625 struct graph_symbol *symbol = &canvas->symbols[i];
7626 enum line_type color = get_graph_color(symbol);
7628 if (fn(view, symbol, color, i == 0))
7629 return TRUE;
7632 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7636 * Main view backend
7639 struct commit {
7640 char id[SIZEOF_REV]; /* SHA1 ID. */
7641 const struct ident *author; /* Author of the commit. */
7642 struct time time; /* Date from the author ident. */
7643 struct graph_canvas graph; /* Ancestry chain graphics. */
7644 char title[1]; /* First line of the commit message. */
7647 struct main_state {
7648 struct graph graph;
7649 struct commit current;
7650 int id_width;
7651 bool in_header;
7652 bool added_changes_commits;
7653 bool with_graph;
7656 static void
7657 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7659 struct main_state *state = view->private;
7661 string_copy_rev(commit->id, ids);
7662 if (state->with_graph)
7663 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7666 static struct commit *
7667 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7668 const char *title, bool custom)
7670 struct main_state *state = view->private;
7671 size_t titlelen = strlen(title);
7672 struct commit *commit;
7673 char buf[SIZEOF_STR / 2];
7675 /* FIXME: More graceful handling of titles; append "..." to
7676 * shortened titles, etc. */
7677 string_expand(buf, sizeof(buf), title, 1);
7678 title = buf;
7679 titlelen = strlen(title);
7681 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7682 return NULL;
7684 *commit = *template;
7685 strncpy(commit->title, title, titlelen);
7686 state->graph.canvas = &commit->graph;
7687 memset(template, 0, sizeof(*template));
7688 return commit;
7691 static inline void
7692 main_flush_commit(struct view *view, struct commit *commit)
7694 if (*commit->id)
7695 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7698 static bool
7699 main_has_changes(const char *argv[])
7701 struct io io;
7703 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7704 return FALSE;
7705 io_done(&io);
7706 return io.status == 1;
7709 static void
7710 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7712 char ids[SIZEOF_STR] = NULL_ID " ";
7713 struct main_state *state = view->private;
7714 struct commit commit = {};
7715 struct timeval now;
7716 struct timezone tz;
7718 if (!parent)
7719 return;
7721 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7723 if (!gettimeofday(&now, &tz)) {
7724 commit.time.tz = tz.tz_minuteswest * 60;
7725 commit.time.sec = now.tv_sec - commit.time.tz;
7728 commit.author = &unknown_ident;
7729 main_register_commit(view, &commit, ids, FALSE);
7730 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7731 graph_render_parents(&state->graph);
7734 static void
7735 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7737 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7738 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7739 const char *staged_parent = NULL_ID;
7740 const char *unstaged_parent = parent;
7742 if (!is_head_commit(parent))
7743 return;
7745 state->added_changes_commits = TRUE;
7747 io_run_bg(update_index_argv);
7749 if (!main_has_changes(unstaged_argv)) {
7750 unstaged_parent = NULL;
7751 staged_parent = parent;
7754 if (!main_has_changes(staged_argv)) {
7755 staged_parent = NULL;
7758 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7759 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7762 static bool
7763 main_open(struct view *view, enum open_flags flags)
7765 static const char *main_argv[] = {
7766 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7768 struct main_state *state = view->private;
7770 state->with_graph = opt_rev_graph;
7771 return begin_update(view, NULL, main_argv, flags);
7774 static void
7775 main_done(struct view *view)
7777 int i;
7779 for (i = 0; i < view->lines; i++) {
7780 struct commit *commit = view->line[i].data;
7782 free(commit->graph.symbols);
7786 #define MAIN_NO_COMMIT_REFS 1
7787 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
7788 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
7790 static inline struct ref_list *
7791 main_get_commit_refs(struct line *line, struct commit *commit)
7793 struct ref_list *refs = NULL;
7795 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
7796 main_mark_no_commit_refs(line);
7798 return refs;
7801 static bool
7802 main_draw(struct view *view, struct line *line, unsigned int lineno)
7804 struct main_state *state = view->private;
7805 struct commit *commit = line->data;
7806 struct ref_list *refs = NULL;
7808 if (!commit->author)
7809 return FALSE;
7811 if (draw_lineno(view, lineno))
7812 return TRUE;
7814 if (opt_show_id) {
7815 if (state->id_width) {
7816 if (draw_formatted_field(view, LINE_ID, state->id_width,
7817 "stash@{%d}", line->lineno - 1))
7818 return TRUE;
7819 } else if (draw_id(view, commit->id)) {
7820 return TRUE;
7824 if (draw_date(view, &commit->time))
7825 return TRUE;
7827 if (draw_author(view, commit->author))
7828 return TRUE;
7830 if (state->with_graph && draw_graph(view, &commit->graph))
7831 return TRUE;
7833 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
7834 return TRUE;
7836 if (commit->title)
7837 draw_commit_title(view, commit->title, 0);
7838 return TRUE;
7841 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7842 static bool
7843 main_read(struct view *view, char *line)
7845 struct main_state *state = view->private;
7846 struct graph *graph = &state->graph;
7847 enum line_type type;
7848 struct commit *commit = &state->current;
7850 if (!line) {
7851 main_flush_commit(view, commit);
7853 if (!view->lines && !view->prev)
7854 die("No revisions match the given arguments.");
7855 if (view->lines > 0) {
7856 struct commit *last = view->line[view->lines - 1].data;
7858 view->line[view->lines - 1].dirty = 1;
7859 if (!last->author) {
7860 view->lines--;
7861 free(last);
7865 if (state->with_graph)
7866 done_graph(graph);
7867 return TRUE;
7870 type = get_line_type(line);
7871 if (type == LINE_COMMIT) {
7872 bool is_boundary;
7874 state->in_header = TRUE;
7875 line += STRING_SIZE("commit ");
7876 is_boundary = *line == '-';
7877 if (is_boundary || !isalnum(*line))
7878 line++;
7880 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7881 main_add_changes_commits(view, state, line);
7882 else
7883 main_flush_commit(view, commit);
7885 main_register_commit(view, &state->current, line, is_boundary);
7886 return TRUE;
7889 if (!*commit->id)
7890 return TRUE;
7892 /* Empty line separates the commit header from the log itself. */
7893 if (*line == '\0')
7894 state->in_header = FALSE;
7896 switch (type) {
7897 case LINE_PARENT:
7898 if (state->with_graph && !graph->has_parents)
7899 graph_add_parent(graph, line + STRING_SIZE("parent "));
7900 break;
7902 case LINE_AUTHOR:
7903 parse_author_line(line + STRING_SIZE("author "),
7904 &commit->author, &commit->time);
7905 if (state->with_graph)
7906 graph_render_parents(graph);
7907 break;
7909 default:
7910 /* Fill in the commit title if it has not already been set. */
7911 if (*commit->title)
7912 break;
7914 /* Skip lines in the commit header. */
7915 if (state->in_header)
7916 break;
7918 /* Require titles to start with a non-space character at the
7919 * offset used by git log. */
7920 if (strncmp(line, " ", 4))
7921 break;
7922 line += 4;
7923 /* Well, if the title starts with a whitespace character,
7924 * try to be forgiving. Otherwise we end up with no title. */
7925 while (isspace(*line))
7926 line++;
7927 if (*line == '\0')
7928 break;
7929 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
7932 return TRUE;
7935 static enum request
7936 main_request(struct view *view, enum request request, struct line *line)
7938 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7939 ? OPEN_SPLIT : OPEN_DEFAULT;
7941 switch (request) {
7942 case REQ_NEXT:
7943 case REQ_PREVIOUS:
7944 if (view_is_displayed(view) && display[0] != view)
7945 return request;
7946 /* Do not pass navigation requests to the branch view
7947 * when the main view is maximized. (GH #38) */
7948 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
7950 case REQ_VIEW_DIFF:
7951 case REQ_ENTER:
7952 if (view_is_displayed(view) && display[0] != view)
7953 maximize_view(view, TRUE);
7955 if (line->type == LINE_STAT_UNSTAGED
7956 || line->type == LINE_STAT_STAGED) {
7957 struct view *diff = VIEW(REQ_VIEW_DIFF);
7958 const char *diff_staged_argv[] = {
7959 GIT_DIFF_STAGED(opt_encoding_arg,
7960 opt_diff_context_arg,
7961 opt_ignore_space_arg, NULL, NULL)
7963 const char *diff_unstaged_argv[] = {
7964 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7965 opt_diff_context_arg,
7966 opt_ignore_space_arg, NULL, NULL)
7968 const char **diff_argv = line->type == LINE_STAT_STAGED
7969 ? diff_staged_argv : diff_unstaged_argv;
7971 open_argv(view, diff, diff_argv, NULL, flags);
7972 break;
7975 open_view(view, REQ_VIEW_DIFF, flags);
7976 break;
7978 case REQ_REFRESH:
7979 load_refs(TRUE);
7980 refresh_view(view);
7981 break;
7983 case REQ_JUMP_COMMIT:
7985 int lineno;
7987 for (lineno = 0; lineno < view->lines; lineno++) {
7988 struct commit *commit = view->line[lineno].data;
7990 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7991 select_view_line(view, lineno);
7992 report_clear();
7993 return REQ_NONE;
7997 report("Unable to find commit '%s'", opt_search);
7998 break;
8000 default:
8001 return request;
8004 return REQ_NONE;
8007 static bool
8008 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8010 struct ref_list *list;
8011 regmatch_t pmatch;
8012 size_t i;
8014 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8015 return FALSE;
8017 for (i = 0; i < list->size; i++) {
8018 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8019 return TRUE;
8022 return FALSE;
8025 static bool
8026 main_grep(struct view *view, struct line *line)
8028 struct commit *commit = line->data;
8029 const char *text[] = {
8030 commit->id,
8031 commit->title,
8032 mkauthor(commit->author, opt_author_width, opt_author),
8033 mkdate(&commit->time, opt_date),
8034 NULL
8037 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8040 static void
8041 main_select(struct view *view, struct line *line)
8043 struct commit *commit = line->data;
8045 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8046 string_ncopy(view->ref, commit->title, strlen(commit->title));
8047 else
8048 string_copy_rev(view->ref, commit->id);
8049 string_copy_rev(ref_commit, commit->id);
8052 static struct view_ops main_ops = {
8053 "commit",
8054 { "main" },
8055 VIEW_STDIN | VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8056 sizeof(struct main_state),
8057 main_open,
8058 main_read,
8059 main_draw,
8060 main_request,
8061 main_grep,
8062 main_select,
8063 main_done,
8066 static bool
8067 stash_open(struct view *view, enum open_flags flags)
8069 static const char *stash_argv[] = { "git", "stash", "list",
8070 opt_encoding_arg, "--no-color", "--pretty=raw", NULL };
8072 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8075 static bool
8076 stash_read(struct view *view, char *line)
8078 struct main_state *state = view->private;
8079 struct commit *commit = &state->current;
8081 if (!state->added_changes_commits) {
8082 state->added_changes_commits = TRUE;
8083 state->with_graph = FALSE;
8086 if (commit && line && get_line_type(line) == LINE_PP_REFLOG) {
8087 int id_width = STRING_SIZE("stash@{}") + count_digits(view->lines);
8089 if (state->id_width < id_width) {
8090 state->id_width = id_width;
8091 if (opt_show_id)
8092 view->force_redraw = TRUE;
8096 return main_read(view, line);
8099 static void
8100 stash_select(struct view *view, struct line *line)
8102 main_select(view, line);
8103 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8104 string_copy(view->ref, ref_stash);
8107 static struct view_ops stash_ops = {
8108 "stash",
8109 { "stash" },
8110 VIEW_SEND_CHILD_ENTER,
8111 sizeof(struct main_state),
8112 stash_open,
8113 stash_read,
8114 main_draw,
8115 main_request,
8116 main_grep,
8117 stash_select,
8121 * Status management
8124 /* Whether or not the curses interface has been initialized. */
8125 static bool cursed = FALSE;
8127 /* Terminal hacks and workarounds. */
8128 static bool use_scroll_redrawwin;
8129 static bool use_scroll_status_wclear;
8131 /* The status window is used for polling keystrokes. */
8132 static WINDOW *status_win;
8134 /* Reading from the prompt? */
8135 static bool input_mode = FALSE;
8137 static bool status_empty = FALSE;
8139 /* Update status and title window. */
8140 static void
8141 report(const char *msg, ...)
8143 struct view *view = display[current_view];
8145 if (input_mode)
8146 return;
8148 if (!view) {
8149 char buf[SIZEOF_STR];
8150 int retval;
8152 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8153 die("%s", buf);
8156 if (!status_empty || *msg) {
8157 va_list args;
8159 va_start(args, msg);
8161 wmove(status_win, 0, 0);
8162 if (view->has_scrolled && use_scroll_status_wclear)
8163 wclear(status_win);
8164 if (*msg) {
8165 vwprintw(status_win, msg, args);
8166 status_empty = FALSE;
8167 } else {
8168 status_empty = TRUE;
8170 wclrtoeol(status_win);
8171 wnoutrefresh(status_win);
8173 va_end(args);
8176 update_view_title(view);
8179 static void
8180 init_display(void)
8182 const char *term;
8183 int x, y;
8185 /* Initialize the curses library */
8186 if (isatty(STDIN_FILENO)) {
8187 cursed = !!initscr();
8188 opt_tty = stdin;
8189 } else {
8190 /* Leave stdin and stdout alone when acting as a pager. */
8191 opt_tty = fopen("/dev/tty", "r+");
8192 if (!opt_tty)
8193 die("Failed to open /dev/tty");
8194 cursed = !!newterm(NULL, opt_tty, opt_tty);
8197 if (!cursed)
8198 die("Failed to initialize curses");
8200 nonl(); /* Disable conversion and detect newlines from input. */
8201 cbreak(); /* Take input chars one at a time, no wait for \n */
8202 noecho(); /* Don't echo input */
8203 leaveok(stdscr, FALSE);
8205 if (has_colors())
8206 init_colors();
8208 getmaxyx(stdscr, y, x);
8209 status_win = newwin(1, x, y - 1, 0);
8210 if (!status_win)
8211 die("Failed to create status window");
8213 /* Enable keyboard mapping */
8214 keypad(status_win, TRUE);
8215 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8217 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8218 set_tabsize(opt_tab_size);
8219 #else
8220 TABSIZE = opt_tab_size;
8221 #endif
8223 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8224 if (term && !strcmp(term, "gnome-terminal")) {
8225 /* In the gnome-terminal-emulator, the message from
8226 * scrolling up one line when impossible followed by
8227 * scrolling down one line causes corruption of the
8228 * status line. This is fixed by calling wclear. */
8229 use_scroll_status_wclear = TRUE;
8230 use_scroll_redrawwin = FALSE;
8232 } else if (term && !strcmp(term, "xrvt-xpm")) {
8233 /* No problems with full optimizations in xrvt-(unicode)
8234 * and aterm. */
8235 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8237 } else {
8238 /* When scrolling in (u)xterm the last line in the
8239 * scrolling direction will update slowly. */
8240 use_scroll_redrawwin = TRUE;
8241 use_scroll_status_wclear = FALSE;
8245 static int
8246 get_input(int prompt_position)
8248 struct view *view;
8249 int i, key, cursor_y, cursor_x;
8251 if (prompt_position)
8252 input_mode = TRUE;
8254 while (TRUE) {
8255 bool loading = FALSE;
8257 foreach_view (view, i) {
8258 update_view(view);
8259 if (view_is_displayed(view) && view->has_scrolled &&
8260 use_scroll_redrawwin)
8261 redrawwin(view->win);
8262 view->has_scrolled = FALSE;
8263 if (view->pipe)
8264 loading = TRUE;
8267 /* Update the cursor position. */
8268 if (prompt_position) {
8269 getbegyx(status_win, cursor_y, cursor_x);
8270 cursor_x = prompt_position;
8271 } else {
8272 view = display[current_view];
8273 getbegyx(view->win, cursor_y, cursor_x);
8274 cursor_x = view->width - 1;
8275 cursor_y += view->pos.lineno - view->pos.offset;
8277 setsyx(cursor_y, cursor_x);
8279 /* Refresh, accept single keystroke of input */
8280 doupdate();
8281 nodelay(status_win, loading);
8282 key = wgetch(status_win);
8284 /* wgetch() with nodelay() enabled returns ERR when
8285 * there's no input. */
8286 if (key == ERR) {
8288 } else if (key == KEY_RESIZE) {
8289 int height, width;
8291 getmaxyx(stdscr, height, width);
8293 wresize(status_win, 1, width);
8294 mvwin(status_win, height - 1, 0);
8295 wnoutrefresh(status_win);
8296 resize_display();
8297 redraw_display(TRUE);
8299 } else {
8300 input_mode = FALSE;
8301 if (key == erasechar())
8302 key = KEY_BACKSPACE;
8303 return key;
8308 static char *
8309 prompt_input(const char *prompt, input_handler handler, void *data)
8311 enum input_status status = INPUT_OK;
8312 static char buf[SIZEOF_STR];
8313 size_t pos = 0;
8315 buf[pos] = 0;
8317 while (status == INPUT_OK || status == INPUT_SKIP) {
8318 int key;
8320 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8321 wclrtoeol(status_win);
8323 key = get_input(pos + 1);
8324 switch (key) {
8325 case KEY_RETURN:
8326 case KEY_ENTER:
8327 case '\n':
8328 status = pos ? INPUT_STOP : INPUT_CANCEL;
8329 break;
8331 case KEY_BACKSPACE:
8332 if (pos > 0)
8333 buf[--pos] = 0;
8334 else
8335 status = INPUT_CANCEL;
8336 break;
8338 case KEY_ESC:
8339 status = INPUT_CANCEL;
8340 break;
8342 default:
8343 if (pos >= sizeof(buf)) {
8344 report("Input string too long");
8345 return NULL;
8348 status = handler(data, buf, key);
8349 if (status == INPUT_OK)
8350 buf[pos++] = (char) key;
8354 /* Clear the status window */
8355 status_empty = FALSE;
8356 report_clear();
8358 if (status == INPUT_CANCEL)
8359 return NULL;
8361 buf[pos++] = 0;
8363 return buf;
8366 static enum input_status
8367 prompt_yesno_handler(void *data, char *buf, int c)
8369 if (c == 'y' || c == 'Y')
8370 return INPUT_STOP;
8371 if (c == 'n' || c == 'N')
8372 return INPUT_CANCEL;
8373 return INPUT_SKIP;
8376 static bool
8377 prompt_yesno(const char *prompt)
8379 char prompt2[SIZEOF_STR];
8381 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8382 return FALSE;
8384 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8387 static enum input_status
8388 read_prompt_handler(void *data, char *buf, int c)
8390 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8393 static char *
8394 read_prompt(const char *prompt)
8396 return prompt_input(prompt, read_prompt_handler, NULL);
8399 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8401 enum input_status status = INPUT_OK;
8402 int size = 0;
8404 while (items[size].text)
8405 size++;
8407 assert(size > 0);
8409 while (status == INPUT_OK) {
8410 const struct menu_item *item = &items[*selected];
8411 int key;
8412 int i;
8414 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8415 prompt, *selected + 1, size);
8416 if (item->hotkey)
8417 wprintw(status_win, "[%c] ", (char) item->hotkey);
8418 wprintw(status_win, "%s", item->text);
8419 wclrtoeol(status_win);
8421 key = get_input(COLS - 1);
8422 switch (key) {
8423 case KEY_RETURN:
8424 case KEY_ENTER:
8425 case '\n':
8426 status = INPUT_STOP;
8427 break;
8429 case KEY_LEFT:
8430 case KEY_UP:
8431 *selected = *selected - 1;
8432 if (*selected < 0)
8433 *selected = size - 1;
8434 break;
8436 case KEY_RIGHT:
8437 case KEY_DOWN:
8438 *selected = (*selected + 1) % size;
8439 break;
8441 case KEY_ESC:
8442 status = INPUT_CANCEL;
8443 break;
8445 default:
8446 for (i = 0; items[i].text; i++)
8447 if (items[i].hotkey == key) {
8448 *selected = i;
8449 status = INPUT_STOP;
8450 break;
8455 /* Clear the status window */
8456 status_empty = FALSE;
8457 report_clear();
8459 return status != INPUT_CANCEL;
8463 * Repository properties
8467 static void
8468 set_remote_branch(const char *name, const char *value, size_t valuelen)
8470 if (!strcmp(name, ".remote")) {
8471 string_ncopy(opt_remote, value, valuelen);
8473 } else if (*opt_remote && !strcmp(name, ".merge")) {
8474 size_t from = strlen(opt_remote);
8476 if (!prefixcmp(value, "refs/heads/"))
8477 value += STRING_SIZE("refs/heads/");
8479 if (!string_format_from(opt_remote, &from, "/%s", value))
8480 opt_remote[0] = 0;
8484 static void
8485 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
8487 const char *argv[SIZEOF_ARG] = { name, "=" };
8488 int argc = 1 + (cmd == option_set_command);
8489 enum option_code error;
8491 if (!argv_from_string(argv, &argc, value))
8492 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
8493 else
8494 error = cmd(argc, argv);
8496 if (error != OPT_OK)
8497 warn("Option 'tig.%s': %s", name, option_errors[error]);
8500 static void
8501 set_work_tree(const char *value)
8503 char cwd[SIZEOF_STR];
8505 if (!getcwd(cwd, sizeof(cwd)))
8506 die("Failed to get cwd path: %s", strerror(errno));
8507 if (chdir(cwd) < 0)
8508 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8509 if (chdir(opt_git_dir) < 0)
8510 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8511 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8512 die("Failed to get git path: %s", strerror(errno));
8513 if (chdir(value) < 0)
8514 die("Failed to chdir(%s): %s", value, strerror(errno));
8515 if (!getcwd(cwd, sizeof(cwd)))
8516 die("Failed to get cwd path: %s", strerror(errno));
8517 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8518 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8519 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8520 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8521 opt_is_inside_work_tree = TRUE;
8524 static void
8525 parse_git_color_option(enum line_type type, char *value)
8527 struct line_info *info = &line_info[type];
8528 const char *argv[SIZEOF_ARG];
8529 int argc = 0;
8530 bool first_color = TRUE;
8531 int i;
8533 if (!argv_from_string(argv, &argc, value))
8534 return;
8536 info->fg = COLOR_DEFAULT;
8537 info->bg = COLOR_DEFAULT;
8538 info->attr = 0;
8540 for (i = 0; i < argc; i++) {
8541 int attr = 0;
8543 if (set_attribute(&attr, argv[i])) {
8544 info->attr |= attr;
8546 } else if (set_color(&attr, argv[i])) {
8547 if (first_color)
8548 info->fg = attr;
8549 else
8550 info->bg = attr;
8551 first_color = FALSE;
8556 static void
8557 set_git_color_option(const char *name, char *value)
8559 static const struct enum_map color_option_map[] = {
8560 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8561 ENUM_MAP("branch.local", LINE_MAIN_REF),
8562 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8563 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8565 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8566 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8567 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8568 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8569 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8570 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8571 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8573 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8575 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8576 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8577 ENUM_MAP("status.added", LINE_STAT_STAGED),
8578 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8579 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8580 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8583 int type = LINE_NONE;
8585 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8586 parse_git_color_option(type, value);
8590 static void
8591 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8593 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
8594 opt_encoding_arg[0] = 0;
8597 static int
8598 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8600 if (!strcmp(name, "i18n.commitencoding"))
8601 set_encoding(&opt_encoding, value, FALSE);
8603 else if (!strcmp(name, "gui.encoding"))
8604 set_encoding(&opt_encoding, value, TRUE);
8606 else if (!strcmp(name, "core.editor"))
8607 string_ncopy(opt_editor, value, valuelen);
8609 else if (!strcmp(name, "core.worktree"))
8610 set_work_tree(value);
8612 else if (!strcmp(name, "core.abbrev"))
8613 parse_id(&opt_id_cols, value);
8615 else if (!prefixcmp(name, "tig.color."))
8616 set_repo_config_option(name + 10, value, option_color_command);
8618 else if (!prefixcmp(name, "tig.bind."))
8619 set_repo_config_option(name + 9, value, option_bind_command);
8621 else if (!prefixcmp(name, "tig."))
8622 set_repo_config_option(name + 4, value, option_set_command);
8624 else if (!prefixcmp(name, "color."))
8625 set_git_color_option(name + STRING_SIZE("color."), value);
8627 else if (*opt_head && !prefixcmp(name, "branch.") &&
8628 !strncmp(name + 7, opt_head, strlen(opt_head)))
8629 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8631 return OK;
8634 static int
8635 load_git_config(void)
8637 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8639 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8642 #define REPO_INFO_GIT_DIR "--git-dir"
8643 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8644 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8645 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8646 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8647 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8649 struct repo_info_state {
8650 const char **argv;
8651 char head_id[SIZEOF_REV];
8654 static int
8655 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8657 struct repo_info_state *state = data;
8658 const char *arg = *state->argv ? *state->argv++ : "";
8660 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8661 string_ncopy(opt_git_dir, name, namelen);
8663 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8664 /* This can be 3 different values depending on the
8665 * version of git being used. If git-rev-parse does not
8666 * understand --is-inside-work-tree it will simply echo
8667 * the option else either "true" or "false" is printed.
8668 * Default to true for the unknown case. */
8669 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8671 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8672 string_ncopy(opt_cdup, name, namelen);
8674 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8675 string_ncopy(opt_prefix, name, namelen);
8677 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8678 string_ncopy(state->head_id, name, namelen);
8680 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8681 if (!prefixcmp(name, "refs/heads/")) {
8682 char *offset = name + STRING_SIZE("refs/heads/");
8684 string_ncopy(opt_head, offset, strlen(offset) + 1);
8685 add_ref(state->head_id, name, opt_remote, opt_head);
8687 state->argv++;
8690 return OK;
8693 static int
8694 load_repo_info(void)
8696 const char *rev_parse_argv[] = {
8697 "git", "rev-parse", REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8698 REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE, REPO_INFO_SHOW_CDUP,
8699 REPO_INFO_SHOW_PREFIX, NULL
8701 struct repo_info_state state = { rev_parse_argv + 2 };
8703 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8708 * Main
8711 static const char usage[] =
8712 "tig " TIG_VERSION " (" __DATE__ ")\n"
8713 "\n"
8714 "Usage: tig [options] [revs] [--] [paths]\n"
8715 " or: tig log [options] [revs] [--] [paths]\n"
8716 " or: tig show [options] [revs] [--] [paths]\n"
8717 " or: tig blame [options] [rev] [--] path\n"
8718 " or: tig stash\n"
8719 " or: tig status\n"
8720 " or: tig < [git command output]\n"
8721 "\n"
8722 "Options:\n"
8723 " +<number> Select line <number> in the first view\n"
8724 " -v, --version Show version and exit\n"
8725 " -h, --help Show help message and exit";
8727 static void TIG_NORETURN
8728 quit(int sig)
8730 if (sig)
8731 signal(sig, SIG_DFL);
8733 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8734 if (cursed)
8735 endwin();
8736 exit(0);
8739 static void TIG_NORETURN
8740 die(const char *err, ...)
8742 va_list args;
8744 endwin();
8746 va_start(args, err);
8747 fputs("tig: ", stderr);
8748 vfprintf(stderr, err, args);
8749 fputs("\n", stderr);
8750 va_end(args);
8752 exit(1);
8755 static void
8756 warn(const char *msg, ...)
8758 va_list args;
8760 va_start(args, msg);
8761 fputs("tig warning: ", stderr);
8762 vfprintf(stderr, msg, args);
8763 fputs("\n", stderr);
8764 va_end(args);
8767 static int
8768 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8770 const char ***filter_args = data;
8772 return argv_append(filter_args, name) ? OK : ERR;
8775 static void
8776 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8778 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8779 const char **all_argv = NULL;
8781 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8782 !argv_append_array(&all_argv, argv) ||
8783 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8784 die("Failed to split arguments");
8785 argv_free(all_argv);
8786 free(all_argv);
8789 static bool
8790 is_rev_flag(const char *flag)
8792 static const char *rev_flags[] = { GIT_REV_FLAGS };
8793 int i;
8795 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8796 if (!strcmp(flag, rev_flags[i]))
8797 return TRUE;
8799 return FALSE;
8802 static void
8803 filter_options(const char *argv[], bool blame)
8805 const char **flags = NULL;
8807 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8808 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8810 if (flags) {
8811 int next, flags_pos;
8813 for (next = flags_pos = 0; flags && flags[next]; next++) {
8814 const char *flag = flags[next];
8816 if (is_rev_flag(flag))
8817 argv_append(&opt_rev_argv, flag);
8818 else
8819 flags[flags_pos++] = flag;
8822 flags[flags_pos] = NULL;
8824 if (blame)
8825 opt_blame_argv = flags;
8826 else
8827 opt_diff_argv = flags;
8830 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8833 static enum request
8834 parse_options(int argc, const char *argv[])
8836 enum request request;
8837 const char *subcommand;
8838 bool seen_dashdash = FALSE;
8839 const char **filter_argv = NULL;
8840 int i;
8842 opt_stdin = !isatty(STDIN_FILENO);
8843 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8845 if (argc <= 1)
8846 return request;
8848 subcommand = argv[1];
8849 if (!strcmp(subcommand, "status")) {
8850 request = REQ_VIEW_STATUS;
8852 } else if (!strcmp(subcommand, "blame")) {
8853 request = REQ_VIEW_BLAME;
8855 } else if (!strcmp(subcommand, "show")) {
8856 request = REQ_VIEW_DIFF;
8858 } else if (!strcmp(subcommand, "log")) {
8859 request = REQ_VIEW_LOG;
8861 } else if (!strcmp(subcommand, "stash")) {
8862 request = REQ_VIEW_STASH;
8864 } else {
8865 subcommand = NULL;
8868 for (i = 1 + !!subcommand; i < argc; i++) {
8869 const char *opt = argv[i];
8871 // stop parsing our options after -- and let rev-parse handle the rest
8872 if (!seen_dashdash) {
8873 if (!strcmp(opt, "--")) {
8874 seen_dashdash = TRUE;
8875 continue;
8877 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8878 printf("tig version %s\n", TIG_VERSION);
8879 quit(0);
8881 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8882 printf("%s\n", usage);
8883 quit(0);
8885 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8886 opt_lineno = atoi(opt + 1);
8887 continue;
8892 if (!argv_append(&filter_argv, opt))
8893 die("command too long");
8896 if (filter_argv)
8897 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8899 /* Finish validating and setting up blame options */
8900 if (request == REQ_VIEW_BLAME) {
8901 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8902 die("invalid number of options to blame\n\n%s", usage);
8904 if (opt_rev_argv) {
8905 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8908 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8910 } else if (request == REQ_VIEW_PAGER) {
8911 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8912 if (!strcmp("--stdin", opt_rev_argv[i])) {
8913 request = REQ_VIEW_MAIN;
8914 break;
8919 return request;
8922 static enum request
8923 run_prompt_command(struct view *view, char *cmd) {
8924 enum request request;
8926 if (cmd && string_isnumber(cmd)) {
8927 int lineno = view->pos.lineno + 1;
8929 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8930 select_view_line(view, lineno - 1);
8931 report_clear();
8932 } else {
8933 report("Unable to parse '%s' as a line number", cmd);
8935 } else if (cmd && iscommit(cmd)) {
8936 string_ncopy(opt_search, cmd, strlen(cmd));
8938 request = view_request(view, REQ_JUMP_COMMIT);
8939 if (request == REQ_JUMP_COMMIT) {
8940 report("Jumping to commits is not supported by the '%s' view", view->name);
8943 } else if (cmd && strlen(cmd) == 1) {
8944 request = get_keybinding(&view->ops->keymap, cmd[0]);
8945 return request;
8947 } else if (cmd && cmd[0] == '!') {
8948 struct view *next = VIEW(REQ_VIEW_PAGER);
8949 const char *argv[SIZEOF_ARG];
8950 int argc = 0;
8952 cmd++;
8953 /* When running random commands, initially show the
8954 * command in the title. However, it maybe later be
8955 * overwritten if a commit line is selected. */
8956 string_ncopy(next->ref, cmd, strlen(cmd));
8958 if (!argv_from_string(argv, &argc, cmd)) {
8959 report("Too many arguments");
8960 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
8961 report("Argument formatting failed");
8962 } else {
8963 next->dir = NULL;
8964 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8967 } else if (cmd) {
8968 request = get_request(cmd);
8969 if (request != REQ_UNKNOWN)
8970 return request;
8972 char *args = strchr(cmd, ' ');
8973 if (args) {
8974 *args++ = 0;
8975 if (set_option(cmd, args) == OPT_OK) {
8976 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
8977 if (!strcmp(cmd, "color"))
8978 init_colors();
8981 return request;
8983 return REQ_NONE;
8987 main(int argc, const char *argv[])
8989 const char *codeset = ENCODING_UTF8;
8990 enum request request = parse_options(argc, argv);
8991 struct view *view;
8992 int i;
8994 signal(SIGINT, quit);
8995 signal(SIGQUIT, quit);
8996 signal(SIGPIPE, SIG_IGN);
8998 if (setlocale(LC_ALL, "")) {
8999 codeset = nl_langinfo(CODESET);
9002 foreach_view(view, i) {
9003 add_keymap(&view->ops->keymap);
9006 if (load_repo_info() == ERR)
9007 die("Failed to load repo info.");
9009 if (load_options() == ERR)
9010 die("Failed to load user config.");
9012 if (load_git_config() == ERR)
9013 die("Failed to load repo config.");
9015 /* Require a git repository unless when running in pager mode. */
9016 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9017 die("Not a git repository");
9019 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9020 char translit[SIZEOF_STR];
9022 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9023 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9024 else
9025 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9026 if (opt_iconv_out == ICONV_NONE)
9027 die("Failed to initialize character set conversion");
9030 if (load_refs(FALSE) == ERR)
9031 die("Failed to load refs.");
9033 init_display();
9035 while (view_driver(display[current_view], request)) {
9036 int key = get_input(0);
9038 if (key == KEY_ESC)
9039 key = get_input(0) + 0x80;
9041 view = display[current_view];
9042 request = get_keybinding(&view->ops->keymap, key);
9044 /* Some low-level request handling. This keeps access to
9045 * status_win restricted. */
9046 switch (request) {
9047 case REQ_NONE:
9048 report("Unknown key, press %s for help",
9049 get_view_key(view, REQ_VIEW_HELP));
9050 break;
9051 case REQ_PROMPT:
9053 char *cmd = read_prompt(":");
9054 request = run_prompt_command(view, cmd);
9055 break;
9057 case REQ_SEARCH:
9058 case REQ_SEARCH_BACK:
9060 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9061 char *search = read_prompt(prompt);
9063 if (search)
9064 string_ncopy(opt_search, search, strlen(search));
9065 else if (*opt_search)
9066 request = request == REQ_SEARCH ?
9067 REQ_FIND_NEXT :
9068 REQ_FIND_PREV;
9069 else
9070 request = REQ_NONE;
9071 break;
9073 default:
9074 break;
9078 quit(0);
9080 return 0;
9083 /* vim: set ts=8 sw=8 noexpandtab: */