Load HEAD ID and symbolic name as part of the repo info
[tig.git] / tig.c
blob66046ca51cb3ca01edc05eb1d111ebc473f9a63b
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"), \
435 REQ_GROUP("Misc") \
436 REQ_(PROMPT, "Bring up the prompt"), \
437 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
438 REQ_(SHOW_VERSION, "Show version information"), \
439 REQ_(STOP_LOADING, "Stop all loading views"), \
440 REQ_(EDIT, "Open in editor"), \
441 REQ_(NONE, "Do nothing")
444 /* User action requests. */
445 enum request {
446 #define REQ_GROUP(help)
447 #define REQ_(req, help) REQ_##req
449 /* Offset all requests to avoid conflicts with ncurses getch values. */
450 REQ_UNKNOWN = KEY_MAX + 1,
451 REQ_OFFSET,
452 REQ_INFO,
454 /* Internal requests. */
455 REQ_JUMP_COMMIT,
457 #undef REQ_GROUP
458 #undef REQ_
461 struct request_info {
462 enum request request;
463 const char *name;
464 int namelen;
465 const char *help;
468 static const struct request_info req_info[] = {
469 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
470 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
471 REQ_INFO
472 #undef REQ_GROUP
473 #undef REQ_
476 static enum request
477 get_request(const char *name)
479 int namelen = strlen(name);
480 int i;
482 for (i = 0; i < ARRAY_SIZE(req_info); i++)
483 if (enum_equals(req_info[i], name, namelen))
484 return req_info[i].request;
486 return REQ_UNKNOWN;
491 * Options
494 /* Option and state variables. */
495 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
496 static enum date opt_date = DATE_DEFAULT;
497 static enum author opt_author = AUTHOR_FULL;
498 static enum filename opt_filename = FILENAME_AUTO;
499 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
500 static bool opt_rev_graph = TRUE;
501 static bool opt_line_number = FALSE;
502 static bool opt_show_refs = TRUE;
503 static bool opt_show_changes = TRUE;
504 static bool opt_untracked_dirs_content = TRUE;
505 static bool opt_read_git_colors = TRUE;
506 static bool opt_wrap_lines = FALSE;
507 static bool opt_ignore_case = FALSE;
508 static bool opt_stdin = FALSE;
509 static bool opt_focus_child = TRUE;
510 static int opt_diff_context = 3;
511 static char opt_diff_context_arg[9] = "";
512 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
513 static char opt_ignore_space_arg[22] = "";
514 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
515 static char opt_commit_order_arg[22] = "";
516 static bool opt_notes = TRUE;
517 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
518 static int opt_num_interval = 5;
519 static double opt_hscroll = 0.50;
520 static double opt_scale_split_view = 2.0 / 3.0;
521 static double opt_scale_vsplit_view = 0.5;
522 static bool opt_vsplit = FALSE;
523 static int opt_tab_size = 8;
524 static int opt_author_width = AUTHOR_WIDTH;
525 static int opt_filename_width = FILENAME_WIDTH;
526 static char opt_path[SIZEOF_STR] = "";
527 static char opt_file[SIZEOF_STR] = "";
528 static char opt_ref[SIZEOF_REF] = "";
529 static unsigned long opt_goto_line = 0;
530 static char opt_head[SIZEOF_REF] = "";
531 static char opt_remote[SIZEOF_REF] = "";
532 static struct encoding *opt_encoding = NULL;
533 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
534 static iconv_t opt_iconv_out = ICONV_NONE;
535 static char opt_search[SIZEOF_STR] = "";
536 static char opt_cdup[SIZEOF_STR] = "";
537 static char opt_prefix[SIZEOF_STR] = "";
538 static char opt_git_dir[SIZEOF_STR] = "";
539 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
540 static char opt_editor[SIZEOF_STR] = "";
541 static bool opt_editor_lineno = TRUE;
542 static FILE *opt_tty = NULL;
543 static const char **opt_diff_argv = NULL;
544 static const char **opt_rev_argv = NULL;
545 static const char **opt_file_argv = NULL;
546 static const char **opt_blame_argv = NULL;
547 static int opt_lineno = 0;
548 static bool opt_show_id = FALSE;
549 static int opt_id_cols = ID_WIDTH;
550 static bool opt_file_filter = TRUE;
551 static bool opt_show_title_overflow = FALSE;
552 static int opt_title_overflow = 50;
553 static char opt_env_lines[64] = "";
554 static char opt_env_columns[64] = "";
555 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
557 #define is_initial_commit() (!get_ref_head())
558 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
559 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
561 static inline void
562 update_diff_context_arg(int diff_context)
564 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
565 string_ncopy(opt_diff_context_arg, "-U3", 3);
568 static inline void
569 update_ignore_space_arg()
571 if (opt_ignore_space == IGNORE_SPACE_ALL) {
572 string_copy(opt_ignore_space_arg, "--ignore-all-space");
573 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
574 string_copy(opt_ignore_space_arg, "--ignore-space-change");
575 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
576 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
577 } else {
578 string_copy(opt_ignore_space_arg, "");
582 static inline void
583 update_commit_order_arg()
585 if (opt_commit_order == COMMIT_ORDER_TOPO) {
586 string_copy(opt_commit_order_arg, "--topo-order");
587 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
588 string_copy(opt_commit_order_arg, "--date-order");
589 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
590 string_copy(opt_commit_order_arg, "--reverse");
591 } else {
592 string_copy(opt_commit_order_arg, "");
596 static inline void
597 update_notes_arg()
599 if (opt_notes) {
600 string_copy(opt_notes_arg, "--show-notes");
601 } else {
602 /* Notes are disabled by default when passing --pretty args. */
603 string_copy(opt_notes_arg, "");
608 * Line-oriented content detection.
611 #define LINE_INFO \
612 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
613 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
614 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
615 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
616 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
617 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
618 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
619 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
620 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
621 LINE(DIFF_DELETED_FILE_MODE, \
622 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
623 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
624 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
625 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
626 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
627 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
628 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
629 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
630 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
631 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
632 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
633 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
634 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
635 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
636 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
637 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
638 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
639 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
640 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
641 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
642 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
643 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
644 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
645 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
646 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
647 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
648 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
649 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
650 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
651 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
652 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
653 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
654 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
655 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
656 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
657 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
658 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
659 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
660 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
661 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
662 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
663 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
664 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
665 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
666 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
667 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
668 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
669 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
670 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
671 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
672 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
673 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
674 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
675 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
676 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
677 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
678 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
679 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
680 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
681 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
682 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
683 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
684 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
685 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
686 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
687 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
688 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
689 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
690 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
692 enum line_type {
693 #define LINE(type, line, fg, bg, attr) \
694 LINE_##type
695 LINE_INFO,
696 LINE_NONE
697 #undef LINE
700 struct line_info {
701 const char *name; /* Option name. */
702 int namelen; /* Size of option name. */
703 const char *line; /* The start of line to match. */
704 int linelen; /* Size of string to match. */
705 int fg, bg, attr; /* Color and text attributes for the lines. */
706 int color_pair;
709 static struct line_info line_info[] = {
710 #define LINE(type, line, fg, bg, attr) \
711 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
712 LINE_INFO
713 #undef LINE
716 static struct line_info **color_pair;
717 static size_t color_pairs;
719 static struct line_info *custom_color;
720 static size_t custom_colors;
722 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
723 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
725 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
726 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
728 /* Color IDs must be 1 or higher. [GH #15] */
729 #define COLOR_ID(line_type) ((line_type) + 1)
731 static enum line_type
732 get_line_type(const char *line)
734 int linelen = strlen(line);
735 enum line_type type;
737 for (type = 0; type < custom_colors; type++)
738 /* Case insensitive search matches Signed-off-by lines better. */
739 if (linelen >= custom_color[type].linelen &&
740 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
741 return TO_CUSTOM_COLOR_TYPE(type);
743 for (type = 0; type < ARRAY_SIZE(line_info); type++)
744 /* Case insensitive search matches Signed-off-by lines better. */
745 if (linelen >= line_info[type].linelen &&
746 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
747 return type;
749 return LINE_DEFAULT;
752 static enum line_type
753 get_line_type_from_ref(const struct ref *ref)
755 if (ref->head)
756 return LINE_MAIN_HEAD;
757 else if (ref->ltag)
758 return LINE_MAIN_LOCAL_TAG;
759 else if (ref->tag)
760 return LINE_MAIN_TAG;
761 else if (ref->tracked)
762 return LINE_MAIN_TRACKED;
763 else if (ref->remote)
764 return LINE_MAIN_REMOTE;
765 else if (ref->replace)
766 return LINE_MAIN_REPLACE;
768 return LINE_MAIN_REF;
771 static inline struct line_info *
772 get_line(enum line_type type)
774 if (type > LINE_NONE) {
775 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
776 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
777 } else {
778 assert(type < ARRAY_SIZE(line_info));
779 return &line_info[type];
783 static inline int
784 get_line_color(enum line_type type)
786 return COLOR_ID(get_line(type)->color_pair);
789 static inline int
790 get_line_attr(enum line_type type)
792 struct line_info *info = get_line(type);
794 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
797 static struct line_info *
798 get_line_info(const char *name)
800 size_t namelen = strlen(name);
801 enum line_type type;
803 for (type = 0; type < ARRAY_SIZE(line_info); type++)
804 if (enum_equals(line_info[type], name, namelen))
805 return &line_info[type];
807 return NULL;
810 static struct line_info *
811 add_custom_color(const char *quoted_line)
813 struct line_info *info;
814 char *line;
815 size_t linelen;
817 if (!realloc_custom_color(&custom_color, custom_colors, 1))
818 die("Failed to alloc custom line info");
820 linelen = strlen(quoted_line) - 1;
821 line = malloc(linelen);
822 if (!line)
823 return NULL;
825 strncpy(line, quoted_line + 1, linelen);
826 line[linelen - 1] = 0;
828 info = &custom_color[custom_colors++];
829 info->name = info->line = line;
830 info->namelen = info->linelen = strlen(line);
832 return info;
835 static void
836 init_line_info_color_pair(struct line_info *info, enum line_type type,
837 int default_bg, int default_fg)
839 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
840 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
841 int i;
843 for (i = 0; i < color_pairs; i++) {
844 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
845 info->color_pair = i;
846 return;
850 if (!realloc_color_pair(&color_pair, color_pairs, 1))
851 die("Failed to alloc color pair");
853 color_pair[color_pairs] = info;
854 info->color_pair = color_pairs++;
855 init_pair(COLOR_ID(info->color_pair), fg, bg);
858 static void
859 init_colors(void)
861 int default_bg = line_info[LINE_DEFAULT].bg;
862 int default_fg = line_info[LINE_DEFAULT].fg;
863 enum line_type type;
865 start_color();
867 if (assume_default_colors(default_fg, default_bg) == ERR) {
868 default_bg = COLOR_BLACK;
869 default_fg = COLOR_WHITE;
872 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
873 struct line_info *info = &line_info[type];
875 init_line_info_color_pair(info, type, default_bg, default_fg);
878 for (type = 0; type < custom_colors; type++) {
879 struct line_info *info = &custom_color[type];
881 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
882 default_bg, default_fg);
886 struct line {
887 enum line_type type;
888 unsigned int lineno:24;
890 /* State flags */
891 unsigned int selected:1;
892 unsigned int dirty:1;
893 unsigned int cleareol:1;
894 unsigned int wrapped:1;
896 unsigned int user_flags:6;
897 void *data; /* User data */
902 * Keys
905 struct keybinding {
906 int alias;
907 enum request request;
910 static struct keybinding default_keybindings[] = {
911 /* View switching */
912 { 'm', REQ_VIEW_MAIN },
913 { 'd', REQ_VIEW_DIFF },
914 { 'l', REQ_VIEW_LOG },
915 { 't', REQ_VIEW_TREE },
916 { 'f', REQ_VIEW_BLOB },
917 { 'B', REQ_VIEW_BLAME },
918 { 'H', REQ_VIEW_BRANCH },
919 { 'p', REQ_VIEW_PAGER },
920 { 'h', REQ_VIEW_HELP },
921 { 'S', REQ_VIEW_STATUS },
922 { 'c', REQ_VIEW_STAGE },
923 { 'y', REQ_VIEW_STASH },
925 /* View manipulation */
926 { 'q', REQ_VIEW_CLOSE },
927 { KEY_TAB, REQ_VIEW_NEXT },
928 { KEY_RETURN, REQ_ENTER },
929 { KEY_UP, REQ_PREVIOUS },
930 { KEY_CTL('P'), REQ_PREVIOUS },
931 { KEY_DOWN, REQ_NEXT },
932 { KEY_CTL('N'), REQ_NEXT },
933 { 'R', REQ_REFRESH },
934 { KEY_F(5), REQ_REFRESH },
935 { 'O', REQ_MAXIMIZE },
936 { ',', REQ_PARENT },
938 /* View specific */
939 { 'u', REQ_STATUS_UPDATE },
940 { '!', REQ_STATUS_REVERT },
941 { 'M', REQ_STATUS_MERGE },
942 { '1', REQ_STAGE_UPDATE_LINE },
943 { '@', REQ_STAGE_NEXT },
944 { '[', REQ_DIFF_CONTEXT_DOWN },
945 { ']', REQ_DIFF_CONTEXT_UP },
947 /* Cursor navigation */
948 { 'k', REQ_MOVE_UP },
949 { 'j', REQ_MOVE_DOWN },
950 { KEY_HOME, REQ_MOVE_FIRST_LINE },
951 { KEY_END, REQ_MOVE_LAST_LINE },
952 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
953 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
954 { ' ', REQ_MOVE_PAGE_DOWN },
955 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
956 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
957 { 'b', REQ_MOVE_PAGE_UP },
958 { '-', REQ_MOVE_PAGE_UP },
960 /* Scrolling */
961 { '|', REQ_SCROLL_FIRST_COL },
962 { KEY_LEFT, REQ_SCROLL_LEFT },
963 { KEY_RIGHT, REQ_SCROLL_RIGHT },
964 { KEY_IC, REQ_SCROLL_LINE_UP },
965 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
966 { KEY_DC, REQ_SCROLL_LINE_DOWN },
967 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
968 { 'w', REQ_SCROLL_PAGE_UP },
969 { 's', REQ_SCROLL_PAGE_DOWN },
971 /* Searching */
972 { '/', REQ_SEARCH },
973 { '?', REQ_SEARCH_BACK },
974 { 'n', REQ_FIND_NEXT },
975 { 'N', REQ_FIND_PREV },
977 /* Misc */
978 { 'Q', REQ_QUIT },
979 { 'z', REQ_STOP_LOADING },
980 { 'v', REQ_SHOW_VERSION },
981 { 'r', REQ_SCREEN_REDRAW },
982 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
983 { 'o', REQ_OPTIONS },
984 { '.', REQ_TOGGLE_LINENO },
985 { 'D', REQ_TOGGLE_DATE },
986 { 'A', REQ_TOGGLE_AUTHOR },
987 { 'g', REQ_TOGGLE_REV_GRAPH },
988 { '~', REQ_TOGGLE_GRAPHIC },
989 { '#', REQ_TOGGLE_FILENAME },
990 { 'F', REQ_TOGGLE_REFS },
991 { 'I', REQ_TOGGLE_SORT_ORDER },
992 { 'i', REQ_TOGGLE_SORT_FIELD },
993 { 'W', REQ_TOGGLE_IGNORE_SPACE },
994 { 'X', REQ_TOGGLE_ID },
995 { '%', REQ_TOGGLE_FILES },
996 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
997 { ':', REQ_PROMPT },
998 { 'e', REQ_EDIT },
1001 struct keymap {
1002 const char *name;
1003 struct keymap *next;
1004 struct keybinding *data;
1005 size_t size;
1006 bool hidden;
1009 static struct keymap generic_keymap = { "generic" };
1010 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
1012 static struct keymap *keymaps = &generic_keymap;
1014 static void
1015 add_keymap(struct keymap *keymap)
1017 keymap->next = keymaps;
1018 keymaps = keymap;
1021 static struct keymap *
1022 get_keymap(const char *name)
1024 struct keymap *keymap = keymaps;
1026 while (keymap) {
1027 if (!strcasecmp(keymap->name, name))
1028 return keymap;
1029 keymap = keymap->next;
1032 return NULL;
1036 static void
1037 add_keybinding(struct keymap *table, enum request request, int key)
1039 size_t i;
1041 for (i = 0; i < table->size; i++) {
1042 if (table->data[i].alias == key) {
1043 table->data[i].request = request;
1044 return;
1048 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1049 if (!table->data)
1050 die("Failed to allocate keybinding");
1051 table->data[table->size].alias = key;
1052 table->data[table->size++].request = request;
1054 if (request == REQ_NONE && is_generic_keymap(table)) {
1055 int i;
1057 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1058 if (default_keybindings[i].alias == key)
1059 default_keybindings[i].request = REQ_NONE;
1063 /* Looks for a key binding first in the given map, then in the generic map, and
1064 * lastly in the default keybindings. */
1065 static enum request
1066 get_keybinding(struct keymap *keymap, int key)
1068 size_t i;
1070 for (i = 0; i < keymap->size; i++)
1071 if (keymap->data[i].alias == key)
1072 return keymap->data[i].request;
1074 for (i = 0; i < generic_keymap.size; i++)
1075 if (generic_keymap.data[i].alias == key)
1076 return generic_keymap.data[i].request;
1078 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1079 if (default_keybindings[i].alias == key)
1080 return default_keybindings[i].request;
1082 return (enum request) key;
1086 struct key {
1087 const char *name;
1088 int value;
1091 static const struct key key_table[] = {
1092 { "Enter", KEY_RETURN },
1093 { "Space", ' ' },
1094 { "Backspace", KEY_BACKSPACE },
1095 { "Tab", KEY_TAB },
1096 { "Escape", KEY_ESC },
1097 { "Left", KEY_LEFT },
1098 { "Right", KEY_RIGHT },
1099 { "Up", KEY_UP },
1100 { "Down", KEY_DOWN },
1101 { "Insert", KEY_IC },
1102 { "Delete", KEY_DC },
1103 { "Hash", '#' },
1104 { "Home", KEY_HOME },
1105 { "End", KEY_END },
1106 { "PageUp", KEY_PPAGE },
1107 { "PageDown", KEY_NPAGE },
1108 { "F1", KEY_F(1) },
1109 { "F2", KEY_F(2) },
1110 { "F3", KEY_F(3) },
1111 { "F4", KEY_F(4) },
1112 { "F5", KEY_F(5) },
1113 { "F6", KEY_F(6) },
1114 { "F7", KEY_F(7) },
1115 { "F8", KEY_F(8) },
1116 { "F9", KEY_F(9) },
1117 { "F10", KEY_F(10) },
1118 { "F11", KEY_F(11) },
1119 { "F12", KEY_F(12) },
1122 static int
1123 get_key_value(const char *name)
1125 int i;
1127 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1128 if (!strcasecmp(key_table[i].name, name))
1129 return key_table[i].value;
1131 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1132 return (int)name[2] + 0x80;
1133 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1134 return (int)name[1] & 0x1f;
1135 if (strlen(name) == 1 && isprint(*name))
1136 return (int) *name;
1137 return ERR;
1140 static const char *
1141 get_key_name(int key_value)
1143 static char key_char[] = "'X'\0";
1144 const char *seq = NULL;
1145 int key;
1147 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1148 if (key_table[key].value == key_value)
1149 seq = key_table[key].name;
1151 if (seq == NULL && key_value < 0x7f) {
1152 char *s = key_char + 1;
1154 if (key_value >= 0x20) {
1155 *s++ = key_value;
1156 } else {
1157 *s++ = '^';
1158 *s++ = 0x40 | (key_value & 0x1f);
1160 *s++ = '\'';
1161 *s++ = '\0';
1162 seq = key_char;
1165 return seq ? seq : "(no key)";
1168 static bool
1169 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1171 const char *sep = *pos > 0 ? ", " : "";
1172 const char *keyname = get_key_name(keybinding->alias);
1174 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1177 static bool
1178 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1179 struct keymap *keymap, bool all)
1181 int i;
1183 for (i = 0; i < keymap->size; i++) {
1184 if (keymap->data[i].request == request) {
1185 if (!append_key(buf, pos, &keymap->data[i]))
1186 return FALSE;
1187 if (!all)
1188 break;
1192 return TRUE;
1195 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1197 static const char *
1198 get_keys(struct keymap *keymap, enum request request, bool all)
1200 static char buf[BUFSIZ];
1201 size_t pos = 0;
1202 int i;
1204 buf[pos] = 0;
1206 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1207 return "Too many keybindings!";
1208 if (pos > 0 && !all)
1209 return buf;
1211 if (!is_generic_keymap(keymap)) {
1212 /* Only the generic keymap includes the default keybindings when
1213 * listing all keys. */
1214 if (all)
1215 return buf;
1217 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1218 return "Too many keybindings!";
1219 if (pos)
1220 return buf;
1223 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1224 if (default_keybindings[i].request == request) {
1225 if (!append_key(buf, &pos, &default_keybindings[i]))
1226 return "Too many keybindings!";
1227 if (!all)
1228 return buf;
1232 return buf;
1235 enum run_request_flag {
1236 RUN_REQUEST_DEFAULT = 0,
1237 RUN_REQUEST_FORCE = 1,
1238 RUN_REQUEST_SILENT = 2,
1239 RUN_REQUEST_CONFIRM = 4,
1240 RUN_REQUEST_EXIT = 8,
1241 RUN_REQUEST_INTERNAL = 16,
1244 struct run_request {
1245 struct keymap *keymap;
1246 int key;
1247 const char **argv;
1248 bool silent;
1249 bool confirm;
1250 bool exit;
1251 bool internal;
1254 static struct run_request *run_request;
1255 static size_t run_requests;
1257 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1259 static bool
1260 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1262 bool force = flags & RUN_REQUEST_FORCE;
1263 struct run_request *req;
1265 if (!force && get_keybinding(keymap, key) != key)
1266 return TRUE;
1268 if (!realloc_run_requests(&run_request, run_requests, 1))
1269 return FALSE;
1271 if (!argv_copy(&run_request[run_requests].argv, argv))
1272 return FALSE;
1274 req = &run_request[run_requests++];
1275 req->silent = flags & RUN_REQUEST_SILENT;
1276 req->confirm = flags & RUN_REQUEST_CONFIRM;
1277 req->exit = flags & RUN_REQUEST_EXIT;
1278 req->internal = flags & RUN_REQUEST_INTERNAL;
1279 req->keymap = keymap;
1280 req->key = key;
1282 add_keybinding(keymap, REQ_NONE + run_requests, key);
1283 return TRUE;
1286 static struct run_request *
1287 get_run_request(enum request request)
1289 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1290 return NULL;
1291 return &run_request[request - REQ_NONE - 1];
1294 static void
1295 add_builtin_run_requests(void)
1297 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1298 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1299 const char *commit[] = { "git", "commit", NULL };
1300 const char *gc[] = { "git", "gc", NULL };
1301 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1303 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1304 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1305 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1306 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1307 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1311 * User config file handling.
1314 #define OPT_ERR_INFO \
1315 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1316 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1317 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1318 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1319 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1320 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1321 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1322 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1323 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1324 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1325 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1326 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1327 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1328 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1329 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1330 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1331 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1332 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"), \
1333 OPT_ERR_(HOME_UNRESOLVABLE, "HOME environment variable could not be resolved"),
1335 enum option_code {
1336 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1337 OPT_ERR_INFO
1338 #undef OPT_ERR_
1339 OPT_OK
1342 static const char *option_errors[] = {
1343 #define OPT_ERR_(name, msg) msg
1344 OPT_ERR_INFO
1345 #undef OPT_ERR_
1348 static const struct enum_map color_map[] = {
1349 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1350 COLOR_MAP(DEFAULT),
1351 COLOR_MAP(BLACK),
1352 COLOR_MAP(BLUE),
1353 COLOR_MAP(CYAN),
1354 COLOR_MAP(GREEN),
1355 COLOR_MAP(MAGENTA),
1356 COLOR_MAP(RED),
1357 COLOR_MAP(WHITE),
1358 COLOR_MAP(YELLOW),
1361 static const struct enum_map attr_map[] = {
1362 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1363 ATTR_MAP(NORMAL),
1364 ATTR_MAP(BLINK),
1365 ATTR_MAP(BOLD),
1366 ATTR_MAP(DIM),
1367 ATTR_MAP(REVERSE),
1368 ATTR_MAP(STANDOUT),
1369 ATTR_MAP(UNDERLINE),
1372 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1374 static enum option_code
1375 parse_step(double *opt, const char *arg)
1377 *opt = atoi(arg);
1378 if (!strchr(arg, '%'))
1379 return OPT_OK;
1381 /* "Shift down" so 100% and 1 does not conflict. */
1382 *opt = (*opt - 1) / 100;
1383 if (*opt >= 1.0) {
1384 *opt = 0.99;
1385 return OPT_ERR_INVALID_STEP_VALUE;
1387 if (*opt < 0.0) {
1388 *opt = 1;
1389 return OPT_ERR_INVALID_STEP_VALUE;
1391 return OPT_OK;
1394 static enum option_code
1395 parse_int(int *opt, const char *arg, int min, int max)
1397 int value = atoi(arg);
1399 if (min <= value && value <= max) {
1400 *opt = value;
1401 return OPT_OK;
1404 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1407 #define parse_id(opt, arg) \
1408 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1410 static bool
1411 set_color(int *color, const char *name)
1413 if (map_enum(color, color_map, name))
1414 return TRUE;
1415 if (!prefixcmp(name, "color"))
1416 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1417 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1418 return parse_int(color, name, 0, 255) == OPT_OK;
1421 /* Wants: object fgcolor bgcolor [attribute] */
1422 static enum option_code
1423 option_color_command(int argc, const char *argv[])
1425 struct line_info *info;
1427 if (argc < 3)
1428 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1430 if (*argv[0] == '"' || *argv[0] == '\'') {
1431 info = add_custom_color(argv[0]);
1432 } else {
1433 info = get_line_info(argv[0]);
1435 if (!info) {
1436 static const struct enum_map obsolete[] = {
1437 ENUM_MAP("main-delim", LINE_DELIMITER),
1438 ENUM_MAP("main-date", LINE_DATE),
1439 ENUM_MAP("main-author", LINE_AUTHOR),
1440 ENUM_MAP("blame-id", LINE_ID),
1442 int index;
1444 if (!map_enum(&index, obsolete, argv[0]))
1445 return OPT_ERR_UNKNOWN_COLOR_NAME;
1446 info = &line_info[index];
1449 if (!set_color(&info->fg, argv[1]) ||
1450 !set_color(&info->bg, argv[2]))
1451 return OPT_ERR_UNKNOWN_COLOR;
1453 info->attr = 0;
1454 while (argc-- > 3) {
1455 int attr;
1457 if (!set_attribute(&attr, argv[argc]))
1458 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1459 info->attr |= attr;
1462 return OPT_OK;
1465 static enum option_code
1466 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1468 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1469 ? TRUE : FALSE;
1470 if (matched)
1471 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1472 return OPT_OK;
1475 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1477 static enum option_code
1478 parse_enum_do(unsigned int *opt, const char *arg,
1479 const struct enum_map *map, size_t map_size)
1481 bool is_true;
1483 assert(map_size > 1);
1485 if (map_enum_do(map, map_size, (int *) opt, arg))
1486 return OPT_OK;
1488 parse_bool(&is_true, arg);
1489 *opt = is_true ? map[1].value : map[0].value;
1490 return OPT_OK;
1493 #define parse_enum(opt, arg, map) \
1494 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1496 static enum option_code
1497 parse_string(char *opt, const char *arg, size_t optsize)
1499 int arglen = strlen(arg);
1501 switch (arg[0]) {
1502 case '\"':
1503 case '\'':
1504 if (arglen == 1 || arg[arglen - 1] != arg[0])
1505 return OPT_ERR_UNMATCHED_QUOTATION;
1506 arg += 1; arglen -= 2;
1507 default:
1508 string_ncopy_do(opt, optsize, arg, arglen);
1509 return OPT_OK;
1513 static enum option_code
1514 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1516 char buf[SIZEOF_STR];
1517 enum option_code code = parse_string(buf, arg, sizeof(buf));
1519 if (code == OPT_OK) {
1520 struct encoding *encoding = *encoding_ref;
1522 if (encoding && !priority)
1523 return code;
1524 encoding = encoding_open(buf);
1525 if (encoding)
1526 *encoding_ref = encoding;
1529 return code;
1532 static enum option_code
1533 parse_args(const char ***args, const char *argv[])
1535 if (!argv_copy(args, argv))
1536 return OPT_ERR_OUT_OF_MEMORY;
1537 return OPT_OK;
1540 /* Wants: name = value */
1541 static enum option_code
1542 option_set_command(int argc, const char *argv[])
1544 if (argc < 3)
1545 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1547 if (strcmp(argv[1], "="))
1548 return OPT_ERR_NO_VALUE_ASSIGNED;
1550 if (!strcmp(argv[0], "blame-options"))
1551 return parse_args(&opt_blame_argv, argv + 2);
1553 if (!strcmp(argv[0], "diff-options"))
1554 return parse_args(&opt_diff_argv, argv + 2);
1556 if (argc != 3)
1557 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1559 if (!strcmp(argv[0], "show-author"))
1560 return parse_enum(&opt_author, argv[2], author_map);
1562 if (!strcmp(argv[0], "show-date"))
1563 return parse_enum(&opt_date, argv[2], date_map);
1565 if (!strcmp(argv[0], "show-rev-graph"))
1566 return parse_bool(&opt_rev_graph, argv[2]);
1568 if (!strcmp(argv[0], "show-refs"))
1569 return parse_bool(&opt_show_refs, argv[2]);
1571 if (!strcmp(argv[0], "show-changes"))
1572 return parse_bool(&opt_show_changes, argv[2]);
1574 if (!strcmp(argv[0], "show-notes")) {
1575 bool matched = FALSE;
1576 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1578 if (res == OPT_OK && matched) {
1579 update_notes_arg();
1580 return res;
1583 opt_notes = TRUE;
1584 strcpy(opt_notes_arg, "--show-notes=");
1585 res = parse_string(opt_notes_arg + 8, argv[2],
1586 sizeof(opt_notes_arg) - 8);
1587 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1588 opt_notes_arg[7] = '\0';
1589 return res;
1592 if (!strcmp(argv[0], "show-line-numbers"))
1593 return parse_bool(&opt_line_number, argv[2]);
1595 if (!strcmp(argv[0], "line-graphics"))
1596 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1598 if (!strcmp(argv[0], "line-number-interval"))
1599 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1601 if (!strcmp(argv[0], "author-width"))
1602 return parse_int(&opt_author_width, argv[2], 0, 1024);
1604 if (!strcmp(argv[0], "filename-width"))
1605 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1607 if (!strcmp(argv[0], "show-filename"))
1608 return parse_enum(&opt_filename, argv[2], filename_map);
1610 if (!strcmp(argv[0], "show-file-size"))
1611 return parse_enum(&opt_file_size, argv[2], file_size_map);
1613 if (!strcmp(argv[0], "horizontal-scroll"))
1614 return parse_step(&opt_hscroll, argv[2]);
1616 if (!strcmp(argv[0], "split-view-height"))
1617 return parse_step(&opt_scale_split_view, argv[2]);
1619 if (!strcmp(argv[0], "vertical-split"))
1620 return parse_bool(&opt_vsplit, argv[2]);
1622 if (!strcmp(argv[0], "tab-size"))
1623 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1625 if (!strcmp(argv[0], "diff-context")) {
1626 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1628 if (code == OPT_OK)
1629 update_diff_context_arg(opt_diff_context);
1630 return code;
1633 if (!strcmp(argv[0], "ignore-space")) {
1634 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1636 if (code == OPT_OK)
1637 update_ignore_space_arg();
1638 return code;
1641 if (!strcmp(argv[0], "commit-order")) {
1642 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1644 if (code == OPT_OK)
1645 update_commit_order_arg();
1646 return code;
1649 if (!strcmp(argv[0], "status-untracked-dirs"))
1650 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1652 if (!strcmp(argv[0], "read-git-colors"))
1653 return parse_bool(&opt_read_git_colors, argv[2]);
1655 if (!strcmp(argv[0], "ignore-case"))
1656 return parse_bool(&opt_ignore_case, argv[2]);
1658 if (!strcmp(argv[0], "focus-child"))
1659 return parse_bool(&opt_focus_child, argv[2]);
1661 if (!strcmp(argv[0], "wrap-lines"))
1662 return parse_bool(&opt_wrap_lines, argv[2]);
1664 if (!strcmp(argv[0], "show-id"))
1665 return parse_bool(&opt_show_id, argv[2]);
1667 if (!strcmp(argv[0], "id-width"))
1668 return parse_id(&opt_id_cols, argv[2]);
1670 if (!strcmp(argv[0], "title-overflow")) {
1671 bool matched;
1672 enum option_code code;
1675 * "title-overflow" is considered a boolint.
1676 * We try to parse it as a boolean (and set the value to 50 if true),
1677 * otherwise we parse it as an integer and use the given value.
1679 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1680 if (code == OPT_OK && matched) {
1681 if (opt_show_title_overflow)
1682 opt_title_overflow = 50;
1683 } else {
1684 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1685 if (code == OPT_OK)
1686 opt_show_title_overflow = TRUE;
1689 return code;
1692 if (!strcmp(argv[0], "editor-line-number"))
1693 return parse_bool(&opt_editor_lineno, argv[2]);
1695 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1698 /* Wants: mode request key */
1699 static enum option_code
1700 option_bind_command(int argc, const char *argv[])
1702 enum request request;
1703 struct keymap *keymap;
1704 int key;
1706 if (argc < 3)
1707 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1709 if (!(keymap = get_keymap(argv[0])))
1710 return OPT_ERR_UNKNOWN_KEY_MAP;
1712 key = get_key_value(argv[1]);
1713 if (key == ERR)
1714 return OPT_ERR_UNKNOWN_KEY;
1716 request = get_request(argv[2]);
1717 if (request == REQ_UNKNOWN) {
1718 static const struct enum_map obsolete[] = {
1719 ENUM_MAP("cherry-pick", REQ_NONE),
1720 ENUM_MAP("screen-resize", REQ_NONE),
1721 ENUM_MAP("tree-parent", REQ_PARENT),
1723 int alias;
1725 if (map_enum(&alias, obsolete, argv[2])) {
1726 if (alias != REQ_NONE)
1727 add_keybinding(keymap, alias, key);
1728 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1732 if (request == REQ_UNKNOWN) {
1733 enum run_request_flag flags = RUN_REQUEST_FORCE;
1735 if (strchr("!?@<", *argv[2])) {
1736 while (*argv[2]) {
1737 if (*argv[2] == '@') {
1738 flags |= RUN_REQUEST_SILENT;
1739 } else if (*argv[2] == '?') {
1740 flags |= RUN_REQUEST_CONFIRM;
1741 } else if (*argv[2] == '<') {
1742 flags |= RUN_REQUEST_EXIT;
1743 } else if (*argv[2] != '!') {
1744 break;
1746 argv[2]++;
1749 } else if (*argv[2] == ':') {
1750 argv[2]++;
1751 flags |= RUN_REQUEST_INTERNAL;
1753 } else {
1754 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1757 return add_run_request(keymap, key, argv + 2, flags)
1758 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1761 add_keybinding(keymap, request, key);
1763 return OPT_OK;
1767 static enum option_code load_option_file(const char *path);
1769 static enum option_code
1770 option_source_command(int argc, const char *argv[])
1772 if (argc < 1)
1773 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1775 return load_option_file(argv[0]);
1778 static enum option_code
1779 set_option(const char *opt, char *value)
1781 const char *argv[SIZEOF_ARG];
1782 int argc = 0;
1784 if (!argv_from_string(argv, &argc, value))
1785 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1787 if (!strcmp(opt, "color"))
1788 return option_color_command(argc, argv);
1790 if (!strcmp(opt, "set"))
1791 return option_set_command(argc, argv);
1793 if (!strcmp(opt, "bind"))
1794 return option_bind_command(argc, argv);
1796 if (!strcmp(opt, "source"))
1797 return option_source_command(argc, argv);
1799 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1802 struct config_state {
1803 const char *path;
1804 int lineno;
1805 bool errors;
1808 static int
1809 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1811 struct config_state *config = data;
1812 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1814 config->lineno++;
1816 /* Check for comment markers, since read_properties() will
1817 * only ensure opt and value are split at first " \t". */
1818 optlen = strcspn(opt, "#");
1819 if (optlen == 0)
1820 return OK;
1822 if (opt[optlen] == 0) {
1823 /* Look for comment endings in the value. */
1824 size_t len = strcspn(value, "#");
1826 if (len < valuelen) {
1827 valuelen = len;
1828 value[valuelen] = 0;
1831 status = set_option(opt, value);
1834 if (status != OPT_OK) {
1835 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1836 option_errors[status], (int) optlen, opt);
1837 config->errors = TRUE;
1840 /* Always keep going if errors are encountered. */
1841 return OK;
1844 static enum option_code
1845 load_option_file(const char *path)
1847 struct config_state config = { path, 0, FALSE };
1848 struct io io;
1849 char buf[SIZEOF_STR];
1851 /* Do not read configuration from stdin if set to "" */
1852 if (!path || !strlen(path))
1853 return OPT_OK;
1855 if (!prefixcmp(path, "~/")) {
1856 const char *home = getenv("HOME");
1858 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1859 return OPT_ERR_HOME_UNRESOLVABLE;
1860 path = buf;
1863 /* It's OK that the file doesn't exist. */
1864 if (!io_open(&io, "%s", path))
1865 return OPT_ERR_FILE_DOES_NOT_EXIST;
1867 if (io_load(&io, " \t", read_option, &config) == ERR ||
1868 config.errors == TRUE)
1869 warn("Errors while loading %s.", path);
1870 return OPT_OK;
1873 static int
1874 load_options(void)
1876 const char *tigrc_user = getenv("TIGRC_USER");
1877 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1878 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1879 const bool diff_opts_from_args = !!opt_diff_argv;
1881 if (!tigrc_system)
1882 tigrc_system = SYSCONFDIR "/tigrc";
1883 load_option_file(tigrc_system);
1885 if (!tigrc_user)
1886 tigrc_user = "~/.tigrc";
1887 load_option_file(tigrc_user);
1889 /* Add _after_ loading config files to avoid adding run requests
1890 * that conflict with keybindings. */
1891 add_builtin_run_requests();
1893 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1894 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1895 char buf[SIZEOF_STR];
1896 int argc = 0;
1898 if (!string_format(buf, "%s", tig_diff_opts) ||
1899 !argv_from_string(diff_opts, &argc, buf))
1900 die("TIG_DIFF_OPTS contains too many arguments");
1901 else if (!argv_copy(&opt_diff_argv, diff_opts))
1902 die("Failed to format TIG_DIFF_OPTS arguments");
1905 return OK;
1910 * The viewer
1913 struct view;
1914 struct view_ops;
1916 /* The display array of active views and the index of the current view. */
1917 static struct view *display[2];
1918 static WINDOW *display_win[2];
1919 static WINDOW *display_title[2];
1920 static WINDOW *display_sep;
1922 static unsigned int current_view;
1924 #define foreach_displayed_view(view, i) \
1925 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1927 #define displayed_views() (display[1] != NULL ? 2 : 1)
1929 /* Current head and commit ID */
1930 static char ref_blob[SIZEOF_REF] = "";
1931 static char ref_commit[SIZEOF_REF] = "HEAD";
1932 static char ref_head[SIZEOF_REF] = "HEAD";
1933 static char ref_branch[SIZEOF_REF] = "";
1934 static char ref_status[SIZEOF_STR] = "";
1935 static char ref_stash[SIZEOF_REF] = "";
1937 enum view_flag {
1938 VIEW_NO_FLAGS = 0,
1939 VIEW_ALWAYS_LINENO = 1 << 0,
1940 VIEW_CUSTOM_STATUS = 1 << 1,
1941 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1942 VIEW_ADD_PAGER_REFS = 1 << 3,
1943 VIEW_OPEN_DIFF = 1 << 4,
1944 VIEW_NO_REF = 1 << 5,
1945 VIEW_NO_GIT_DIR = 1 << 6,
1946 VIEW_DIFF_LIKE = 1 << 7,
1947 VIEW_STDIN = 1 << 8,
1948 VIEW_SEND_CHILD_ENTER = 1 << 9,
1949 VIEW_FILE_FILTER = 1 << 10,
1952 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1954 struct position {
1955 unsigned long offset; /* Offset of the window top */
1956 unsigned long col; /* Offset from the window side. */
1957 unsigned long lineno; /* Current line number */
1960 struct view {
1961 const char *name; /* View name */
1962 const char *id; /* Points to either of ref_{head,commit,blob} */
1964 struct view_ops *ops; /* View operations */
1966 char ref[SIZEOF_REF]; /* Hovered commit reference */
1967 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1969 int height, width; /* The width and height of the main window */
1970 WINDOW *win; /* The main window */
1972 /* Navigation */
1973 struct position pos; /* Current position. */
1974 struct position prev_pos; /* Previous position. */
1976 /* Searching */
1977 char grep[SIZEOF_STR]; /* Search string */
1978 regex_t *regex; /* Pre-compiled regexp */
1980 /* If non-NULL, points to the view that opened this view. If this view
1981 * is closed tig will switch back to the parent view. */
1982 struct view *parent;
1983 struct view *prev;
1985 /* Buffering */
1986 size_t lines; /* Total number of lines */
1987 struct line *line; /* Line index */
1988 unsigned int digits; /* Number of digits in the lines member. */
1990 /* Number of lines with custom status, not to be counted in the
1991 * view title. */
1992 unsigned int custom_lines;
1994 /* Drawing */
1995 struct line *curline; /* Line currently being drawn. */
1996 enum line_type curtype; /* Attribute currently used for drawing. */
1997 unsigned long col; /* Column when drawing. */
1998 bool has_scrolled; /* View was scrolled. */
1999 bool force_redraw; /* Whether to force a redraw after reading. */
2001 /* Loading */
2002 const char **argv; /* Shell command arguments. */
2003 const char *dir; /* Directory from which to execute. */
2004 struct io io;
2005 struct io *pipe;
2006 time_t start_time;
2007 time_t update_secs;
2008 struct encoding *encoding;
2009 bool unrefreshable;
2011 /* Private data */
2012 void *private;
2015 enum open_flags {
2016 OPEN_DEFAULT = 0, /* Use default view switching. */
2017 OPEN_SPLIT = 1, /* Split current view. */
2018 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
2019 OPEN_REFRESH = 16, /* Refresh view using previous command. */
2020 OPEN_PREPARED = 32, /* Open already prepared command. */
2021 OPEN_EXTRA = 64, /* Open extra data from command. */
2024 struct view_ops {
2025 /* What type of content being displayed. Used in the title bar. */
2026 const char *type;
2027 /* What keymap does this view have */
2028 struct keymap keymap;
2029 /* Flags to control the view behavior. */
2030 enum view_flag flags;
2031 /* Size of private data. */
2032 size_t private_size;
2033 /* Open and reads in all view content. */
2034 bool (*open)(struct view *view, enum open_flags flags);
2035 /* Read one line; updates view->line. */
2036 bool (*read)(struct view *view, char *data);
2037 /* Draw one line; @lineno must be < view->height. */
2038 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
2039 /* Depending on view handle a special requests. */
2040 enum request (*request)(struct view *view, enum request request, struct line *line);
2041 /* Search for regexp in a line. */
2042 bool (*grep)(struct view *view, struct line *line);
2043 /* Select line */
2044 void (*select)(struct view *view, struct line *line);
2045 /* Release resources when reloading the view */
2046 void (*done)(struct view *view);
2049 #define VIEW_OPS(id, name, ref) name##_ops
2050 static struct view_ops VIEW_INFO(VIEW_OPS);
2052 static struct view views[] = {
2053 #define VIEW_DATA(id, name, ref) \
2054 { #name, ref, &name##_ops }
2055 VIEW_INFO(VIEW_DATA)
2058 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2060 #define foreach_view(view, i) \
2061 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2063 #define view_is_displayed(view) \
2064 (view == display[0] || view == display[1])
2066 #define view_has_line(view, line_) \
2067 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2069 static bool
2070 forward_request_to_child(struct view *child, enum request request)
2072 return displayed_views() == 2 && view_is_displayed(child) &&
2073 !strcmp(child->vid, child->id);
2076 static enum request
2077 view_request(struct view *view, enum request request)
2079 if (!view || !view->lines)
2080 return request;
2082 if (request == REQ_ENTER && !opt_focus_child &&
2083 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2084 struct view *child = display[1];
2086 if (forward_request_to_child(child, request)) {
2087 view_request(child, request);
2088 return REQ_NONE;
2092 if (request == REQ_REFRESH && view->unrefreshable) {
2093 report("This view can not be refreshed");
2094 return REQ_NONE;
2097 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2101 * View drawing.
2104 static inline void
2105 set_view_attr(struct view *view, enum line_type type)
2107 if (!view->curline->selected && view->curtype != type) {
2108 (void) wattrset(view->win, get_line_attr(type));
2109 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2110 view->curtype = type;
2114 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2116 static bool
2117 draw_chars(struct view *view, enum line_type type, const char *string,
2118 int max_len, bool use_tilde)
2120 int len = 0;
2121 int col = 0;
2122 int trimmed = FALSE;
2123 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2125 if (max_len <= 0)
2126 return VIEW_MAX_LEN(view) <= 0;
2128 if (opt_iconv_out != ICONV_NONE) {
2129 string = encoding_iconv(opt_iconv_out, string);
2130 if (!string)
2131 return VIEW_MAX_LEN(view) <= 0;
2134 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2136 set_view_attr(view, type);
2137 if (len > 0) {
2138 waddnstr(view->win, string, len);
2140 if (trimmed && use_tilde) {
2141 set_view_attr(view, LINE_DELIMITER);
2142 waddch(view->win, '~');
2143 col++;
2147 view->col += col;
2148 return VIEW_MAX_LEN(view) <= 0;
2151 static bool
2152 draw_space(struct view *view, enum line_type type, int max, int spaces)
2154 static char space[] = " ";
2156 spaces = MIN(max, spaces);
2158 while (spaces > 0) {
2159 int len = MIN(spaces, sizeof(space) - 1);
2161 if (draw_chars(view, type, space, len, FALSE))
2162 return TRUE;
2163 spaces -= len;
2166 return VIEW_MAX_LEN(view) <= 0;
2169 static bool
2170 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2172 static char text[SIZEOF_STR];
2174 do {
2175 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2177 if (draw_chars(view, type, text, max_len, use_tilde))
2178 return TRUE;
2179 string += pos;
2180 } while (*string);
2182 return VIEW_MAX_LEN(view) <= 0;
2185 static bool
2186 draw_text(struct view *view, enum line_type type, const char *string)
2188 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2191 static bool
2192 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2194 if (on) {
2195 int max = MIN(VIEW_MAX_LEN(view), overflow);
2196 int len = strlen(text);
2198 if (draw_text_expanded(view, type, text, max, max < overflow))
2199 return TRUE;
2201 text = len > overflow ? text + overflow : "";
2202 type = LINE_OVERFLOW;
2205 if (*text && draw_text(view, type, text))
2206 return TRUE;
2208 return VIEW_MAX_LEN(view) <= 0;
2211 #define draw_commit_title(view, text, offset) \
2212 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2214 static bool PRINTF_LIKE(3, 4)
2215 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2217 char text[SIZEOF_STR];
2218 int retval;
2220 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2221 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2224 static bool
2225 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2227 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2228 int max = VIEW_MAX_LEN(view);
2229 int i;
2231 if (max < size)
2232 size = max;
2234 set_view_attr(view, type);
2235 /* Using waddch() instead of waddnstr() ensures that
2236 * they'll be rendered correctly for the cursor line. */
2237 for (i = skip; i < size; i++)
2238 waddch(view->win, graphic[i]);
2240 view->col += size;
2241 if (separator) {
2242 if (size < max && skip <= size)
2243 waddch(view->win, ' ');
2244 view->col++;
2247 return VIEW_MAX_LEN(view) <= 0;
2250 enum align {
2251 ALIGN_LEFT,
2252 ALIGN_RIGHT
2255 static bool
2256 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2258 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2259 int col = view->col;
2261 if (!text)
2262 return draw_space(view, type, max, max);
2264 if (align == ALIGN_RIGHT) {
2265 int textlen = strlen(text);
2266 int leftpad = max - textlen - 1;
2268 if (leftpad > 0) {
2269 if (draw_space(view, type, leftpad, leftpad))
2270 return TRUE;
2271 max -= leftpad;
2272 col += leftpad;;
2276 return draw_chars(view, type, text, max - 1, trim)
2277 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2280 static bool PRINTF_LIKE(4, 5)
2281 draw_formatted_field(struct view *view, enum line_type type, int width, const char *format, ...)
2283 char text[SIZEOF_STR];
2284 int retval;
2286 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2287 if (retval < 0)
2288 return VIEW_MAX_LEN(view) <= 0;
2289 return draw_field(view, type, text, width, ALIGN_LEFT, FALSE);
2292 static bool
2293 draw_date(struct view *view, struct time *time)
2295 const char *date = mkdate(time, opt_date);
2296 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2298 if (opt_date == DATE_NO)
2299 return FALSE;
2301 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2304 static bool
2305 draw_author(struct view *view, const struct ident *author)
2307 bool trim = author_trim(opt_author_width);
2308 const char *text = mkauthor(author, opt_author_width, opt_author);
2310 if (opt_author == AUTHOR_NO)
2311 return FALSE;
2313 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2316 static bool
2317 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2319 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2322 static bool
2323 draw_id(struct view *view, const char *id)
2325 if (!opt_show_id)
2326 return FALSE;
2328 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2331 static bool
2332 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2334 bool trim = filename && strlen(filename) >= opt_filename_width;
2336 if (opt_filename == FILENAME_NO)
2337 return FALSE;
2339 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2340 return FALSE;
2342 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2345 static bool
2346 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2348 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2350 if (!width || opt_file_size == FILE_SIZE_NO)
2351 return FALSE;
2353 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2356 static bool
2357 draw_mode(struct view *view, mode_t mode)
2359 const char *str = mkmode(mode);
2361 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2364 static bool
2365 draw_lineno(struct view *view, unsigned int lineno)
2367 char number[10];
2368 int digits3 = view->digits < 3 ? 3 : view->digits;
2369 int max = MIN(VIEW_MAX_LEN(view), digits3);
2370 char *text = NULL;
2371 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2373 if (!opt_line_number)
2374 return FALSE;
2376 lineno += view->pos.offset + 1;
2377 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2378 static char fmt[] = "%1ld";
2380 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2381 if (string_format(number, fmt, lineno))
2382 text = number;
2384 if (text)
2385 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2386 else
2387 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2388 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2391 static bool
2392 draw_refs(struct view *view, struct ref_list *refs)
2394 size_t i;
2396 if (!opt_show_refs || !refs)
2397 return FALSE;
2399 for (i = 0; i < refs->size; i++) {
2400 struct ref *ref = refs->refs[i];
2401 enum line_type type = get_line_type_from_ref(ref);
2403 if (draw_formatted(view, type, "[%s]", ref->name))
2404 return TRUE;
2406 if (draw_text(view, LINE_DEFAULT, " "))
2407 return TRUE;
2410 return FALSE;
2413 static bool
2414 draw_view_line(struct view *view, unsigned int lineno)
2416 struct line *line;
2417 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2419 assert(view_is_displayed(view));
2421 if (view->pos.offset + lineno >= view->lines)
2422 return FALSE;
2424 line = &view->line[view->pos.offset + lineno];
2426 wmove(view->win, lineno, 0);
2427 if (line->cleareol)
2428 wclrtoeol(view->win);
2429 view->col = 0;
2430 view->curline = line;
2431 view->curtype = LINE_NONE;
2432 line->selected = FALSE;
2433 line->dirty = line->cleareol = 0;
2435 if (selected) {
2436 set_view_attr(view, LINE_CURSOR);
2437 line->selected = TRUE;
2438 view->ops->select(view, line);
2441 return view->ops->draw(view, line, lineno);
2444 static void
2445 redraw_view_dirty(struct view *view)
2447 bool dirty = FALSE;
2448 int lineno;
2450 for (lineno = 0; lineno < view->height; lineno++) {
2451 if (view->pos.offset + lineno >= view->lines)
2452 break;
2453 if (!view->line[view->pos.offset + lineno].dirty)
2454 continue;
2455 dirty = TRUE;
2456 if (!draw_view_line(view, lineno))
2457 break;
2460 if (!dirty)
2461 return;
2462 wnoutrefresh(view->win);
2465 static void
2466 redraw_view_from(struct view *view, int lineno)
2468 assert(0 <= lineno && lineno < view->height);
2470 for (; lineno < view->height; lineno++) {
2471 if (!draw_view_line(view, lineno))
2472 break;
2475 wnoutrefresh(view->win);
2478 static void
2479 redraw_view(struct view *view)
2481 werase(view->win);
2482 redraw_view_from(view, 0);
2486 static void
2487 update_view_title(struct view *view)
2489 char buf[SIZEOF_STR];
2490 char state[SIZEOF_STR];
2491 size_t bufpos = 0, statelen = 0;
2492 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2493 struct line *line = &view->line[view->pos.lineno];
2495 assert(view_is_displayed(view));
2497 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2498 line->lineno) {
2499 unsigned int view_lines = view->pos.offset + view->height;
2500 unsigned int lines = view->lines
2501 ? MIN(view_lines, view->lines) * 100 / view->lines
2502 : 0;
2504 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2505 view->ops->type,
2506 line->lineno,
2507 view->lines - view->custom_lines,
2508 lines);
2512 if (view->pipe) {
2513 time_t secs = time(NULL) - view->start_time;
2515 /* Three git seconds are a long time ... */
2516 if (secs > 2)
2517 string_format_from(state, &statelen, " loading %lds", secs);
2520 string_format_from(buf, &bufpos, "[%s]", view->name);
2521 if (*view->ref && bufpos < view->width) {
2522 size_t refsize = strlen(view->ref);
2523 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2525 if (minsize < view->width)
2526 refsize = view->width - minsize + 7;
2527 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2530 if (statelen && bufpos < view->width) {
2531 string_format_from(buf, &bufpos, "%s", state);
2534 if (view == display[current_view])
2535 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2536 else
2537 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2539 mvwaddnstr(window, 0, 0, buf, bufpos);
2540 wclrtoeol(window);
2541 wnoutrefresh(window);
2544 static int
2545 apply_step(double step, int value)
2547 if (step >= 1)
2548 return (int) step;
2549 value *= step + 0.01;
2550 return value ? value : 1;
2553 static void
2554 apply_horizontal_split(struct view *base, struct view *view)
2556 view->width = base->width;
2557 view->height = apply_step(opt_scale_split_view, base->height);
2558 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2559 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2560 base->height -= view->height;
2563 static void
2564 apply_vertical_split(struct view *base, struct view *view)
2566 view->height = base->height;
2567 view->width = apply_step(opt_scale_vsplit_view, base->width);
2568 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2569 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2570 base->width -= view->width;
2573 static void
2574 redraw_display_separator(bool clear)
2576 if (displayed_views() > 1 && opt_vsplit) {
2577 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2579 if (clear)
2580 wclear(display_sep);
2581 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2582 wnoutrefresh(display_sep);
2586 static void
2587 resize_display(void)
2589 int x, y, i;
2590 struct view *base = display[0];
2591 struct view *view = display[1] ? display[1] : display[0];
2593 /* Setup window dimensions */
2595 getmaxyx(stdscr, base->height, base->width);
2596 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2597 string_format(opt_env_lines, "LINES=%d", base->height);
2599 /* Make room for the status window. */
2600 base->height -= 1;
2602 if (view != base) {
2603 if (opt_vsplit) {
2604 apply_vertical_split(base, view);
2606 /* Make room for the separator bar. */
2607 view->width -= 1;
2608 } else {
2609 apply_horizontal_split(base, view);
2612 /* Make room for the title bar. */
2613 view->height -= 1;
2616 /* Make room for the title bar. */
2617 base->height -= 1;
2619 x = y = 0;
2621 foreach_displayed_view (view, i) {
2622 if (!display_win[i]) {
2623 display_win[i] = newwin(view->height, view->width, y, x);
2624 if (!display_win[i])
2625 die("Failed to create %s view", view->name);
2627 scrollok(display_win[i], FALSE);
2629 display_title[i] = newwin(1, view->width, y + view->height, x);
2630 if (!display_title[i])
2631 die("Failed to create title window");
2633 } else {
2634 wresize(display_win[i], view->height, view->width);
2635 mvwin(display_win[i], y, x);
2636 wresize(display_title[i], 1, view->width);
2637 mvwin(display_title[i], y + view->height, x);
2640 if (i > 0 && opt_vsplit) {
2641 if (!display_sep) {
2642 display_sep = newwin(view->height, 1, 0, x - 1);
2643 if (!display_sep)
2644 die("Failed to create separator window");
2646 } else {
2647 wresize(display_sep, view->height, 1);
2648 mvwin(display_sep, 0, x - 1);
2652 view->win = display_win[i];
2654 if (opt_vsplit)
2655 x += view->width + 1;
2656 else
2657 y += view->height + 1;
2660 redraw_display_separator(FALSE);
2663 static void
2664 redraw_display(bool clear)
2666 struct view *view;
2667 int i;
2669 foreach_displayed_view (view, i) {
2670 if (clear)
2671 wclear(view->win);
2672 redraw_view(view);
2673 update_view_title(view);
2676 redraw_display_separator(clear);
2680 * Option management
2683 #define TOGGLE_MENU_INFO(_) \
2684 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0), \
2685 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map)), \
2686 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map)), \
2687 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map)), \
2688 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0), \
2689 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map)), \
2690 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map)), \
2691 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map)), \
2692 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map)), \
2693 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0), \
2694 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0), \
2695 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0), \
2696 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0), \
2697 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0), \
2699 static bool
2700 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2702 const struct {
2703 enum request request;
2704 const struct enum_map *map;
2705 size_t map_size;
2706 } data[] = {
2707 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size) { REQ_TOGGLE_ ## id, map, map_size }
2708 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2710 const struct menu_item menu[] = {
2711 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size) { key, help, value }
2712 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2713 { 0 }
2715 int i = 0;
2717 if (request == REQ_OPTIONS) {
2718 if (!prompt_menu("Toggle option", menu, &i))
2719 return FALSE;
2720 } else {
2721 while (i < ARRAY_SIZE(data) && data[i].request != request)
2722 i++;
2723 if (i >= ARRAY_SIZE(data))
2724 die("Invalid request (%d)", request);
2727 if (data[i].map != NULL) {
2728 unsigned int *opt = menu[i].data;
2730 *opt = (*opt + 1) % data[i].map_size;
2731 if (data[i].map == ignore_space_map) {
2732 update_ignore_space_arg();
2733 string_format_size(msg, SIZEOF_STR,
2734 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2735 return TRUE;
2737 } else if (data[i].map == commit_order_map) {
2738 update_commit_order_arg();
2739 string_format_size(msg, SIZEOF_STR,
2740 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2741 return TRUE;
2744 string_format_size(msg, SIZEOF_STR,
2745 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2747 } else {
2748 bool *option = menu[i].data;
2750 *option = !*option;
2751 string_format_size(msg, SIZEOF_STR,
2752 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2754 if (option == &opt_file_filter || option == &opt_rev_graph)
2755 return TRUE;
2758 return FALSE;
2763 * Navigation
2766 static bool
2767 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2769 if (lineno >= view->lines)
2770 lineno = view->lines > 0 ? view->lines - 1 : 0;
2772 if (offset > lineno || offset + view->height <= lineno) {
2773 unsigned long half = view->height / 2;
2775 if (lineno > half)
2776 offset = lineno - half;
2777 else
2778 offset = 0;
2781 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2782 view->pos.offset = offset;
2783 view->pos.lineno = lineno;
2784 return TRUE;
2787 return FALSE;
2790 /* Scrolling backend */
2791 static void
2792 do_scroll_view(struct view *view, int lines)
2794 bool redraw_current_line = FALSE;
2796 /* The rendering expects the new offset. */
2797 view->pos.offset += lines;
2799 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2800 assert(lines);
2802 /* Move current line into the view. */
2803 if (view->pos.lineno < view->pos.offset) {
2804 view->pos.lineno = view->pos.offset;
2805 redraw_current_line = TRUE;
2806 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2807 view->pos.lineno = view->pos.offset + view->height - 1;
2808 redraw_current_line = TRUE;
2811 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2813 /* Redraw the whole screen if scrolling is pointless. */
2814 if (view->height < ABS(lines)) {
2815 redraw_view(view);
2817 } else {
2818 int line = lines > 0 ? view->height - lines : 0;
2819 int end = line + ABS(lines);
2821 scrollok(view->win, TRUE);
2822 wscrl(view->win, lines);
2823 scrollok(view->win, FALSE);
2825 while (line < end && draw_view_line(view, line))
2826 line++;
2828 if (redraw_current_line)
2829 draw_view_line(view, view->pos.lineno - view->pos.offset);
2830 wnoutrefresh(view->win);
2833 view->has_scrolled = TRUE;
2834 report_clear();
2837 /* Scroll frontend */
2838 static void
2839 scroll_view(struct view *view, enum request request)
2841 int lines = 1;
2843 assert(view_is_displayed(view));
2845 switch (request) {
2846 case REQ_SCROLL_FIRST_COL:
2847 view->pos.col = 0;
2848 redraw_view_from(view, 0);
2849 report_clear();
2850 return;
2851 case REQ_SCROLL_LEFT:
2852 if (view->pos.col == 0) {
2853 report("Cannot scroll beyond the first column");
2854 return;
2856 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2857 view->pos.col = 0;
2858 else
2859 view->pos.col -= apply_step(opt_hscroll, view->width);
2860 redraw_view_from(view, 0);
2861 report_clear();
2862 return;
2863 case REQ_SCROLL_RIGHT:
2864 view->pos.col += apply_step(opt_hscroll, view->width);
2865 redraw_view(view);
2866 report_clear();
2867 return;
2868 case REQ_SCROLL_PAGE_DOWN:
2869 lines = view->height;
2870 case REQ_SCROLL_LINE_DOWN:
2871 if (view->pos.offset + lines > view->lines)
2872 lines = view->lines - view->pos.offset;
2874 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2875 report("Cannot scroll beyond the last line");
2876 return;
2878 break;
2880 case REQ_SCROLL_PAGE_UP:
2881 lines = view->height;
2882 case REQ_SCROLL_LINE_UP:
2883 if (lines > view->pos.offset)
2884 lines = view->pos.offset;
2886 if (lines == 0) {
2887 report("Cannot scroll beyond the first line");
2888 return;
2891 lines = -lines;
2892 break;
2894 default:
2895 die("request %d not handled in switch", request);
2898 do_scroll_view(view, lines);
2901 /* Cursor moving */
2902 static void
2903 move_view(struct view *view, enum request request)
2905 int scroll_steps = 0;
2906 int steps;
2908 switch (request) {
2909 case REQ_MOVE_FIRST_LINE:
2910 steps = -view->pos.lineno;
2911 break;
2913 case REQ_MOVE_LAST_LINE:
2914 steps = view->lines - view->pos.lineno - 1;
2915 break;
2917 case REQ_MOVE_PAGE_UP:
2918 steps = view->height > view->pos.lineno
2919 ? -view->pos.lineno : -view->height;
2920 break;
2922 case REQ_MOVE_PAGE_DOWN:
2923 steps = view->pos.lineno + view->height >= view->lines
2924 ? view->lines - view->pos.lineno - 1 : view->height;
2925 break;
2927 case REQ_MOVE_UP:
2928 case REQ_PREVIOUS:
2929 steps = -1;
2930 break;
2932 case REQ_MOVE_DOWN:
2933 case REQ_NEXT:
2934 steps = 1;
2935 break;
2937 default:
2938 die("request %d not handled in switch", request);
2941 if (steps <= 0 && view->pos.lineno == 0) {
2942 report("Cannot move beyond the first line");
2943 return;
2945 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2946 report("Cannot move beyond the last line");
2947 return;
2950 /* Move the current line */
2951 view->pos.lineno += steps;
2952 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2954 /* Check whether the view needs to be scrolled */
2955 if (view->pos.lineno < view->pos.offset ||
2956 view->pos.lineno >= view->pos.offset + view->height) {
2957 scroll_steps = steps;
2958 if (steps < 0 && -steps > view->pos.offset) {
2959 scroll_steps = -view->pos.offset;
2961 } else if (steps > 0) {
2962 if (view->pos.lineno == view->lines - 1 &&
2963 view->lines > view->height) {
2964 scroll_steps = view->lines - view->pos.offset - 1;
2965 if (scroll_steps >= view->height)
2966 scroll_steps -= view->height - 1;
2971 if (!view_is_displayed(view)) {
2972 view->pos.offset += scroll_steps;
2973 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2974 view->ops->select(view, &view->line[view->pos.lineno]);
2975 return;
2978 /* Repaint the old "current" line if we be scrolling */
2979 if (ABS(steps) < view->height)
2980 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2982 if (scroll_steps) {
2983 do_scroll_view(view, scroll_steps);
2984 return;
2987 /* Draw the current line */
2988 draw_view_line(view, view->pos.lineno - view->pos.offset);
2990 wnoutrefresh(view->win);
2991 report_clear();
2996 * Searching
2999 static void search_view(struct view *view, enum request request);
3001 static bool
3002 grep_text(struct view *view, const char *text[])
3004 regmatch_t pmatch;
3005 size_t i;
3007 for (i = 0; text[i]; i++)
3008 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
3009 return TRUE;
3010 return FALSE;
3013 static void
3014 select_view_line(struct view *view, unsigned long lineno)
3016 struct position old = view->pos;
3018 if (goto_view_line(view, view->pos.offset, lineno)) {
3019 if (view_is_displayed(view)) {
3020 if (old.offset != view->pos.offset) {
3021 redraw_view(view);
3022 } else {
3023 draw_view_line(view, old.lineno - view->pos.offset);
3024 draw_view_line(view, view->pos.lineno - view->pos.offset);
3025 wnoutrefresh(view->win);
3027 } else {
3028 view->ops->select(view, &view->line[view->pos.lineno]);
3033 static void
3034 find_next(struct view *view, enum request request)
3036 unsigned long lineno = view->pos.lineno;
3037 int direction;
3039 if (!*view->grep) {
3040 if (!*opt_search)
3041 report("No previous search");
3042 else
3043 search_view(view, request);
3044 return;
3047 switch (request) {
3048 case REQ_SEARCH:
3049 case REQ_FIND_NEXT:
3050 direction = 1;
3051 break;
3053 case REQ_SEARCH_BACK:
3054 case REQ_FIND_PREV:
3055 direction = -1;
3056 break;
3058 default:
3059 return;
3062 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
3063 lineno += direction;
3065 /* Note, lineno is unsigned long so will wrap around in which case it
3066 * will become bigger than view->lines. */
3067 for (; lineno < view->lines; lineno += direction) {
3068 if (view->ops->grep(view, &view->line[lineno])) {
3069 select_view_line(view, lineno);
3070 report("Line %ld matches '%s'", lineno + 1, view->grep);
3071 return;
3075 report("No match found for '%s'", view->grep);
3078 static void
3079 search_view(struct view *view, enum request request)
3081 int regex_err;
3082 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3084 if (view->regex) {
3085 regfree(view->regex);
3086 *view->grep = 0;
3087 } else {
3088 view->regex = calloc(1, sizeof(*view->regex));
3089 if (!view->regex)
3090 return;
3093 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3094 if (regex_err != 0) {
3095 char buf[SIZEOF_STR] = "unknown error";
3097 regerror(regex_err, view->regex, buf, sizeof(buf));
3098 report("Search failed: %s", buf);
3099 return;
3102 string_copy(view->grep, opt_search);
3104 find_next(view, request);
3108 * Incremental updating
3111 static inline bool
3112 check_position(struct position *pos)
3114 return pos->lineno || pos->col || pos->offset;
3117 static inline void
3118 clear_position(struct position *pos)
3120 memset(pos, 0, sizeof(*pos));
3123 static void
3124 reset_view(struct view *view)
3126 int i;
3128 if (view->ops->done)
3129 view->ops->done(view);
3131 for (i = 0; i < view->lines; i++)
3132 free(view->line[i].data);
3133 free(view->line);
3135 view->prev_pos = view->pos;
3136 clear_position(&view->pos);
3138 view->line = NULL;
3139 view->lines = 0;
3140 view->vid[0] = 0;
3141 view->custom_lines = 0;
3142 view->update_secs = 0;
3145 struct format_context {
3146 struct view *view;
3147 char buf[SIZEOF_STR];
3148 size_t bufpos;
3149 bool file_filter;
3152 static bool
3153 format_expand_arg(struct format_context *format, const char *name)
3155 static struct {
3156 const char *name;
3157 size_t namelen;
3158 const char *value;
3159 const char *value_if_empty;
3160 } vars[] = {
3161 #define FORMAT_VAR(name, value, value_if_empty) \
3162 { name, STRING_SIZE(name), value, value_if_empty }
3163 FORMAT_VAR("%(directory)", opt_path, "."),
3164 FORMAT_VAR("%(file)", opt_file, ""),
3165 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3166 FORMAT_VAR("%(head)", ref_head, ""),
3167 FORMAT_VAR("%(commit)", ref_commit, ""),
3168 FORMAT_VAR("%(blob)", ref_blob, ""),
3169 FORMAT_VAR("%(branch)", ref_branch, ""),
3170 FORMAT_VAR("%(stash)", ref_stash, ""),
3172 int i;
3174 if (!prefixcmp(name, "%(prompt)")) {
3175 const char *value = read_prompt("Command argument: ");
3177 return string_format_from(format->buf, &format->bufpos, "%s", value);
3180 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3181 const char *value;
3183 if (strncmp(name, vars[i].name, vars[i].namelen))
3184 continue;
3186 if (vars[i].value == opt_file && !format->file_filter)
3187 return TRUE;
3189 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3190 if (!*value)
3191 return TRUE;
3193 return string_format_from(format->buf, &format->bufpos, "%s", value);
3196 report("Unknown replacement: `%s`", name);
3197 return NULL;
3200 static bool
3201 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3203 int i;
3205 for (i = 0; i < sizeof(format->buf); i++)
3206 format->buf[i] = 0;
3207 format->bufpos = 0;
3209 while (arg) {
3210 char *next = strstr(arg, "%(");
3211 int len = next ? next - arg : strlen(arg);
3213 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3214 return FALSE;
3216 if (next && !format_expand_arg(format, next))
3217 return FALSE;
3219 arg = next ? strchr(next, ')') + 1 : NULL;
3222 return argv_append(dst_argv, format->buf);
3225 static bool
3226 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3228 int argc;
3230 if (!src_argv)
3231 return TRUE;
3233 for (argc = 0; src_argv[argc]; argc++)
3234 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3235 return FALSE;
3237 return src_argv[argc] == NULL;
3240 static bool
3241 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3243 struct format_context format = { view, "", 0, file_filter };
3244 int argc;
3246 argv_free(*dst_argv);
3248 for (argc = 0; src_argv[argc]; argc++) {
3249 const char *arg = src_argv[argc];
3251 if (!strcmp(arg, "%(fileargs)")) {
3252 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3253 break;
3255 } else if (!strcmp(arg, "%(diffargs)")) {
3256 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3257 break;
3259 } else if (!strcmp(arg, "%(blameargs)")) {
3260 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3261 break;
3263 } else if (!strcmp(arg, "%(revargs)") ||
3264 (first && !strcmp(arg, "%(commit)"))) {
3265 if (!argv_append_array(dst_argv, opt_rev_argv))
3266 break;
3268 } else if (!format_append_arg(&format, dst_argv, arg)) {
3269 break;
3273 return src_argv[argc] == NULL;
3276 static bool
3277 restore_view_position(struct view *view)
3279 /* A view without a previous view is the first view */
3280 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3281 select_view_line(view, opt_lineno - 1);
3282 opt_lineno = 0;
3285 /* Ensure that the view position is in a valid state. */
3286 if (!check_position(&view->prev_pos) ||
3287 (view->pipe && view->lines <= view->prev_pos.lineno))
3288 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3290 /* Changing the view position cancels the restoring. */
3291 /* FIXME: Changing back to the first line is not detected. */
3292 if (check_position(&view->pos)) {
3293 clear_position(&view->prev_pos);
3294 return FALSE;
3297 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3298 view_is_displayed(view))
3299 werase(view->win);
3301 view->pos.col = view->prev_pos.col;
3302 clear_position(&view->prev_pos);
3304 return TRUE;
3307 static void
3308 end_update(struct view *view, bool force)
3310 if (!view->pipe)
3311 return;
3312 while (!view->ops->read(view, NULL))
3313 if (!force)
3314 return;
3315 if (force)
3316 io_kill(view->pipe);
3317 io_done(view->pipe);
3318 view->pipe = NULL;
3321 static void
3322 setup_update(struct view *view, const char *vid)
3324 reset_view(view);
3325 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3326 string_ncopy(view->vid, vid, strlen(vid));
3327 view->pipe = &view->io;
3328 view->start_time = time(NULL);
3331 static bool
3332 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3334 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3335 bool extra = !!(flags & (OPEN_EXTRA));
3336 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3337 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3338 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3340 opt_stdin = FALSE;
3342 if ((!reload && !strcmp(view->vid, view->id)) ||
3343 ((flags & OPEN_REFRESH) && view->unrefreshable))
3344 return TRUE;
3346 if (view->pipe) {
3347 if (extra)
3348 io_done(view->pipe);
3349 else
3350 end_update(view, TRUE);
3353 view->unrefreshable = use_stdin;
3355 if (!refresh && argv) {
3356 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3358 view->dir = dir;
3359 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3360 report("Failed to format %s arguments", view->name);
3361 return FALSE;
3364 /* Put the current ref_* value to the view title ref
3365 * member. This is needed by the blob view. Most other
3366 * views sets it automatically after loading because the
3367 * first line is a commit line. */
3368 string_copy_rev(view->ref, view->id);
3371 if (view->argv && view->argv[0] &&
3372 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3373 report("Failed to open %s view", view->name);
3374 return FALSE;
3377 if (!extra)
3378 setup_update(view, view->id);
3380 return TRUE;
3383 static bool
3384 update_view(struct view *view)
3386 char *line;
3387 /* Clear the view and redraw everything since the tree sorting
3388 * might have rearranged things. */
3389 bool redraw = view->lines == 0;
3390 bool can_read = TRUE;
3391 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3393 if (!view->pipe)
3394 return TRUE;
3396 if (!io_can_read(view->pipe, FALSE)) {
3397 if (view->lines == 0 && view_is_displayed(view)) {
3398 time_t secs = time(NULL) - view->start_time;
3400 if (secs > 1 && secs > view->update_secs) {
3401 if (view->update_secs == 0)
3402 redraw_view(view);
3403 update_view_title(view);
3404 view->update_secs = secs;
3407 return TRUE;
3410 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3411 if (encoding) {
3412 line = encoding_convert(encoding, line);
3415 if (!view->ops->read(view, line)) {
3416 report("Allocation failure");
3417 end_update(view, TRUE);
3418 return FALSE;
3423 int digits = count_digits(view->lines);
3425 /* Keep the displayed view in sync with line number scaling. */
3426 if (digits != view->digits) {
3427 view->digits = digits;
3428 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3429 redraw = TRUE;
3433 if (io_error(view->pipe)) {
3434 report("Failed to read: %s", io_strerror(view->pipe));
3435 end_update(view, TRUE);
3437 } else if (io_eof(view->pipe)) {
3438 end_update(view, FALSE);
3441 if (restore_view_position(view))
3442 redraw = TRUE;
3444 if (!view_is_displayed(view))
3445 return TRUE;
3447 if (redraw || view->force_redraw)
3448 redraw_view_from(view, 0);
3449 else
3450 redraw_view_dirty(view);
3451 view->force_redraw = FALSE;
3453 /* Update the title _after_ the redraw so that if the redraw picks up a
3454 * commit reference in view->ref it'll be available here. */
3455 update_view_title(view);
3456 return TRUE;
3459 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3461 static struct line *
3462 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3464 struct line *line;
3466 if (!realloc_lines(&view->line, view->lines, 1))
3467 return NULL;
3469 if (data_size) {
3470 void *alloc_data = calloc(1, data_size);
3472 if (!alloc_data)
3473 return NULL;
3475 if (data)
3476 memcpy(alloc_data, data, data_size);
3477 data = alloc_data;
3480 line = &view->line[view->lines++];
3481 memset(line, 0, sizeof(*line));
3482 line->type = type;
3483 line->data = (void *) data;
3484 line->dirty = 1;
3486 if (custom)
3487 view->custom_lines++;
3488 else
3489 line->lineno = view->lines - view->custom_lines;
3491 return line;
3494 static struct line *
3495 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3497 struct line *line = add_line(view, NULL, type, data_size, custom);
3499 if (line)
3500 *ptr = line->data;
3501 return line;
3504 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3505 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3507 static struct line *
3508 add_line_nodata(struct view *view, enum line_type type)
3510 return add_line(view, NULL, type, 0, FALSE);
3513 static struct line *
3514 add_line_text(struct view *view, const char *text, enum line_type type)
3516 return add_line(view, text, type, strlen(text) + 1, FALSE);
3519 static struct line * PRINTF_LIKE(3, 4)
3520 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3522 char buf[SIZEOF_STR];
3523 int retval;
3525 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3526 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3530 * View opening
3533 static void
3534 split_view(struct view *prev, struct view *view)
3536 display[1] = view;
3537 current_view = opt_focus_child ? 1 : 0;
3538 view->parent = prev;
3539 resize_display();
3541 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3542 /* Take the title line into account. */
3543 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3545 /* Scroll the view that was split if the current line is
3546 * outside the new limited view. */
3547 do_scroll_view(prev, lines);
3550 if (view != prev && view_is_displayed(prev)) {
3551 /* "Blur" the previous view. */
3552 update_view_title(prev);
3556 static void
3557 maximize_view(struct view *view, bool redraw)
3559 memset(display, 0, sizeof(display));
3560 current_view = 0;
3561 display[current_view] = view;
3562 resize_display();
3563 if (redraw) {
3564 redraw_display(FALSE);
3565 report_clear();
3569 static void
3570 load_view(struct view *view, struct view *prev, enum open_flags flags)
3572 if (view->pipe)
3573 end_update(view, TRUE);
3574 if (view->ops->private_size) {
3575 if (!view->private)
3576 view->private = calloc(1, view->ops->private_size);
3577 else
3578 memset(view->private, 0, view->ops->private_size);
3581 /* When prev == view it means this is the first loaded view. */
3582 if (prev && view != prev) {
3583 view->prev = prev;
3586 if (!view->ops->open(view, flags))
3587 return;
3589 if (prev) {
3590 bool split = !!(flags & OPEN_SPLIT);
3592 if (split) {
3593 split_view(prev, view);
3594 } else {
3595 maximize_view(view, FALSE);
3599 restore_view_position(view);
3601 if (view->pipe && view->lines == 0) {
3602 /* Clear the old view and let the incremental updating refill
3603 * the screen. */
3604 werase(view->win);
3605 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3606 clear_position(&view->prev_pos);
3607 report_clear();
3608 } else if (view_is_displayed(view)) {
3609 redraw_view(view);
3610 report_clear();
3614 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3615 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3617 static void
3618 open_view(struct view *prev, enum request request, enum open_flags flags)
3620 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3621 struct view *view = VIEW(request);
3622 int nviews = displayed_views();
3624 assert(flags ^ OPEN_REFRESH);
3626 if (view == prev && nviews == 1 && !reload) {
3627 report("Already in %s view", view->name);
3628 return;
3631 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3632 report("The %s view is disabled in pager view", view->name);
3633 return;
3636 load_view(view, prev ? prev : view, flags);
3639 static void
3640 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3642 enum request request = view - views + REQ_OFFSET + 1;
3644 if (view->pipe)
3645 end_update(view, TRUE);
3646 view->dir = dir;
3648 if (!argv_copy(&view->argv, argv)) {
3649 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3650 } else {
3651 open_view(prev, request, flags | OPEN_PREPARED);
3655 static bool
3656 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3658 bool ok;
3660 def_prog_mode(); /* save current tty modes */
3661 endwin(); /* restore original tty modes */
3662 ok = io_run_fg(argv, dir);
3663 if (confirm) {
3664 if (!ok && *notice)
3665 fprintf(stderr, "%s", notice);
3666 fprintf(stderr, "Press Enter to continue");
3667 getc(opt_tty);
3669 reset_prog_mode();
3670 redraw_display(TRUE);
3671 return ok;
3674 static void
3675 open_mergetool(const char *file)
3677 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3679 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3682 #define EDITOR_LINENO_MSG \
3683 "*** Your editor reported an error while opening the file.\n" \
3684 "*** This is probably because it doesn't support the line\n" \
3685 "*** number argument added automatically. The line number\n" \
3686 "*** has been disabled for now. You can permanently disable\n" \
3687 "*** it by adding the following line to ~/.tigrc\n" \
3688 "*** set editor-line-number = no\n"
3690 static void
3691 open_editor(const char *file, unsigned int lineno)
3693 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3694 char editor_cmd[SIZEOF_STR];
3695 char lineno_cmd[SIZEOF_STR];
3696 const char *editor;
3697 int argc = 0;
3699 editor = getenv("GIT_EDITOR");
3700 if (!editor && *opt_editor)
3701 editor = opt_editor;
3702 if (!editor)
3703 editor = getenv("VISUAL");
3704 if (!editor)
3705 editor = getenv("EDITOR");
3706 if (!editor)
3707 editor = "vi";
3709 string_ncopy(editor_cmd, editor, strlen(editor));
3710 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3711 report("Failed to read editor command");
3712 return;
3715 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3716 editor_argv[argc++] = lineno_cmd;
3717 editor_argv[argc] = file;
3718 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3719 opt_editor_lineno = FALSE;
3722 static enum request run_prompt_command(struct view *view, char *cmd);
3724 static enum request
3725 open_run_request(struct view *view, enum request request)
3727 struct run_request *req = get_run_request(request);
3728 const char **argv = NULL;
3729 bool confirmed = FALSE;
3731 request = REQ_NONE;
3733 if (!req) {
3734 report("Unknown run request");
3735 return request;
3738 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3739 if (req->internal) {
3740 char cmd[SIZEOF_STR];
3742 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3743 request = run_prompt_command(view, cmd);
3746 else {
3747 confirmed = !req->confirm;
3749 if (req->confirm) {
3750 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3751 const char *and_exit = req->exit ? " and exit" : "";
3753 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3754 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3755 prompt_yesno(prompt)) {
3756 confirmed = TRUE;
3760 if (confirmed && argv_remove_quotes(argv)) {
3761 if (req->silent)
3762 io_run_bg(argv);
3763 else
3764 open_external_viewer(argv, NULL, !req->exit, "");
3769 if (argv)
3770 argv_free(argv);
3771 free(argv);
3773 if (request == REQ_NONE) {
3774 if (req->confirm && !confirmed)
3775 request = REQ_NONE;
3777 else if (req->exit)
3778 request = REQ_QUIT;
3780 else if (!view->unrefreshable)
3781 request = REQ_REFRESH;
3783 return request;
3787 * User request switch noodle
3790 static int
3791 view_driver(struct view *view, enum request request)
3793 int i;
3795 if (request == REQ_NONE)
3796 return TRUE;
3798 if (request > REQ_NONE) {
3799 request = open_run_request(view, request);
3801 // exit quickly rather than going through view_request and back
3802 if (request == REQ_QUIT)
3803 return FALSE;
3806 request = view_request(view, request);
3807 if (request == REQ_NONE)
3808 return TRUE;
3810 switch (request) {
3811 case REQ_MOVE_UP:
3812 case REQ_MOVE_DOWN:
3813 case REQ_MOVE_PAGE_UP:
3814 case REQ_MOVE_PAGE_DOWN:
3815 case REQ_MOVE_FIRST_LINE:
3816 case REQ_MOVE_LAST_LINE:
3817 move_view(view, request);
3818 break;
3820 case REQ_SCROLL_FIRST_COL:
3821 case REQ_SCROLL_LEFT:
3822 case REQ_SCROLL_RIGHT:
3823 case REQ_SCROLL_LINE_DOWN:
3824 case REQ_SCROLL_LINE_UP:
3825 case REQ_SCROLL_PAGE_DOWN:
3826 case REQ_SCROLL_PAGE_UP:
3827 scroll_view(view, request);
3828 break;
3830 case REQ_VIEW_MAIN:
3831 case REQ_VIEW_DIFF:
3832 case REQ_VIEW_LOG:
3833 case REQ_VIEW_TREE:
3834 case REQ_VIEW_HELP:
3835 case REQ_VIEW_BRANCH:
3836 case REQ_VIEW_BLAME:
3837 case REQ_VIEW_BLOB:
3838 case REQ_VIEW_STATUS:
3839 case REQ_VIEW_STAGE:
3840 case REQ_VIEW_PAGER:
3841 case REQ_VIEW_STASH:
3842 open_view(view, request, OPEN_DEFAULT);
3843 break;
3845 case REQ_NEXT:
3846 case REQ_PREVIOUS:
3847 if (view->parent) {
3848 int line;
3850 view = view->parent;
3851 line = view->pos.lineno;
3852 view_request(view, request);
3853 move_view(view, request);
3854 if (view_is_displayed(view))
3855 update_view_title(view);
3856 if (line != view->pos.lineno)
3857 view_request(view, REQ_ENTER);
3858 } else {
3859 move_view(view, request);
3861 break;
3863 case REQ_VIEW_NEXT:
3865 int nviews = displayed_views();
3866 int next_view = (current_view + 1) % nviews;
3868 if (next_view == current_view) {
3869 report("Only one view is displayed");
3870 break;
3873 current_view = next_view;
3874 /* Blur out the title of the previous view. */
3875 update_view_title(view);
3876 report_clear();
3877 break;
3879 case REQ_REFRESH:
3880 report("Refreshing is not yet supported for the %s view", view->name);
3881 break;
3883 case REQ_MAXIMIZE:
3884 if (displayed_views() == 2)
3885 maximize_view(view, TRUE);
3886 break;
3888 case REQ_OPTIONS:
3889 case REQ_TOGGLE_LINENO:
3890 case REQ_TOGGLE_DATE:
3891 case REQ_TOGGLE_AUTHOR:
3892 case REQ_TOGGLE_FILENAME:
3893 case REQ_TOGGLE_GRAPHIC:
3894 case REQ_TOGGLE_REV_GRAPH:
3895 case REQ_TOGGLE_REFS:
3896 case REQ_TOGGLE_CHANGES:
3897 case REQ_TOGGLE_IGNORE_SPACE:
3898 case REQ_TOGGLE_ID:
3899 case REQ_TOGGLE_FILES:
3900 case REQ_TOGGLE_TITLE_OVERFLOW:
3902 char action[SIZEOF_STR] = "";
3903 bool reload = toggle_option(view, request, action);
3905 if (reload && (view_has_flags(view, VIEW_DIFF_LIKE) || view->ops == &main_ops))
3906 reload_view(view);
3907 else
3908 redraw_display(FALSE);
3910 if (*action)
3911 report("%s", action);
3913 break;
3915 case REQ_TOGGLE_SORT_FIELD:
3916 case REQ_TOGGLE_SORT_ORDER:
3917 report("Sorting is not yet supported for the %s view", view->name);
3918 break;
3920 case REQ_DIFF_CONTEXT_UP:
3921 case REQ_DIFF_CONTEXT_DOWN:
3922 report("Changing the diff context is not yet supported for the %s view", view->name);
3923 break;
3925 case REQ_SEARCH:
3926 case REQ_SEARCH_BACK:
3927 search_view(view, request);
3928 break;
3930 case REQ_FIND_NEXT:
3931 case REQ_FIND_PREV:
3932 find_next(view, request);
3933 break;
3935 case REQ_STOP_LOADING:
3936 foreach_view(view, i) {
3937 if (view->pipe)
3938 report("Stopped loading the %s view", view->name),
3939 end_update(view, TRUE);
3941 break;
3943 case REQ_SHOW_VERSION:
3944 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3945 return TRUE;
3947 case REQ_SCREEN_REDRAW:
3948 redraw_display(TRUE);
3949 break;
3951 case REQ_EDIT:
3952 report("Nothing to edit");
3953 break;
3955 case REQ_ENTER:
3956 report("Nothing to enter");
3957 break;
3959 case REQ_VIEW_CLOSE:
3960 /* XXX: Mark closed views by letting view->prev point to the
3961 * view itself. Parents to closed view should never be
3962 * followed. */
3963 if (view->prev && view->prev != view) {
3964 maximize_view(view->prev, TRUE);
3965 view->prev = view;
3966 break;
3968 /* Fall-through */
3969 case REQ_QUIT:
3970 return FALSE;
3972 default:
3973 report("Unknown key, press %s for help",
3974 get_view_key(view, REQ_VIEW_HELP));
3975 return TRUE;
3978 return TRUE;
3983 * View backend utilities
3986 enum sort_field {
3987 ORDERBY_NAME,
3988 ORDERBY_DATE,
3989 ORDERBY_AUTHOR,
3992 struct sort_state {
3993 const enum sort_field *fields;
3994 size_t size, current;
3995 bool reverse;
3998 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3999 #define get_sort_field(state) ((state).fields[(state).current])
4000 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
4002 static void
4003 sort_view(struct view *view, enum request request, struct sort_state *state,
4004 int (*compare)(const void *, const void *))
4006 switch (request) {
4007 case REQ_TOGGLE_SORT_FIELD:
4008 state->current = (state->current + 1) % state->size;
4009 break;
4011 case REQ_TOGGLE_SORT_ORDER:
4012 state->reverse = !state->reverse;
4013 break;
4014 default:
4015 die("Not a sort request");
4018 qsort(view->line, view->lines, sizeof(*view->line), compare);
4019 redraw_view(view);
4022 static bool
4023 update_diff_context(enum request request)
4025 int diff_context = opt_diff_context;
4027 switch (request) {
4028 case REQ_DIFF_CONTEXT_UP:
4029 opt_diff_context += 1;
4030 update_diff_context_arg(opt_diff_context);
4031 break;
4033 case REQ_DIFF_CONTEXT_DOWN:
4034 if (opt_diff_context == 0) {
4035 report("Diff context cannot be less than zero");
4036 break;
4038 opt_diff_context -= 1;
4039 update_diff_context_arg(opt_diff_context);
4040 break;
4042 default:
4043 die("Not a diff context request");
4046 return diff_context != opt_diff_context;
4049 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4051 /* Small author cache to reduce memory consumption. It uses binary
4052 * search to lookup or find place to position new entries. No entries
4053 * are ever freed. */
4054 static struct ident *
4055 get_author(const char *name, const char *email)
4057 static struct ident **authors;
4058 static size_t authors_size;
4059 int from = 0, to = authors_size - 1;
4060 struct ident *ident;
4062 while (from <= to) {
4063 size_t pos = (to + from) / 2;
4064 int cmp = strcmp(name, authors[pos]->name);
4066 if (!cmp)
4067 return authors[pos];
4069 if (cmp < 0)
4070 to = pos - 1;
4071 else
4072 from = pos + 1;
4075 if (!realloc_authors(&authors, authors_size, 1))
4076 return NULL;
4077 ident = calloc(1, sizeof(*ident));
4078 if (!ident)
4079 return NULL;
4080 ident->name = strdup(name);
4081 ident->email = strdup(email);
4082 if (!ident->name || !ident->email) {
4083 free((void *) ident->name);
4084 free(ident);
4085 return NULL;
4088 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4089 authors[from] = ident;
4090 authors_size++;
4092 return ident;
4095 static void
4096 parse_timesec(struct time *time, const char *sec)
4098 time->sec = (time_t) atol(sec);
4101 static void
4102 parse_timezone(struct time *time, const char *zone)
4104 long tz;
4106 tz = ('0' - zone[1]) * 60 * 60 * 10;
4107 tz += ('0' - zone[2]) * 60 * 60;
4108 tz += ('0' - zone[3]) * 60 * 10;
4109 tz += ('0' - zone[4]) * 60;
4111 if (zone[0] == '-')
4112 tz = -tz;
4114 time->tz = tz;
4115 time->sec -= tz;
4118 /* Parse author lines where the name may be empty:
4119 * author <email@address.tld> 1138474660 +0100
4121 static void
4122 parse_author_line(char *ident, const struct ident **author, struct time *time)
4124 char *nameend = strchr(ident, '<');
4125 char *emailend = strchr(ident, '>');
4126 const char *name, *email = "";
4128 if (nameend && emailend)
4129 *nameend = *emailend = 0;
4130 name = chomp_string(ident);
4131 if (nameend)
4132 email = chomp_string(nameend + 1);
4133 if (!*name)
4134 name = *email ? email : unknown_ident.name;
4135 if (!*email)
4136 email = *name ? name : unknown_ident.email;
4138 *author = get_author(name, email);
4140 /* Parse epoch and timezone */
4141 if (time && emailend && emailend[1] == ' ') {
4142 char *secs = emailend + 2;
4143 char *zone = strchr(secs, ' ');
4145 parse_timesec(time, secs);
4147 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4148 parse_timezone(time, zone + 1);
4152 static struct line *
4153 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4155 for (; view_has_line(view, line); line += direction)
4156 if (line->type == type)
4157 return line;
4159 return NULL;
4162 #define find_prev_line_by_type(view, line, type) \
4163 find_line_by_type(view, line, type, -1)
4165 #define find_next_line_by_type(view, line, type) \
4166 find_line_by_type(view, line, type, 1)
4169 * Blame
4172 struct blame_commit {
4173 char id[SIZEOF_REV]; /* SHA1 ID. */
4174 char title[128]; /* First line of the commit message. */
4175 const struct ident *author; /* Author of the commit. */
4176 struct time time; /* Date from the author ident. */
4177 char filename[128]; /* Name of file. */
4178 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4179 char parent_filename[128]; /* Parent/previous name of file. */
4182 struct blame_header {
4183 char id[SIZEOF_REV]; /* SHA1 ID. */
4184 size_t orig_lineno;
4185 size_t lineno;
4186 size_t group;
4189 static bool
4190 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4192 const char *pos = *posref;
4194 *posref = NULL;
4195 pos = strchr(pos + 1, ' ');
4196 if (!pos || !isdigit(pos[1]))
4197 return FALSE;
4198 *number = atoi(pos + 1);
4199 if (*number < min || *number > max)
4200 return FALSE;
4202 *posref = pos;
4203 return TRUE;
4206 static bool
4207 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4209 const char *pos = text + SIZEOF_REV - 2;
4211 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4212 return FALSE;
4214 string_ncopy(header->id, text, SIZEOF_REV);
4216 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4217 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4218 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4219 return FALSE;
4221 return TRUE;
4224 static bool
4225 match_blame_header(const char *name, char **line)
4227 size_t namelen = strlen(name);
4228 bool matched = !strncmp(name, *line, namelen);
4230 if (matched)
4231 *line += namelen;
4233 return matched;
4236 static bool
4237 parse_blame_info(struct blame_commit *commit, char *line)
4239 if (match_blame_header("author ", &line)) {
4240 parse_author_line(line, &commit->author, NULL);
4242 } else if (match_blame_header("author-time ", &line)) {
4243 parse_timesec(&commit->time, line);
4245 } else if (match_blame_header("author-tz ", &line)) {
4246 parse_timezone(&commit->time, line);
4248 } else if (match_blame_header("summary ", &line)) {
4249 string_ncopy(commit->title, line, strlen(line));
4251 } else if (match_blame_header("previous ", &line)) {
4252 if (strlen(line) <= SIZEOF_REV)
4253 return FALSE;
4254 string_copy_rev(commit->parent_id, line);
4255 line += SIZEOF_REV;
4256 string_ncopy(commit->parent_filename, line, strlen(line));
4258 } else if (match_blame_header("filename ", &line)) {
4259 string_ncopy(commit->filename, line, strlen(line));
4260 return TRUE;
4263 return FALSE;
4267 * Pager backend
4270 static bool
4271 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4273 if (draw_lineno(view, lineno))
4274 return TRUE;
4276 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4277 return TRUE;
4279 draw_text(view, line->type, line->data);
4280 return TRUE;
4283 static bool
4284 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4286 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4287 char ref[SIZEOF_STR];
4289 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4290 return TRUE;
4292 /* This is the only fatal call, since it can "corrupt" the buffer. */
4293 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4294 return FALSE;
4296 return TRUE;
4299 static void
4300 add_pager_refs(struct view *view, const char *commit_id)
4302 char buf[SIZEOF_STR];
4303 struct ref_list *list;
4304 size_t bufpos = 0, i;
4305 const char *sep = "Refs: ";
4306 bool is_tag = FALSE;
4308 list = get_ref_list(commit_id);
4309 if (!list) {
4310 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4311 goto try_add_describe_ref;
4312 return;
4315 for (i = 0; i < list->size; i++) {
4316 struct ref *ref = list->refs[i];
4317 const char *fmt = ref->tag ? "%s[%s]" :
4318 ref->remote ? "%s<%s>" : "%s%s";
4320 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4321 return;
4322 sep = ", ";
4323 if (ref->tag)
4324 is_tag = TRUE;
4327 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4328 try_add_describe_ref:
4329 /* Add <tag>-g<commit_id> "fake" reference. */
4330 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4331 return;
4334 if (bufpos == 0)
4335 return;
4337 add_line_text(view, buf, LINE_PP_REFS);
4340 static struct line *
4341 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4343 size_t first_line = 0;
4344 bool has_first_line = FALSE;
4345 size_t datalen = strlen(data);
4346 size_t lineno = 0;
4348 while (datalen > 0 || !has_first_line) {
4349 bool wrapped = !!first_line;
4350 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4351 struct line *line;
4352 char *text;
4354 line = add_line(view, NULL, type, linelen + 1, wrapped);
4355 if (!line)
4356 break;
4357 if (!has_first_line) {
4358 first_line = view->lines - 1;
4359 has_first_line = TRUE;
4362 if (!wrapped)
4363 lineno = line->lineno;
4365 line->wrapped = wrapped;
4366 line->lineno = lineno;
4367 text = line->data;
4368 if (linelen)
4369 strncpy(text, data, linelen);
4370 text[linelen] = 0;
4372 datalen -= linelen;
4373 data += linelen;
4376 return has_first_line ? &view->line[first_line] : NULL;
4379 static bool
4380 pager_common_read(struct view *view, const char *data, enum line_type type)
4382 struct line *line;
4384 if (!data)
4385 return TRUE;
4387 if (opt_wrap_lines) {
4388 line = pager_wrap_line(view, data, type);
4389 } else {
4390 line = add_line_text(view, data, type);
4393 if (!line)
4394 return FALSE;
4396 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4397 add_pager_refs(view, data + STRING_SIZE("commit "));
4399 return TRUE;
4402 static bool
4403 pager_read(struct view *view, char *data)
4405 if (!data)
4406 return TRUE;
4408 return pager_common_read(view, data, get_line_type(data));
4411 static enum request
4412 pager_request(struct view *view, enum request request, struct line *line)
4414 int split = 0;
4416 if (request != REQ_ENTER)
4417 return request;
4419 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4420 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4421 split = 1;
4424 /* Always scroll the view even if it was split. That way
4425 * you can use Enter to scroll through the log view and
4426 * split open each commit diff. */
4427 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4429 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4430 * but if we are scrolling a non-current view this won't properly
4431 * update the view title. */
4432 if (split)
4433 update_view_title(view);
4435 return REQ_NONE;
4438 static bool
4439 pager_grep(struct view *view, struct line *line)
4441 const char *text[] = { line->data, NULL };
4443 return grep_text(view, text);
4446 static void
4447 pager_select(struct view *view, struct line *line)
4449 if (line->type == LINE_COMMIT) {
4450 string_copy_rev_from_commit_line(ref_commit, line->data);
4451 if (!view_has_flags(view, VIEW_NO_REF))
4452 string_copy_rev(view->ref, ref_commit);
4456 struct log_state {
4457 /* Used for tracking when we need to recalculate the previous
4458 * commit, for example when the user scrolls up or uses the page
4459 * up/down in the log view. */
4460 int last_lineno;
4461 enum line_type last_type;
4464 static void
4465 log_select(struct view *view, struct line *line)
4467 struct log_state *state = view->private;
4468 int last_lineno = state->last_lineno;
4470 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4471 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4472 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4474 if (commit_line)
4475 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4478 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4479 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4481 string_copy_rev(ref_commit, view->ref);
4482 state->last_lineno = line->lineno;
4483 state->last_type = line->type;
4486 static bool
4487 pager_open(struct view *view, enum open_flags flags)
4489 if (display[0] == NULL) {
4490 if (!io_open(&view->io, "%s", ""))
4491 die("Failed to open stdin");
4492 flags = OPEN_PREPARED;
4494 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4495 report("No pager content, press %s to run command from prompt",
4496 get_view_key(view, REQ_PROMPT));
4497 return FALSE;
4500 return begin_update(view, NULL, NULL, flags);
4503 static struct view_ops pager_ops = {
4504 "line",
4505 { "pager" },
4506 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4508 pager_open,
4509 pager_read,
4510 pager_draw,
4511 pager_request,
4512 pager_grep,
4513 pager_select,
4516 static bool
4517 log_open(struct view *view, enum open_flags flags)
4519 static const char *log_argv[] = {
4520 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4523 return begin_update(view, NULL, log_argv, flags);
4526 static enum request
4527 log_request(struct view *view, enum request request, struct line *line)
4529 switch (request) {
4530 case REQ_REFRESH:
4531 load_refs();
4532 refresh_view(view);
4533 return REQ_NONE;
4535 case REQ_ENTER:
4536 if (!display[1] || strcmp(display[1]->vid, view->ref))
4537 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4538 return REQ_NONE;
4540 default:
4541 return request;
4545 static struct view_ops log_ops = {
4546 "line",
4547 { "log" },
4548 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER,
4549 sizeof(struct log_state),
4550 log_open,
4551 pager_read,
4552 pager_draw,
4553 log_request,
4554 pager_grep,
4555 log_select,
4558 struct diff_state {
4559 bool after_commit_title;
4560 bool after_diff;
4561 bool reading_diff_stat;
4562 bool combined_diff;
4565 #define DIFF_LINE_COMMIT_TITLE 1
4567 static bool
4568 diff_open(struct view *view, enum open_flags flags)
4570 static const char *diff_argv[] = {
4571 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4572 "--patch-with-stat",
4573 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4574 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4577 return begin_update(view, NULL, diff_argv, flags);
4580 static bool
4581 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4583 enum line_type type = get_line_type(data);
4585 if (!view->lines && type != LINE_COMMIT)
4586 state->reading_diff_stat = TRUE;
4588 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4589 state->reading_diff_stat = TRUE;
4591 if (state->reading_diff_stat) {
4592 size_t len = strlen(data);
4593 char *pipe = strchr(data, '|');
4594 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4595 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4596 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4598 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4599 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4600 } else {
4601 state->reading_diff_stat = FALSE;
4604 } else if (!strcmp(data, "---")) {
4605 state->reading_diff_stat = TRUE;
4608 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4609 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4611 if (line)
4612 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4613 state->after_commit_title = TRUE;
4614 return line != NULL;
4617 if (type == LINE_DIFF_HEADER) {
4618 const int len = line_info[LINE_DIFF_HEADER].linelen;
4620 state->after_diff = TRUE;
4621 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4622 !strncmp(data + len, "cc ", strlen("cc ")))
4623 state->combined_diff = TRUE;
4625 } else if (type == LINE_PP_MERGE) {
4626 state->combined_diff = TRUE;
4629 /* ADD2 and DEL2 are only valid in combined diff hunks */
4630 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4631 type = LINE_DEFAULT;
4633 return pager_common_read(view, data, type);
4636 static bool
4637 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4639 struct line *marker = find_next_line_by_type(view, line, type);
4641 return marker &&
4642 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4645 static enum request
4646 diff_common_enter(struct view *view, enum request request, struct line *line)
4648 if (line->type == LINE_DIFF_STAT) {
4649 int file_number = 0;
4651 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4652 file_number++;
4653 line--;
4656 for (line = view->line; view_has_line(view, line); line++) {
4657 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4658 if (!line)
4659 break;
4661 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4662 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4663 if (file_number == 1) {
4664 break;
4666 file_number--;
4670 if (!line) {
4671 report("Failed to find file diff");
4672 return REQ_NONE;
4675 select_view_line(view, line - view->line);
4676 report_clear();
4677 return REQ_NONE;
4679 } else {
4680 return pager_request(view, request, line);
4684 static bool
4685 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4687 char *sep = strchr(*text, c);
4689 if (sep != NULL) {
4690 *sep = 0;
4691 draw_text(view, *type, *text);
4692 *sep = c;
4693 *text = sep;
4694 *type = next_type;
4697 return sep != NULL;
4700 static bool
4701 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4703 char *text = line->data;
4704 enum line_type type = line->type;
4706 if (draw_lineno(view, lineno))
4707 return TRUE;
4709 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4710 return TRUE;
4712 if (type == LINE_DIFF_STAT) {
4713 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4714 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4715 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4716 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4717 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4718 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4719 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4721 } else {
4722 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4723 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4727 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4728 draw_commit_title(view, text, 4);
4729 else
4730 draw_text(view, type, text);
4731 return TRUE;
4734 static bool
4735 diff_read(struct view *view, char *data)
4737 struct diff_state *state = view->private;
4739 if (!data) {
4740 /* Fall back to retry if no diff will be shown. */
4741 if (view->lines == 0 && opt_file_argv) {
4742 int pos = argv_size(view->argv)
4743 - argv_size(opt_file_argv) - 1;
4745 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4746 for (; view->argv[pos]; pos++) {
4747 free((void *) view->argv[pos]);
4748 view->argv[pos] = NULL;
4751 if (view->pipe)
4752 io_done(view->pipe);
4753 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4754 return FALSE;
4757 return TRUE;
4760 return diff_common_read(view, data, state);
4763 static bool
4764 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4765 struct blame_header *header, struct blame_commit *commit)
4767 char line_arg[SIZEOF_STR];
4768 const char *blame_argv[] = {
4769 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4771 struct io io;
4772 bool ok = FALSE;
4773 char *buf;
4775 if (!string_format(line_arg, "-L%ld,+1", lineno))
4776 return FALSE;
4778 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4779 return FALSE;
4781 while ((buf = io_get(&io, '\n', TRUE))) {
4782 if (header) {
4783 if (!parse_blame_header(header, buf, 9999999))
4784 break;
4785 header = NULL;
4787 } else if (parse_blame_info(commit, buf)) {
4788 ok = TRUE;
4789 break;
4793 if (io_error(&io))
4794 ok = FALSE;
4796 io_done(&io);
4797 return ok;
4800 static unsigned int
4801 diff_get_lineno(struct view *view, struct line *line)
4803 const struct line *header, *chunk;
4804 const char *data;
4805 unsigned int lineno;
4807 /* Verify that we are after a diff header and one of its chunks */
4808 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4809 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4810 if (!header || !chunk || chunk < header)
4811 return 0;
4814 * In a chunk header, the number after the '+' sign is the number of its
4815 * following line, in the new version of the file. We increment this
4816 * number for each non-deletion line, until the given line position.
4818 data = strchr(chunk->data, '+');
4819 if (!data)
4820 return 0;
4822 lineno = atoi(data);
4823 chunk++;
4824 while (chunk++ < line)
4825 if (chunk->type != LINE_DIFF_DEL)
4826 lineno++;
4828 return lineno;
4831 static bool
4832 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4834 return prefixcmp(chunk, "@@ -") ||
4835 !(chunk = strchr(chunk, marker)) ||
4836 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4839 static enum request
4840 diff_trace_origin(struct view *view, struct line *line)
4842 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4843 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4844 const char *chunk_data;
4845 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4846 int lineno = 0;
4847 const char *file = NULL;
4848 char ref[SIZEOF_REF];
4849 struct blame_header header;
4850 struct blame_commit commit;
4852 if (!diff || !chunk || chunk == line) {
4853 report("The line to trace must be inside a diff chunk");
4854 return REQ_NONE;
4857 for (; diff < line && !file; diff++) {
4858 const char *data = diff->data;
4860 if (!prefixcmp(data, "--- a/")) {
4861 file = data + STRING_SIZE("--- a/");
4862 break;
4866 if (diff == line || !file) {
4867 report("Failed to read the file name");
4868 return REQ_NONE;
4871 chunk_data = chunk->data;
4873 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4874 report("Failed to read the line number");
4875 return REQ_NONE;
4878 if (lineno == 0) {
4879 report("This is the origin of the line");
4880 return REQ_NONE;
4883 for (chunk += 1; chunk < line; chunk++) {
4884 if (chunk->type == LINE_DIFF_ADD) {
4885 lineno += chunk_marker == '+';
4886 } else if (chunk->type == LINE_DIFF_DEL) {
4887 lineno += chunk_marker == '-';
4888 } else {
4889 lineno++;
4893 if (chunk_marker == '+')
4894 string_copy(ref, view->vid);
4895 else
4896 string_format(ref, "%s^", view->vid);
4898 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4899 report("Failed to read blame data");
4900 return REQ_NONE;
4903 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4904 string_copy(opt_ref, header.id);
4905 opt_goto_line = header.orig_lineno - 1;
4907 return REQ_VIEW_BLAME;
4910 static const char *
4911 diff_get_pathname(struct view *view, struct line *line)
4913 const struct line *header;
4914 const char *dst = NULL;
4915 const char *prefixes[] = { " b/", "cc ", "combined " };
4916 int i;
4918 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4919 if (!header)
4920 return NULL;
4922 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4923 dst = strstr(header->data, prefixes[i]);
4925 return dst ? dst + strlen(prefixes[--i]) : NULL;
4928 static enum request
4929 diff_common_edit(struct view *view, enum request request, struct line *line)
4931 const char *file = diff_get_pathname(view, line);
4932 char path[SIZEOF_STR];
4933 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
4935 if (has_path && access(path, R_OK)) {
4936 report("Failed to open file: %s", file);
4937 return REQ_NONE;
4940 open_editor(file, diff_get_lineno(view, line));
4941 return REQ_NONE;
4944 static enum request
4945 diff_request(struct view *view, enum request request, struct line *line)
4947 switch (request) {
4948 case REQ_VIEW_BLAME:
4949 return diff_trace_origin(view, line);
4951 case REQ_DIFF_CONTEXT_UP:
4952 case REQ_DIFF_CONTEXT_DOWN:
4953 if (!update_diff_context(request))
4954 return REQ_NONE;
4955 reload_view(view);
4956 return REQ_NONE;
4959 case REQ_EDIT:
4960 return diff_common_edit(view, request, line);
4962 case REQ_ENTER:
4963 return diff_common_enter(view, request, line);
4965 case REQ_REFRESH:
4966 reload_view(view);
4967 return REQ_NONE;
4969 default:
4970 return pager_request(view, request, line);
4974 static void
4975 diff_select(struct view *view, struct line *line)
4977 if (line->type == LINE_DIFF_STAT) {
4978 string_format(view->ref, "Press '%s' to jump to file diff",
4979 get_view_key(view, REQ_ENTER));
4980 } else {
4981 const char *file = diff_get_pathname(view, line);
4983 if (file) {
4984 string_format(view->ref, "Changes to '%s'", file);
4985 string_format(opt_file, "%s", file);
4986 ref_blob[0] = 0;
4987 } else {
4988 string_ncopy(view->ref, view->id, strlen(view->id));
4989 pager_select(view, line);
4994 static struct view_ops diff_ops = {
4995 "line",
4996 { "diff" },
4997 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN | VIEW_FILE_FILTER,
4998 sizeof(struct diff_state),
4999 diff_open,
5000 diff_read,
5001 diff_common_draw,
5002 diff_request,
5003 pager_grep,
5004 diff_select,
5008 * Help backend
5011 static bool
5012 help_draw(struct view *view, struct line *line, unsigned int lineno)
5014 if (line->type == LINE_HELP_KEYMAP) {
5015 struct keymap *keymap = line->data;
5017 draw_formatted(view, line->type, "[%c] %s bindings",
5018 keymap->hidden ? '+' : '-', keymap->name);
5019 return TRUE;
5020 } else {
5021 return pager_draw(view, line, lineno);
5025 static bool
5026 help_open_keymap_title(struct view *view, struct keymap *keymap)
5028 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5029 return keymap->hidden;
5032 static void
5033 help_open_keymap(struct view *view, struct keymap *keymap)
5035 const char *group = NULL;
5036 char buf[SIZEOF_STR];
5037 bool add_title = TRUE;
5038 int i;
5040 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5041 const char *key = NULL;
5043 if (req_info[i].request == REQ_NONE)
5044 continue;
5046 if (!req_info[i].request) {
5047 group = req_info[i].help;
5048 continue;
5051 key = get_keys(keymap, req_info[i].request, TRUE);
5052 if (!key || !*key)
5053 continue;
5055 if (add_title && help_open_keymap_title(view, keymap))
5056 return;
5057 add_title = FALSE;
5059 if (group) {
5060 add_line_text(view, group, LINE_HELP_GROUP);
5061 group = NULL;
5064 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5065 enum_name(req_info[i]), req_info[i].help);
5068 group = "External commands:";
5070 for (i = 0; i < run_requests; i++) {
5071 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5072 const char *key;
5074 if (!req || req->keymap != keymap)
5075 continue;
5077 key = get_key_name(req->key);
5078 if (!*key)
5079 key = "(no key defined)";
5081 if (add_title && help_open_keymap_title(view, keymap))
5082 return;
5083 add_title = FALSE;
5085 if (group) {
5086 add_line_text(view, group, LINE_HELP_GROUP);
5087 group = NULL;
5090 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5091 return;
5093 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5097 static bool
5098 help_open(struct view *view, enum open_flags flags)
5100 struct keymap *keymap;
5102 reset_view(view);
5103 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5104 add_line_text(view, "", LINE_DEFAULT);
5106 for (keymap = keymaps; keymap; keymap = keymap->next)
5107 help_open_keymap(view, keymap);
5109 return TRUE;
5112 static enum request
5113 help_request(struct view *view, enum request request, struct line *line)
5115 switch (request) {
5116 case REQ_ENTER:
5117 if (line->type == LINE_HELP_KEYMAP) {
5118 struct keymap *keymap = line->data;
5120 keymap->hidden = !keymap->hidden;
5121 refresh_view(view);
5124 return REQ_NONE;
5125 default:
5126 return pager_request(view, request, line);
5130 static void
5131 help_done(struct view *view)
5133 int i;
5135 for (i = 0; i < view->lines; i++)
5136 if (view->line[i].type == LINE_HELP_KEYMAP)
5137 view->line[i].data = NULL;
5140 static struct view_ops help_ops = {
5141 "line",
5142 { "help" },
5143 VIEW_NO_GIT_DIR,
5145 help_open,
5146 NULL,
5147 help_draw,
5148 help_request,
5149 pager_grep,
5150 pager_select,
5151 help_done,
5156 * Tree backend
5159 struct tree_stack_entry {
5160 struct tree_stack_entry *prev; /* Entry below this in the stack */
5161 unsigned long lineno; /* Line number to restore */
5162 char *name; /* Position of name in opt_path */
5165 /* The top of the path stack. */
5166 static struct tree_stack_entry *tree_stack = NULL;
5167 unsigned long tree_lineno = 0;
5169 static void
5170 pop_tree_stack_entry(void)
5172 struct tree_stack_entry *entry = tree_stack;
5174 tree_lineno = entry->lineno;
5175 entry->name[0] = 0;
5176 tree_stack = entry->prev;
5177 free(entry);
5180 static void
5181 push_tree_stack_entry(const char *name, unsigned long lineno)
5183 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
5184 size_t pathlen = strlen(opt_path);
5186 if (!entry)
5187 return;
5189 entry->prev = tree_stack;
5190 entry->name = opt_path + pathlen;
5191 tree_stack = entry;
5193 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5194 pop_tree_stack_entry();
5195 return;
5198 /* Move the current line to the first tree entry. */
5199 tree_lineno = 1;
5200 entry->lineno = lineno;
5203 /* Parse output from git-ls-tree(1):
5205 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5208 #define SIZEOF_TREE_ATTR \
5209 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5211 #define SIZEOF_TREE_MODE \
5212 STRING_SIZE("100644 ")
5214 #define TREE_ID_OFFSET \
5215 STRING_SIZE("100644 blob ")
5217 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5219 struct tree_entry {
5220 char id[SIZEOF_REV];
5221 char commit[SIZEOF_REV];
5222 mode_t mode;
5223 struct time time; /* Date from the author ident. */
5224 const struct ident *author; /* Author of the commit. */
5225 unsigned long size;
5226 char name[1];
5229 struct tree_state {
5230 char commit[SIZEOF_REV];
5231 const struct ident *author;
5232 struct time author_time;
5233 int size_width;
5234 bool read_date;
5237 static const char *
5238 tree_path(const struct line *line)
5240 return ((struct tree_entry *) line->data)->name;
5243 static int
5244 tree_compare_entry(const struct line *line1, const struct line *line2)
5246 if (line1->type != line2->type)
5247 return line1->type == LINE_TREE_DIR ? -1 : 1;
5248 return strcmp(tree_path(line1), tree_path(line2));
5251 static const enum sort_field tree_sort_fields[] = {
5252 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5254 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5256 static int
5257 tree_compare(const void *l1, const void *l2)
5259 const struct line *line1 = (const struct line *) l1;
5260 const struct line *line2 = (const struct line *) l2;
5261 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5262 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5264 if (line1->type == LINE_TREE_HEAD)
5265 return -1;
5266 if (line2->type == LINE_TREE_HEAD)
5267 return 1;
5269 switch (get_sort_field(tree_sort_state)) {
5270 case ORDERBY_DATE:
5271 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5273 case ORDERBY_AUTHOR:
5274 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5276 case ORDERBY_NAME:
5277 default:
5278 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5283 static struct line *
5284 tree_entry(struct view *view, enum line_type type, const char *path,
5285 const char *mode, const char *id, unsigned long size)
5287 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5288 struct tree_entry *entry;
5289 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5291 if (!line)
5292 return NULL;
5294 strncpy(entry->name, path, strlen(path));
5295 if (mode)
5296 entry->mode = strtoul(mode, NULL, 8);
5297 if (id)
5298 string_copy_rev(entry->id, id);
5299 entry->size = size;
5301 return line;
5304 static bool
5305 tree_read_date(struct view *view, char *text, struct tree_state *state)
5307 if (!text && state->read_date) {
5308 state->read_date = FALSE;
5309 return TRUE;
5311 } else if (!text) {
5312 /* Find next entry to process */
5313 const char *log_file[] = {
5314 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
5315 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5318 if (!view->lines) {
5319 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5320 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5321 report("Tree is empty");
5322 return TRUE;
5325 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5326 report("Failed to load tree data");
5327 return TRUE;
5330 state->read_date = TRUE;
5331 return FALSE;
5333 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5334 string_copy_rev_from_commit_line(state->commit, text);
5336 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5337 parse_author_line(text + STRING_SIZE("author "),
5338 &state->author, &state->author_time);
5340 } else if (*text == ':') {
5341 char *pos;
5342 size_t annotated = 1;
5343 size_t i;
5345 pos = strchr(text, '\t');
5346 if (!pos)
5347 return TRUE;
5348 text = pos + 1;
5349 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5350 text += strlen(opt_path);
5351 pos = strchr(text, '/');
5352 if (pos)
5353 *pos = 0;
5355 for (i = 1; i < view->lines; i++) {
5356 struct line *line = &view->line[i];
5357 struct tree_entry *entry = line->data;
5359 annotated += !!entry->author;
5360 if (entry->author || strcmp(entry->name, text))
5361 continue;
5363 string_copy_rev(entry->commit, state->commit);
5364 entry->author = state->author;
5365 entry->time = state->author_time;
5366 line->dirty = 1;
5367 break;
5370 if (annotated == view->lines)
5371 io_kill(view->pipe);
5373 return TRUE;
5376 static inline size_t
5377 parse_size(const char *text, int *max_digits)
5379 size_t size = 0;
5380 int digits = 0;
5382 while (*text == ' ')
5383 text++;
5385 while (isdigit(*text)) {
5386 size = (size * 10) + (*text++ - '0');
5387 digits++;
5390 if (digits > *max_digits)
5391 *max_digits = digits;
5393 return size;
5396 static bool
5397 tree_read(struct view *view, char *text)
5399 struct tree_state *state = view->private;
5400 struct tree_entry *data;
5401 struct line *entry, *line;
5402 enum line_type type;
5403 size_t textlen = text ? strlen(text) : 0;
5404 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5405 char *path;
5406 size_t size;
5408 if (state->read_date || !text)
5409 return tree_read_date(view, text, state);
5411 if (textlen <= SIZEOF_TREE_ATTR)
5412 return FALSE;
5413 if (view->lines == 0 &&
5414 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5415 return FALSE;
5417 size = parse_size(attr_offset, &state->size_width);
5418 path = strchr(attr_offset, '\t');
5419 if (!path)
5420 return FALSE;
5421 path++;
5423 /* Strip the path part ... */
5424 if (*opt_path) {
5425 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5426 size_t striplen = strlen(opt_path);
5428 if (pathlen > striplen)
5429 memmove(path, path + striplen,
5430 pathlen - striplen + 1);
5432 /* Insert "link" to parent directory. */
5433 if (view->lines == 1 &&
5434 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5435 return FALSE;
5438 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5439 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5440 if (!entry)
5441 return FALSE;
5442 data = entry->data;
5444 /* Skip "Directory ..." and ".." line. */
5445 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5446 if (tree_compare_entry(line, entry) <= 0)
5447 continue;
5449 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5451 line->data = data;
5452 line->type = type;
5453 for (; line <= entry; line++)
5454 line->dirty = line->cleareol = 1;
5455 return TRUE;
5458 if (tree_lineno <= view->pos.lineno)
5459 tree_lineno = view->custom_lines;
5461 if (tree_lineno > view->pos.lineno) {
5462 view->pos.lineno = tree_lineno;
5463 tree_lineno = 0;
5466 return TRUE;
5469 static bool
5470 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5472 struct tree_state *state = view->private;
5473 struct tree_entry *entry = line->data;
5475 if (line->type == LINE_TREE_HEAD) {
5476 if (draw_text(view, line->type, "Directory path /"))
5477 return TRUE;
5478 } else {
5479 if (draw_mode(view, entry->mode))
5480 return TRUE;
5482 if (draw_author(view, entry->author))
5483 return TRUE;
5485 if (draw_file_size(view, entry->size, state->size_width,
5486 line->type != LINE_TREE_FILE))
5487 return TRUE;
5489 if (draw_date(view, &entry->time))
5490 return TRUE;
5492 if (draw_id(view, entry->commit))
5493 return TRUE;
5496 draw_text(view, line->type, entry->name);
5497 return TRUE;
5500 static void
5501 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5503 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5504 char file[SIZEOF_STR];
5505 int fd;
5507 if (!name)
5508 name = "unknown";
5510 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5511 report("Temporary file name is too long");
5512 return;
5515 fd = mkstemps(file, strlen(name) + 1);
5517 if (fd == -1)
5518 report("Failed to create temporary file");
5519 else if (!io_run_append(blob_argv, fd))
5520 report("Failed to save blob data to file");
5521 else
5522 open_editor(file, lineno);
5523 if (fd != -1)
5524 unlink(file);
5527 static enum request
5528 tree_request(struct view *view, enum request request, struct line *line)
5530 enum open_flags flags;
5531 struct tree_entry *entry = line->data;
5533 switch (request) {
5534 case REQ_VIEW_BLAME:
5535 if (line->type != LINE_TREE_FILE) {
5536 report("Blame only supported for files");
5537 return REQ_NONE;
5540 string_copy(opt_ref, view->vid);
5541 return request;
5543 case REQ_EDIT:
5544 if (line->type != LINE_TREE_FILE) {
5545 report("Edit only supported for files");
5546 } else if (!is_head_commit(view->vid)) {
5547 open_blob_editor(entry->id, entry->name, 0);
5548 } else {
5549 open_editor(opt_file, 0);
5551 return REQ_NONE;
5553 case REQ_TOGGLE_SORT_FIELD:
5554 case REQ_TOGGLE_SORT_ORDER:
5555 sort_view(view, request, &tree_sort_state, tree_compare);
5556 return REQ_NONE;
5558 case REQ_PARENT:
5559 if (!*opt_path) {
5560 /* quit view if at top of tree */
5561 return REQ_VIEW_CLOSE;
5563 /* fake 'cd ..' */
5564 line = &view->line[1];
5565 break;
5567 case REQ_ENTER:
5568 break;
5570 default:
5571 return request;
5574 /* Cleanup the stack if the tree view is at a different tree. */
5575 while (!*opt_path && tree_stack)
5576 pop_tree_stack_entry();
5578 switch (line->type) {
5579 case LINE_TREE_DIR:
5580 /* Depending on whether it is a subdirectory or parent link
5581 * mangle the path buffer. */
5582 if (line == &view->line[1] && *opt_path) {
5583 pop_tree_stack_entry();
5585 } else {
5586 const char *basename = tree_path(line);
5588 push_tree_stack_entry(basename, view->pos.lineno);
5591 /* Trees and subtrees share the same ID, so they are not not
5592 * unique like blobs. */
5593 flags = OPEN_RELOAD;
5594 request = REQ_VIEW_TREE;
5595 break;
5597 case LINE_TREE_FILE:
5598 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5599 request = REQ_VIEW_BLOB;
5600 break;
5602 default:
5603 return REQ_NONE;
5606 open_view(view, request, flags);
5607 if (request == REQ_VIEW_TREE)
5608 view->pos.lineno = tree_lineno;
5610 return REQ_NONE;
5613 static bool
5614 tree_grep(struct view *view, struct line *line)
5616 struct tree_entry *entry = line->data;
5617 const char *text[] = {
5618 entry->name,
5619 mkauthor(entry->author, opt_author_width, opt_author),
5620 mkdate(&entry->time, opt_date),
5621 NULL
5624 return grep_text(view, text);
5627 static void
5628 tree_select(struct view *view, struct line *line)
5630 struct tree_entry *entry = line->data;
5632 if (line->type == LINE_TREE_HEAD) {
5633 string_format(view->ref, "Files in /%s", opt_path);
5634 return;
5637 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5638 string_copy(view->ref, "Open parent directory");
5639 ref_blob[0] = 0;
5640 return;
5643 if (line->type == LINE_TREE_FILE) {
5644 string_copy_rev(ref_blob, entry->id);
5645 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5648 string_copy_rev(view->ref, entry->id);
5651 static bool
5652 tree_open(struct view *view, enum open_flags flags)
5654 static const char *tree_argv[] = {
5655 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5658 if (string_rev_is_null(ref_commit)) {
5659 report("No tree exists for this commit");
5660 return FALSE;
5663 if (view->lines == 0 && opt_prefix[0]) {
5664 char *pos = opt_prefix;
5666 while (pos && *pos) {
5667 char *end = strchr(pos, '/');
5669 if (end)
5670 *end = 0;
5671 push_tree_stack_entry(pos, 0);
5672 pos = end;
5673 if (end) {
5674 *end = '/';
5675 pos++;
5679 } else if (strcmp(view->vid, view->id)) {
5680 opt_path[0] = 0;
5683 return begin_update(view, opt_cdup, tree_argv, flags);
5686 static struct view_ops tree_ops = {
5687 "file",
5688 { "tree" },
5689 VIEW_SEND_CHILD_ENTER,
5690 sizeof(struct tree_state),
5691 tree_open,
5692 tree_read,
5693 tree_draw,
5694 tree_request,
5695 tree_grep,
5696 tree_select,
5699 static bool
5700 blob_open(struct view *view, enum open_flags flags)
5702 static const char *blob_argv[] = {
5703 "git", "cat-file", "blob", "%(blob)", NULL
5706 if (!ref_blob[0] && opt_file[0]) {
5707 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5708 char blob_spec[SIZEOF_STR];
5709 const char *rev_parse_argv[] = {
5710 "git", "rev-parse", blob_spec, NULL
5713 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5714 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5715 report("Failed to resolve blob from file name");
5716 return FALSE;
5720 if (!ref_blob[0]) {
5721 report("No file chosen, press %s to open tree view",
5722 get_view_key(view, REQ_VIEW_TREE));
5723 return FALSE;
5726 view->encoding = get_path_encoding(opt_file, opt_encoding);
5728 return begin_update(view, NULL, blob_argv, flags);
5731 static bool
5732 blob_read(struct view *view, char *line)
5734 if (!line)
5735 return TRUE;
5736 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5739 static enum request
5740 blob_request(struct view *view, enum request request, struct line *line)
5742 switch (request) {
5743 case REQ_EDIT:
5744 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5745 return REQ_NONE;
5746 default:
5747 return pager_request(view, request, line);
5751 static struct view_ops blob_ops = {
5752 "line",
5753 { "blob" },
5754 VIEW_NO_FLAGS,
5756 blob_open,
5757 blob_read,
5758 pager_draw,
5759 blob_request,
5760 pager_grep,
5761 pager_select,
5765 * Blame backend
5767 * Loading the blame view is a two phase job:
5769 * 1. File content is read either using opt_file from the
5770 * filesystem or using git-cat-file.
5771 * 2. Then blame information is incrementally added by
5772 * reading output from git-blame.
5775 struct blame {
5776 struct blame_commit *commit;
5777 unsigned long lineno;
5778 char text[1];
5781 struct blame_state {
5782 struct blame_commit *commit;
5783 int blamed;
5784 bool done_reading;
5785 bool auto_filename_display;
5788 static bool
5789 blame_detect_filename_display(struct view *view)
5791 bool show_filenames = FALSE;
5792 const char *filename = NULL;
5793 int i;
5795 if (opt_blame_argv) {
5796 for (i = 0; opt_blame_argv[i]; i++) {
5797 if (prefixcmp(opt_blame_argv[i], "-C"))
5798 continue;
5800 show_filenames = TRUE;
5804 for (i = 0; i < view->lines; i++) {
5805 struct blame *blame = view->line[i].data;
5807 if (blame->commit && blame->commit->id[0]) {
5808 if (!filename)
5809 filename = blame->commit->filename;
5810 else if (strcmp(filename, blame->commit->filename))
5811 show_filenames = TRUE;
5815 return show_filenames;
5818 static bool
5819 blame_open(struct view *view, enum open_flags flags)
5821 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5822 char path[SIZEOF_STR];
5823 size_t i;
5825 if (!opt_file[0]) {
5826 report("No file chosen, press %s to open tree view",
5827 get_view_key(view, REQ_VIEW_TREE));
5828 return FALSE;
5831 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5832 string_copy(path, opt_file);
5833 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5834 report("Failed to setup the blame view");
5835 return FALSE;
5839 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5840 const char *blame_cat_file_argv[] = {
5841 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5844 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5845 return FALSE;
5848 /* First pass: remove multiple references to the same commit. */
5849 for (i = 0; i < view->lines; i++) {
5850 struct blame *blame = view->line[i].data;
5852 if (blame->commit && blame->commit->id[0])
5853 blame->commit->id[0] = 0;
5854 else
5855 blame->commit = NULL;
5858 /* Second pass: free existing references. */
5859 for (i = 0; i < view->lines; i++) {
5860 struct blame *blame = view->line[i].data;
5862 if (blame->commit)
5863 free(blame->commit);
5866 string_format(view->vid, "%s", opt_file);
5867 string_format(view->ref, "%s ...", opt_file);
5869 return TRUE;
5872 static struct blame_commit *
5873 get_blame_commit(struct view *view, const char *id)
5875 size_t i;
5877 for (i = 0; i < view->lines; i++) {
5878 struct blame *blame = view->line[i].data;
5880 if (!blame->commit)
5881 continue;
5883 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5884 return blame->commit;
5888 struct blame_commit *commit = calloc(1, sizeof(*commit));
5890 if (commit)
5891 string_ncopy(commit->id, id, SIZEOF_REV);
5892 return commit;
5896 static struct blame_commit *
5897 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5899 struct blame_header header;
5900 struct blame_commit *commit;
5901 struct blame *blame;
5903 if (!parse_blame_header(&header, text, view->lines))
5904 return NULL;
5906 commit = get_blame_commit(view, text);
5907 if (!commit)
5908 return NULL;
5910 state->blamed += header.group;
5911 while (header.group--) {
5912 struct line *line = &view->line[header.lineno + header.group - 1];
5914 blame = line->data;
5915 blame->commit = commit;
5916 blame->lineno = header.orig_lineno + header.group - 1;
5917 line->dirty = 1;
5920 return commit;
5923 static bool
5924 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5926 if (!text) {
5927 const char *blame_argv[] = {
5928 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5929 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5932 if (view->lines == 0 && !view->prev)
5933 die("No blame exist for %s", view->vid);
5935 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5936 report("Failed to load blame data");
5937 return TRUE;
5940 if (opt_goto_line > 0) {
5941 select_view_line(view, opt_goto_line);
5942 opt_goto_line = 0;
5945 state->done_reading = TRUE;
5946 return FALSE;
5948 } else {
5949 size_t textlen = strlen(text);
5950 struct blame *blame;
5952 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5953 return FALSE;
5955 blame->commit = NULL;
5956 strncpy(blame->text, text, textlen);
5957 blame->text[textlen] = 0;
5958 return TRUE;
5962 static bool
5963 blame_read(struct view *view, char *line)
5965 struct blame_state *state = view->private;
5967 if (!state->done_reading)
5968 return blame_read_file(view, line, state);
5970 if (!line) {
5971 state->auto_filename_display = blame_detect_filename_display(view);
5972 string_format(view->ref, "%s", view->vid);
5973 if (view_is_displayed(view)) {
5974 update_view_title(view);
5975 redraw_view_from(view, 0);
5977 return TRUE;
5980 if (!state->commit) {
5981 state->commit = read_blame_commit(view, line, state);
5982 string_format(view->ref, "%s %2zd%%", view->vid,
5983 view->lines ? state->blamed * 100 / view->lines : 0);
5985 } else if (parse_blame_info(state->commit, line)) {
5986 state->commit = NULL;
5989 return TRUE;
5992 static bool
5993 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5995 struct blame_state *state = view->private;
5996 struct blame *blame = line->data;
5997 struct time *time = NULL;
5998 const char *id = NULL, *filename = NULL;
5999 const struct ident *author = NULL;
6000 enum line_type id_type = LINE_ID;
6001 static const enum line_type blame_colors[] = {
6002 LINE_PALETTE_0,
6003 LINE_PALETTE_1,
6004 LINE_PALETTE_2,
6005 LINE_PALETTE_3,
6006 LINE_PALETTE_4,
6007 LINE_PALETTE_5,
6008 LINE_PALETTE_6,
6011 #define BLAME_COLOR(i) \
6012 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6014 if (blame->commit && *blame->commit->filename) {
6015 id = blame->commit->id;
6016 author = blame->commit->author;
6017 filename = blame->commit->filename;
6018 time = &blame->commit->time;
6019 id_type = BLAME_COLOR((long) blame->commit);
6022 if (draw_date(view, time))
6023 return TRUE;
6025 if (draw_author(view, author))
6026 return TRUE;
6028 if (draw_filename(view, filename, state->auto_filename_display))
6029 return TRUE;
6031 if (draw_id_custom(view, id_type, id, opt_id_cols))
6032 return TRUE;
6034 if (draw_lineno(view, lineno))
6035 return TRUE;
6037 draw_text(view, LINE_DEFAULT, blame->text);
6038 return TRUE;
6041 static bool
6042 check_blame_commit(struct blame *blame, bool check_null_id)
6044 if (!blame->commit)
6045 report("Commit data not loaded yet");
6046 else if (check_null_id && string_rev_is_null(blame->commit->id))
6047 report("No commit exist for the selected line");
6048 else
6049 return TRUE;
6050 return FALSE;
6053 static void
6054 setup_blame_parent_line(struct view *view, struct blame *blame)
6056 char from[SIZEOF_REF + SIZEOF_STR];
6057 char to[SIZEOF_REF + SIZEOF_STR];
6058 const char *diff_tree_argv[] = {
6059 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
6060 "--no-color", "-U0", from, to, "--", NULL
6062 struct io io;
6063 int parent_lineno = -1;
6064 int blamed_lineno = -1;
6065 char *line;
6067 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6068 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6069 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6070 return;
6072 while ((line = io_get(&io, '\n', TRUE))) {
6073 if (*line == '@') {
6074 char *pos = strchr(line, '+');
6076 parent_lineno = atoi(line + 4);
6077 if (pos)
6078 blamed_lineno = atoi(pos + 1);
6080 } else if (*line == '+' && parent_lineno != -1) {
6081 if (blame->lineno == blamed_lineno - 1 &&
6082 !strcmp(blame->text, line + 1)) {
6083 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6084 break;
6086 blamed_lineno++;
6090 io_done(&io);
6093 static enum request
6094 blame_request(struct view *view, enum request request, struct line *line)
6096 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6097 struct blame *blame = line->data;
6099 switch (request) {
6100 case REQ_VIEW_BLAME:
6101 if (check_blame_commit(blame, TRUE)) {
6102 string_copy(opt_ref, blame->commit->id);
6103 string_copy(opt_file, blame->commit->filename);
6104 if (blame->lineno)
6105 view->pos.lineno = blame->lineno;
6106 reload_view(view);
6108 break;
6110 case REQ_PARENT:
6111 if (!check_blame_commit(blame, TRUE))
6112 break;
6113 if (!*blame->commit->parent_id) {
6114 report("The selected commit has no parents");
6115 } else {
6116 string_copy_rev(opt_ref, blame->commit->parent_id);
6117 string_copy(opt_file, blame->commit->parent_filename);
6118 setup_blame_parent_line(view, blame);
6119 opt_goto_line = blame->lineno;
6120 reload_view(view);
6122 break;
6124 case REQ_ENTER:
6125 if (!check_blame_commit(blame, FALSE))
6126 break;
6128 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6129 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6130 break;
6132 if (string_rev_is_null(blame->commit->id)) {
6133 struct view *diff = VIEW(REQ_VIEW_DIFF);
6134 const char *diff_parent_argv[] = {
6135 GIT_DIFF_BLAME(opt_encoding_arg,
6136 opt_diff_context_arg,
6137 opt_ignore_space_arg, view->vid)
6139 const char *diff_no_parent_argv[] = {
6140 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
6141 opt_diff_context_arg,
6142 opt_ignore_space_arg, view->vid)
6144 const char **diff_index_argv = *blame->commit->parent_id
6145 ? diff_parent_argv : diff_no_parent_argv;
6147 open_argv(view, diff, diff_index_argv, NULL, flags);
6148 if (diff->pipe)
6149 string_copy_rev(diff->ref, NULL_ID);
6150 } else {
6151 open_view(view, REQ_VIEW_DIFF, flags);
6153 break;
6155 default:
6156 return request;
6159 return REQ_NONE;
6162 static bool
6163 blame_grep(struct view *view, struct line *line)
6165 struct blame *blame = line->data;
6166 struct blame_commit *commit = blame->commit;
6167 const char *text[] = {
6168 blame->text,
6169 commit ? commit->title : "",
6170 commit ? commit->id : "",
6171 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6172 commit ? mkdate(&commit->time, opt_date) : "",
6173 NULL
6176 return grep_text(view, text);
6179 static void
6180 blame_select(struct view *view, struct line *line)
6182 struct blame *blame = line->data;
6183 struct blame_commit *commit = blame->commit;
6185 if (!commit)
6186 return;
6188 if (string_rev_is_null(commit->id))
6189 string_ncopy(ref_commit, "HEAD", 4);
6190 else
6191 string_copy_rev(ref_commit, commit->id);
6194 static struct view_ops blame_ops = {
6195 "line",
6196 { "blame" },
6197 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6198 sizeof(struct blame_state),
6199 blame_open,
6200 blame_read,
6201 blame_draw,
6202 blame_request,
6203 blame_grep,
6204 blame_select,
6208 * Branch backend
6211 struct branch {
6212 const struct ident *author; /* Author of the last commit. */
6213 struct time time; /* Date of the last activity. */
6214 char title[128]; /* First line of the commit message. */
6215 const struct ref *ref; /* Name and commit ID information. */
6218 static const struct ref branch_all;
6219 #define BRANCH_ALL_NAME "All branches"
6220 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6222 static const enum sort_field branch_sort_fields[] = {
6223 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6225 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6227 struct branch_state {
6228 char id[SIZEOF_REV];
6229 size_t max_ref_length;
6232 static int
6233 branch_compare(const void *l1, const void *l2)
6235 const struct branch *branch1 = ((const struct line *) l1)->data;
6236 const struct branch *branch2 = ((const struct line *) l2)->data;
6238 if (branch_is_all(branch1))
6239 return -1;
6240 else if (branch_is_all(branch2))
6241 return 1;
6243 switch (get_sort_field(branch_sort_state)) {
6244 case ORDERBY_DATE:
6245 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6247 case ORDERBY_AUTHOR:
6248 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6250 case ORDERBY_NAME:
6251 default:
6252 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6256 static bool
6257 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6259 struct branch_state *state = view->private;
6260 struct branch *branch = line->data;
6261 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6262 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6264 if (draw_lineno(view, lineno))
6265 return TRUE;
6267 if (draw_date(view, &branch->time))
6268 return TRUE;
6270 if (draw_author(view, branch->author))
6271 return TRUE;
6273 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6274 return TRUE;
6276 if (draw_id(view, branch->ref->id))
6277 return TRUE;
6279 draw_text(view, LINE_DEFAULT, branch->title);
6280 return TRUE;
6283 static enum request
6284 branch_request(struct view *view, enum request request, struct line *line)
6286 struct branch *branch = line->data;
6288 switch (request) {
6289 case REQ_REFRESH:
6290 load_refs();
6291 refresh_view(view);
6292 return REQ_NONE;
6294 case REQ_TOGGLE_SORT_FIELD:
6295 case REQ_TOGGLE_SORT_ORDER:
6296 sort_view(view, request, &branch_sort_state, branch_compare);
6297 return REQ_NONE;
6299 case REQ_ENTER:
6301 const struct ref *ref = branch->ref;
6302 const char *all_branches_argv[] = {
6303 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6305 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6307 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6308 return REQ_NONE;
6310 case REQ_JUMP_COMMIT:
6312 int lineno;
6314 for (lineno = 0; lineno < view->lines; lineno++) {
6315 struct branch *branch = view->line[lineno].data;
6317 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6318 select_view_line(view, lineno);
6319 report_clear();
6320 return REQ_NONE;
6324 default:
6325 return request;
6329 static bool
6330 branch_read(struct view *view, char *line)
6332 struct branch_state *state = view->private;
6333 const char *title = NULL;
6334 const struct ident *author = NULL;
6335 struct time time = {};
6336 size_t i;
6338 if (!line)
6339 return TRUE;
6341 switch (get_line_type(line)) {
6342 case LINE_COMMIT:
6343 string_copy_rev_from_commit_line(state->id, line);
6344 return TRUE;
6346 case LINE_AUTHOR:
6347 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6348 break;
6350 default:
6351 title = line + STRING_SIZE("title ");
6354 for (i = 0; i < view->lines; i++) {
6355 struct branch *branch = view->line[i].data;
6357 if (strcmp(branch->ref->id, state->id))
6358 continue;
6360 if (author) {
6361 branch->author = author;
6362 branch->time = time;
6365 if (title)
6366 string_expand(branch->title, sizeof(branch->title), title, 1);
6368 view->line[i].dirty = TRUE;
6371 return TRUE;
6374 static bool
6375 branch_open_visitor(void *data, const struct ref *ref)
6377 struct view *view = data;
6378 struct branch_state *state = view->private;
6379 struct branch *branch;
6380 bool is_all = ref == &branch_all;
6381 size_t ref_length;
6383 if (ref->tag || ref->ltag)
6384 return TRUE;
6386 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6387 return FALSE;
6389 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6390 if (ref_length > state->max_ref_length)
6391 state->max_ref_length = ref_length;
6393 branch->ref = ref;
6394 return TRUE;
6397 static bool
6398 branch_open(struct view *view, enum open_flags flags)
6400 const char *branch_log[] = {
6401 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
6402 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6403 "--all", "--simplify-by-decoration", NULL
6406 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6407 report("Failed to load branch data");
6408 return FALSE;
6411 branch_open_visitor(view, &branch_all);
6412 foreach_ref(branch_open_visitor, view);
6414 return TRUE;
6417 static bool
6418 branch_grep(struct view *view, struct line *line)
6420 struct branch *branch = line->data;
6421 const char *text[] = {
6422 branch->ref->name,
6423 mkauthor(branch->author, opt_author_width, opt_author),
6424 NULL
6427 return grep_text(view, text);
6430 static void
6431 branch_select(struct view *view, struct line *line)
6433 struct branch *branch = line->data;
6435 if (branch_is_all(branch)) {
6436 string_copy(view->ref, BRANCH_ALL_NAME);
6437 return;
6439 string_copy_rev(view->ref, branch->ref->id);
6440 string_copy_rev(ref_commit, branch->ref->id);
6441 string_copy_rev(ref_head, branch->ref->id);
6442 string_copy_rev(ref_branch, branch->ref->name);
6445 static struct view_ops branch_ops = {
6446 "branch",
6447 { "branch" },
6448 VIEW_NO_FLAGS,
6449 sizeof(struct branch_state),
6450 branch_open,
6451 branch_read,
6452 branch_draw,
6453 branch_request,
6454 branch_grep,
6455 branch_select,
6459 * Status backend
6462 struct status {
6463 char status;
6464 struct {
6465 mode_t mode;
6466 char rev[SIZEOF_REV];
6467 char name[SIZEOF_STR];
6468 } old;
6469 struct {
6470 mode_t mode;
6471 char rev[SIZEOF_REV];
6472 char name[SIZEOF_STR];
6473 } new;
6476 static char status_onbranch[SIZEOF_STR];
6477 static struct status stage_status;
6478 static enum line_type stage_line_type;
6480 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6482 /* This should work even for the "On branch" line. */
6483 static inline bool
6484 status_has_none(struct view *view, struct line *line)
6486 return view_has_line(view, line) && !line[1].data;
6489 /* Get fields from the diff line:
6490 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6492 static inline bool
6493 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6495 const char *old_mode = buf + 1;
6496 const char *new_mode = buf + 8;
6497 const char *old_rev = buf + 15;
6498 const char *new_rev = buf + 56;
6499 const char *status = buf + 97;
6501 if (bufsize < 98 ||
6502 old_mode[-1] != ':' ||
6503 new_mode[-1] != ' ' ||
6504 old_rev[-1] != ' ' ||
6505 new_rev[-1] != ' ' ||
6506 status[-1] != ' ')
6507 return FALSE;
6509 file->status = *status;
6511 string_copy_rev(file->old.rev, old_rev);
6512 string_copy_rev(file->new.rev, new_rev);
6514 file->old.mode = strtoul(old_mode, NULL, 8);
6515 file->new.mode = strtoul(new_mode, NULL, 8);
6517 file->old.name[0] = file->new.name[0] = 0;
6519 return TRUE;
6522 static bool
6523 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6525 struct status *unmerged = NULL;
6526 char *buf;
6527 struct io io;
6529 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6530 return FALSE;
6532 add_line_nodata(view, type);
6534 while ((buf = io_get(&io, 0, TRUE))) {
6535 struct status *file = unmerged;
6537 if (!file) {
6538 if (!add_line_alloc(view, &file, type, 0, FALSE))
6539 goto error_out;
6542 /* Parse diff info part. */
6543 if (status) {
6544 file->status = status;
6545 if (status == 'A')
6546 string_copy(file->old.rev, NULL_ID);
6548 } else if (!file->status || file == unmerged) {
6549 if (!status_get_diff(file, buf, strlen(buf)))
6550 goto error_out;
6552 buf = io_get(&io, 0, TRUE);
6553 if (!buf)
6554 break;
6556 /* Collapse all modified entries that follow an
6557 * associated unmerged entry. */
6558 if (unmerged == file) {
6559 unmerged->status = 'U';
6560 unmerged = NULL;
6561 } else if (file->status == 'U') {
6562 unmerged = file;
6566 /* Grab the old name for rename/copy. */
6567 if (!*file->old.name &&
6568 (file->status == 'R' || file->status == 'C')) {
6569 string_ncopy(file->old.name, buf, strlen(buf));
6571 buf = io_get(&io, 0, TRUE);
6572 if (!buf)
6573 break;
6576 /* git-ls-files just delivers a NUL separated list of
6577 * file names similar to the second half of the
6578 * git-diff-* output. */
6579 string_ncopy(file->new.name, buf, strlen(buf));
6580 if (!*file->old.name)
6581 string_copy(file->old.name, file->new.name);
6582 file = NULL;
6585 if (io_error(&io)) {
6586 error_out:
6587 io_done(&io);
6588 return FALSE;
6591 if (!view->line[view->lines - 1].data)
6592 add_line_nodata(view, LINE_STAT_NONE);
6594 io_done(&io);
6595 return TRUE;
6598 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6599 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6601 static const char *status_list_other_argv[] = {
6602 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6605 static const char *status_list_no_head_argv[] = {
6606 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6609 static const char *update_index_argv[] = {
6610 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6613 /* Restore the previous line number to stay in the context or select a
6614 * line with something that can be updated. */
6615 static void
6616 status_restore(struct view *view)
6618 if (!check_position(&view->prev_pos))
6619 return;
6621 if (view->prev_pos.lineno >= view->lines)
6622 view->prev_pos.lineno = view->lines - 1;
6623 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6624 view->prev_pos.lineno++;
6625 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6626 view->prev_pos.lineno--;
6628 /* If the above fails, always skip the "On branch" line. */
6629 if (view->prev_pos.lineno < view->lines)
6630 view->pos.lineno = view->prev_pos.lineno;
6631 else
6632 view->pos.lineno = 1;
6634 if (view->prev_pos.offset > view->pos.lineno)
6635 view->pos.offset = view->pos.lineno;
6636 else if (view->prev_pos.offset < view->lines)
6637 view->pos.offset = view->prev_pos.offset;
6639 clear_position(&view->prev_pos);
6642 static void
6643 status_update_onbranch(void)
6645 static const char *paths[][2] = {
6646 { "rebase-apply/rebasing", "Rebasing" },
6647 { "rebase-apply/applying", "Applying mailbox" },
6648 { "rebase-apply/", "Rebasing mailbox" },
6649 { "rebase-merge/interactive", "Interactive rebase" },
6650 { "rebase-merge/", "Rebase merge" },
6651 { "MERGE_HEAD", "Merging" },
6652 { "BISECT_LOG", "Bisecting" },
6653 { "HEAD", "On branch" },
6655 char buf[SIZEOF_STR];
6656 struct stat stat;
6657 int i;
6659 if (is_initial_commit()) {
6660 string_copy(status_onbranch, "Initial commit");
6661 return;
6664 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6665 char *head = opt_head;
6667 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6668 lstat(buf, &stat) < 0)
6669 continue;
6671 if (!*opt_head) {
6672 struct io io;
6674 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6675 io_read_buf(&io, buf, sizeof(buf))) {
6676 head = buf;
6677 if (!prefixcmp(head, "refs/heads/"))
6678 head += STRING_SIZE("refs/heads/");
6682 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6683 string_copy(status_onbranch, opt_head);
6684 return;
6687 string_copy(status_onbranch, "Not currently on any branch");
6690 /* First parse staged info using git-diff-index(1), then parse unstaged
6691 * info using git-diff-files(1), and finally untracked files using
6692 * git-ls-files(1). */
6693 static bool
6694 status_open(struct view *view, enum open_flags flags)
6696 const char **staged_argv = is_initial_commit() ?
6697 status_list_no_head_argv : status_diff_index_argv;
6698 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6700 if (opt_is_inside_work_tree == FALSE) {
6701 report("The status view requires a working tree");
6702 return FALSE;
6705 reset_view(view);
6707 add_line_nodata(view, LINE_STAT_HEAD);
6708 status_update_onbranch();
6710 io_run_bg(update_index_argv);
6712 if (!opt_untracked_dirs_content)
6713 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6715 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6716 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6717 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6718 report("Failed to load status data");
6719 return FALSE;
6722 /* Restore the exact position or use the specialized restore
6723 * mode? */
6724 status_restore(view);
6725 return TRUE;
6728 static bool
6729 status_draw(struct view *view, struct line *line, unsigned int lineno)
6731 struct status *status = line->data;
6732 enum line_type type;
6733 const char *text;
6735 if (!status) {
6736 switch (line->type) {
6737 case LINE_STAT_STAGED:
6738 type = LINE_STAT_SECTION;
6739 text = "Changes to be committed:";
6740 break;
6742 case LINE_STAT_UNSTAGED:
6743 type = LINE_STAT_SECTION;
6744 text = "Changed but not updated:";
6745 break;
6747 case LINE_STAT_UNTRACKED:
6748 type = LINE_STAT_SECTION;
6749 text = "Untracked files:";
6750 break;
6752 case LINE_STAT_NONE:
6753 type = LINE_DEFAULT;
6754 text = " (no files)";
6755 break;
6757 case LINE_STAT_HEAD:
6758 type = LINE_STAT_HEAD;
6759 text = status_onbranch;
6760 break;
6762 default:
6763 return FALSE;
6765 } else {
6766 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6768 buf[0] = status->status;
6769 if (draw_text(view, line->type, buf))
6770 return TRUE;
6771 type = LINE_DEFAULT;
6772 text = status->new.name;
6775 draw_text(view, type, text);
6776 return TRUE;
6779 static enum request
6780 status_enter(struct view *view, struct line *line)
6782 struct status *status = line->data;
6783 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6785 if (line->type == LINE_STAT_NONE ||
6786 (!status && line[1].type == LINE_STAT_NONE)) {
6787 report("No file to diff");
6788 return REQ_NONE;
6791 switch (line->type) {
6792 case LINE_STAT_STAGED:
6793 case LINE_STAT_UNSTAGED:
6794 break;
6796 case LINE_STAT_UNTRACKED:
6797 if (!status) {
6798 report("No file to show");
6799 return REQ_NONE;
6802 if (!suffixcmp(status->new.name, -1, "/")) {
6803 report("Cannot display a directory");
6804 return REQ_NONE;
6806 break;
6808 case LINE_STAT_HEAD:
6809 return REQ_NONE;
6811 default:
6812 die("line type %d not handled in switch", line->type);
6815 if (status) {
6816 stage_status = *status;
6817 } else {
6818 memset(&stage_status, 0, sizeof(stage_status));
6821 stage_line_type = line->type;
6823 open_view(view, REQ_VIEW_STAGE, flags);
6824 return REQ_NONE;
6827 static bool
6828 status_exists(struct view *view, struct status *status, enum line_type type)
6830 unsigned long lineno;
6832 for (lineno = 0; lineno < view->lines; lineno++) {
6833 struct line *line = &view->line[lineno];
6834 struct status *pos = line->data;
6836 if (line->type != type)
6837 continue;
6838 if (!pos && (!status || !status->status) && line[1].data) {
6839 select_view_line(view, lineno);
6840 return TRUE;
6842 if (pos && !strcmp(status->new.name, pos->new.name)) {
6843 select_view_line(view, lineno);
6844 return TRUE;
6848 return FALSE;
6852 static bool
6853 status_update_prepare(struct io *io, enum line_type type)
6855 const char *staged_argv[] = {
6856 "git", "update-index", "-z", "--index-info", NULL
6858 const char *others_argv[] = {
6859 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6862 switch (type) {
6863 case LINE_STAT_STAGED:
6864 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6866 case LINE_STAT_UNSTAGED:
6867 case LINE_STAT_UNTRACKED:
6868 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6870 default:
6871 die("line type %d not handled in switch", type);
6872 return FALSE;
6876 static bool
6877 status_update_write(struct io *io, struct status *status, enum line_type type)
6879 switch (type) {
6880 case LINE_STAT_STAGED:
6881 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6882 status->old.rev, status->old.name, 0);
6884 case LINE_STAT_UNSTAGED:
6885 case LINE_STAT_UNTRACKED:
6886 return io_printf(io, "%s%c", status->new.name, 0);
6888 default:
6889 die("line type %d not handled in switch", type);
6890 return FALSE;
6894 static bool
6895 status_update_file(struct status *status, enum line_type type)
6897 struct io io;
6898 bool result;
6900 if (!status_update_prepare(&io, type))
6901 return FALSE;
6903 result = status_update_write(&io, status, type);
6904 return io_done(&io) && result;
6907 static bool
6908 status_update_files(struct view *view, struct line *line)
6910 char buf[sizeof(view->ref)];
6911 struct io io;
6912 bool result = TRUE;
6913 struct line *pos;
6914 int files = 0;
6915 int file, done;
6916 int cursor_y = -1, cursor_x = -1;
6918 if (!status_update_prepare(&io, line->type))
6919 return FALSE;
6921 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6922 files++;
6924 string_copy(buf, view->ref);
6925 getsyx(cursor_y, cursor_x);
6926 for (file = 0, done = 5; result && file < files; line++, file++) {
6927 int almost_done = file * 100 / files;
6929 if (almost_done > done) {
6930 done = almost_done;
6931 string_format(view->ref, "updating file %u of %u (%d%% done)",
6932 file, files, done);
6933 update_view_title(view);
6934 setsyx(cursor_y, cursor_x);
6935 doupdate();
6937 result = status_update_write(&io, line->data, line->type);
6939 string_copy(view->ref, buf);
6941 return io_done(&io) && result;
6944 static bool
6945 status_update(struct view *view)
6947 struct line *line = &view->line[view->pos.lineno];
6949 assert(view->lines);
6951 if (!line->data) {
6952 if (status_has_none(view, line)) {
6953 report("Nothing to update");
6954 return FALSE;
6957 if (!status_update_files(view, line + 1)) {
6958 report("Failed to update file status");
6959 return FALSE;
6962 } else if (!status_update_file(line->data, line->type)) {
6963 report("Failed to update file status");
6964 return FALSE;
6967 return TRUE;
6970 static bool
6971 status_revert(struct status *status, enum line_type type, bool has_none)
6973 if (!status || type != LINE_STAT_UNSTAGED) {
6974 if (type == LINE_STAT_STAGED) {
6975 report("Cannot revert changes to staged files");
6976 } else if (type == LINE_STAT_UNTRACKED) {
6977 report("Cannot revert changes to untracked files");
6978 } else if (has_none) {
6979 report("Nothing to revert");
6980 } else {
6981 report("Cannot revert changes to multiple files");
6984 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6985 char mode[10] = "100644";
6986 const char *reset_argv[] = {
6987 "git", "update-index", "--cacheinfo", mode,
6988 status->old.rev, status->old.name, NULL
6990 const char *checkout_argv[] = {
6991 "git", "checkout", "--", status->old.name, NULL
6994 if (status->status == 'U') {
6995 string_format(mode, "%5o", status->old.mode);
6997 if (status->old.mode == 0 && status->new.mode == 0) {
6998 reset_argv[2] = "--force-remove";
6999 reset_argv[3] = status->old.name;
7000 reset_argv[4] = NULL;
7003 if (!io_run_fg(reset_argv, opt_cdup))
7004 return FALSE;
7005 if (status->old.mode == 0 && status->new.mode == 0)
7006 return TRUE;
7009 return io_run_fg(checkout_argv, opt_cdup);
7012 return FALSE;
7015 static enum request
7016 status_request(struct view *view, enum request request, struct line *line)
7018 struct status *status = line->data;
7020 switch (request) {
7021 case REQ_STATUS_UPDATE:
7022 if (!status_update(view))
7023 return REQ_NONE;
7024 break;
7026 case REQ_STATUS_REVERT:
7027 if (!status_revert(status, line->type, status_has_none(view, line)))
7028 return REQ_NONE;
7029 break;
7031 case REQ_STATUS_MERGE:
7032 if (!status || status->status != 'U') {
7033 report("Merging only possible for files with unmerged status ('U').");
7034 return REQ_NONE;
7036 open_mergetool(status->new.name);
7037 break;
7039 case REQ_EDIT:
7040 if (!status)
7041 return request;
7042 if (status->status == 'D') {
7043 report("File has been deleted.");
7044 return REQ_NONE;
7047 open_editor(status->new.name, 0);
7048 break;
7050 case REQ_VIEW_BLAME:
7051 if (status)
7052 opt_ref[0] = 0;
7053 return request;
7055 case REQ_ENTER:
7056 /* After returning the status view has been split to
7057 * show the stage view. No further reloading is
7058 * necessary. */
7059 return status_enter(view, line);
7061 case REQ_REFRESH:
7062 /* Load the current branch information and then the view. */
7063 load_refs();
7064 break;
7066 default:
7067 return request;
7070 refresh_view(view);
7072 return REQ_NONE;
7075 static bool
7076 status_stage_info_(char *buf, size_t bufsize,
7077 enum line_type type, struct status *status)
7079 const char *file = status ? status->new.name : "";
7080 const char *info;
7082 switch (type) {
7083 case LINE_STAT_STAGED:
7084 if (status && status->status)
7085 info = "Staged changes to %s";
7086 else
7087 info = "Staged changes";
7088 break;
7090 case LINE_STAT_UNSTAGED:
7091 if (status && status->status)
7092 info = "Unstaged changes to %s";
7093 else
7094 info = "Unstaged changes";
7095 break;
7097 case LINE_STAT_UNTRACKED:
7098 info = "Untracked file %s";
7099 break;
7101 case LINE_STAT_HEAD:
7102 default:
7103 info = "";
7106 return string_nformat(buf, bufsize, NULL, info, file);
7108 #define status_stage_info(buf, type, status) \
7109 status_stage_info_(buf, sizeof(buf), type, status)
7111 static void
7112 status_select(struct view *view, struct line *line)
7114 struct status *status = line->data;
7115 char file[SIZEOF_STR] = "all files";
7116 const char *text;
7117 const char *key;
7119 if (status && !string_format(file, "'%s'", status->new.name))
7120 return;
7122 if (!status && line[1].type == LINE_STAT_NONE)
7123 line++;
7125 switch (line->type) {
7126 case LINE_STAT_STAGED:
7127 text = "Press %s to unstage %s for commit";
7128 break;
7130 case LINE_STAT_UNSTAGED:
7131 text = "Press %s to stage %s for commit";
7132 break;
7134 case LINE_STAT_UNTRACKED:
7135 text = "Press %s to stage %s for addition";
7136 break;
7138 case LINE_STAT_HEAD:
7139 case LINE_STAT_NONE:
7140 text = "Nothing to update";
7141 break;
7143 default:
7144 die("line type %d not handled in switch", line->type);
7147 if (status && status->status == 'U') {
7148 text = "Press %s to resolve conflict in %s";
7149 key = get_view_key(view, REQ_STATUS_MERGE);
7151 } else {
7152 key = get_view_key(view, REQ_STATUS_UPDATE);
7155 string_format(view->ref, text, key, file);
7156 status_stage_info(ref_status, line->type, status);
7157 if (status)
7158 string_copy(opt_file, status->new.name);
7161 static bool
7162 status_grep(struct view *view, struct line *line)
7164 struct status *status = line->data;
7166 if (status) {
7167 const char buf[2] = { status->status, 0 };
7168 const char *text[] = { status->new.name, buf, NULL };
7170 return grep_text(view, text);
7173 return FALSE;
7176 static struct view_ops status_ops = {
7177 "file",
7178 { "status" },
7179 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER,
7181 status_open,
7182 NULL,
7183 status_draw,
7184 status_request,
7185 status_grep,
7186 status_select,
7190 struct stage_state {
7191 struct diff_state diff;
7192 size_t chunks;
7193 int *chunk;
7196 static bool
7197 stage_diff_write(struct io *io, struct line *line, struct line *end)
7199 while (line < end) {
7200 if (!io_write(io, line->data, strlen(line->data)) ||
7201 !io_write(io, "\n", 1))
7202 return FALSE;
7203 line++;
7204 if (line->type == LINE_DIFF_CHUNK ||
7205 line->type == LINE_DIFF_HEADER)
7206 break;
7209 return TRUE;
7212 static bool
7213 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7215 const char *apply_argv[SIZEOF_ARG] = {
7216 "git", "apply", "--whitespace=nowarn", NULL
7218 struct line *diff_hdr;
7219 struct io io;
7220 int argc = 3;
7222 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7223 if (!diff_hdr)
7224 return FALSE;
7226 if (!revert)
7227 apply_argv[argc++] = "--cached";
7228 if (line != NULL)
7229 apply_argv[argc++] = "--unidiff-zero";
7230 if (revert || stage_line_type == LINE_STAT_STAGED)
7231 apply_argv[argc++] = "-R";
7232 apply_argv[argc++] = "-";
7233 apply_argv[argc++] = NULL;
7234 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7235 return FALSE;
7237 if (line != NULL) {
7238 int lineno = 0;
7239 struct line *context = chunk + 1;
7240 const char *markers[] = {
7241 line->type == LINE_DIFF_DEL ? "" : ",0",
7242 line->type == LINE_DIFF_DEL ? ",0" : "",
7245 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7247 while (context < line) {
7248 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7249 break;
7250 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7251 lineno++;
7253 context++;
7256 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7257 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7258 lineno, markers[0], lineno, markers[1]) ||
7259 !stage_diff_write(&io, line, line + 1)) {
7260 chunk = NULL;
7262 } else {
7263 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7264 !stage_diff_write(&io, chunk, view->line + view->lines))
7265 chunk = NULL;
7268 io_done(&io);
7270 return chunk ? TRUE : FALSE;
7273 static bool
7274 stage_update(struct view *view, struct line *line, bool single)
7276 struct line *chunk = NULL;
7278 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7279 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7281 if (chunk) {
7282 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7283 report("Failed to apply chunk");
7284 return FALSE;
7287 } else if (!stage_status.status) {
7288 view = view->parent;
7290 for (line = view->line; view_has_line(view, line); line++)
7291 if (line->type == stage_line_type)
7292 break;
7294 if (!status_update_files(view, line + 1)) {
7295 report("Failed to update files");
7296 return FALSE;
7299 } else if (!status_update_file(&stage_status, stage_line_type)) {
7300 report("Failed to update file");
7301 return FALSE;
7304 return TRUE;
7307 static bool
7308 stage_revert(struct view *view, struct line *line)
7310 struct line *chunk = NULL;
7312 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7313 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7315 if (chunk) {
7316 if (!prompt_yesno("Are you sure you want to revert changes?"))
7317 return FALSE;
7319 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7320 report("Failed to revert chunk");
7321 return FALSE;
7323 return TRUE;
7325 } else {
7326 return status_revert(stage_status.status ? &stage_status : NULL,
7327 stage_line_type, FALSE);
7332 static void
7333 stage_next(struct view *view, struct line *line)
7335 struct stage_state *state = view->private;
7336 int i;
7338 if (!state->chunks) {
7339 for (line = view->line; view_has_line(view, line); line++) {
7340 if (line->type != LINE_DIFF_CHUNK)
7341 continue;
7343 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7344 report("Allocation failure");
7345 return;
7348 state->chunk[state->chunks++] = line - view->line;
7352 for (i = 0; i < state->chunks; i++) {
7353 if (state->chunk[i] > view->pos.lineno) {
7354 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7355 report("Chunk %d of %zd", i + 1, state->chunks);
7356 return;
7360 report("No next chunk found");
7363 static enum request
7364 stage_request(struct view *view, enum request request, struct line *line)
7366 switch (request) {
7367 case REQ_STATUS_UPDATE:
7368 if (!stage_update(view, line, FALSE))
7369 return REQ_NONE;
7370 break;
7372 case REQ_STATUS_REVERT:
7373 if (!stage_revert(view, line))
7374 return REQ_NONE;
7375 break;
7377 case REQ_STAGE_UPDATE_LINE:
7378 if (stage_line_type == LINE_STAT_UNTRACKED ||
7379 stage_status.status == 'A') {
7380 report("Staging single lines is not supported for new files");
7381 return REQ_NONE;
7383 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7384 report("Please select a change to stage");
7385 return REQ_NONE;
7387 if (!stage_update(view, line, TRUE))
7388 return REQ_NONE;
7389 break;
7391 case REQ_STAGE_NEXT:
7392 if (stage_line_type == LINE_STAT_UNTRACKED) {
7393 report("File is untracked; press %s to add",
7394 get_view_key(view, REQ_STATUS_UPDATE));
7395 return REQ_NONE;
7397 stage_next(view, line);
7398 return REQ_NONE;
7400 case REQ_EDIT:
7401 if (!stage_status.new.name[0])
7402 return diff_common_edit(view, request, line);
7404 if (stage_status.status == 'D') {
7405 report("File has been deleted.");
7406 return REQ_NONE;
7409 if (stage_line_type == LINE_STAT_UNTRACKED) {
7410 open_editor(stage_status.new.name, (line - view->line) + 1);
7411 } else {
7412 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7414 break;
7416 case REQ_REFRESH:
7417 /* Reload everything(including current branch information) ... */
7418 load_refs();
7419 break;
7421 case REQ_VIEW_BLAME:
7422 if (stage_status.new.name[0]) {
7423 string_copy(opt_file, stage_status.new.name);
7424 opt_ref[0] = 0;
7426 return request;
7428 case REQ_ENTER:
7429 return diff_common_enter(view, request, line);
7431 case REQ_DIFF_CONTEXT_UP:
7432 case REQ_DIFF_CONTEXT_DOWN:
7433 if (!update_diff_context(request))
7434 return REQ_NONE;
7435 break;
7437 default:
7438 return request;
7441 refresh_view(view->parent);
7443 /* Check whether the staged entry still exists, and close the
7444 * stage view if it doesn't. */
7445 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7446 status_restore(view->parent);
7447 return REQ_VIEW_CLOSE;
7450 refresh_view(view);
7452 return REQ_NONE;
7455 static bool
7456 stage_open(struct view *view, enum open_flags flags)
7458 static const char *no_head_diff_argv[] = {
7459 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7460 stage_status.new.name)
7462 static const char *index_show_argv[] = {
7463 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7464 stage_status.old.name, stage_status.new.name)
7466 static const char *files_show_argv[] = {
7467 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7468 stage_status.old.name, stage_status.new.name)
7470 /* Diffs for unmerged entries are empty when passing the new
7471 * path, so leave out the new path. */
7472 static const char *files_unmerged_argv[] = {
7473 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
7474 opt_diff_context_arg, opt_ignore_space_arg, "--",
7475 stage_status.old.name, NULL
7477 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7478 const char **argv = NULL;
7480 if (!stage_line_type) {
7481 report("No stage content, press %s to open the status view and choose file",
7482 get_view_key(view, REQ_VIEW_STATUS));
7483 return FALSE;
7486 view->encoding = NULL;
7488 switch (stage_line_type) {
7489 case LINE_STAT_STAGED:
7490 if (is_initial_commit()) {
7491 argv = no_head_diff_argv;
7492 } else {
7493 argv = index_show_argv;
7495 break;
7497 case LINE_STAT_UNSTAGED:
7498 if (stage_status.status != 'U')
7499 argv = files_show_argv;
7500 else
7501 argv = files_unmerged_argv;
7502 break;
7504 case LINE_STAT_UNTRACKED:
7505 argv = file_argv;
7506 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
7507 break;
7509 case LINE_STAT_HEAD:
7510 default:
7511 die("line type %d not handled in switch", stage_line_type);
7514 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7515 || !argv_copy(&view->argv, argv)) {
7516 report("Failed to open staged view");
7517 return FALSE;
7520 view->vid[0] = 0;
7521 view->dir = opt_cdup;
7522 return begin_update(view, NULL, NULL, flags);
7525 static bool
7526 stage_read(struct view *view, char *data)
7528 struct stage_state *state = view->private;
7530 if (stage_line_type == LINE_STAT_UNTRACKED)
7531 return pager_common_read(view, data, LINE_DEFAULT);
7533 if (data && diff_common_read(view, data, &state->diff))
7534 return TRUE;
7536 return pager_read(view, data);
7539 static struct view_ops stage_ops = {
7540 "line",
7541 { "stage" },
7542 VIEW_DIFF_LIKE,
7543 sizeof(struct stage_state),
7544 stage_open,
7545 stage_read,
7546 diff_common_draw,
7547 stage_request,
7548 pager_grep,
7549 pager_select,
7554 * Revision graph
7557 static const enum line_type graph_colors[] = {
7558 LINE_PALETTE_0,
7559 LINE_PALETTE_1,
7560 LINE_PALETTE_2,
7561 LINE_PALETTE_3,
7562 LINE_PALETTE_4,
7563 LINE_PALETTE_5,
7564 LINE_PALETTE_6,
7567 static enum line_type get_graph_color(struct graph_symbol *symbol)
7569 if (symbol->commit)
7570 return LINE_GRAPH_COMMIT;
7571 assert(symbol->color < ARRAY_SIZE(graph_colors));
7572 return graph_colors[symbol->color];
7575 static bool
7576 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7578 const char *chars = graph_symbol_to_utf8(symbol);
7580 return draw_text(view, color, chars + !!first);
7583 static bool
7584 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7586 const char *chars = graph_symbol_to_ascii(symbol);
7588 return draw_text(view, color, chars + !!first);
7591 static bool
7592 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7594 const chtype *chars = graph_symbol_to_chtype(symbol);
7596 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7599 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7601 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7603 static const draw_graph_fn fns[] = {
7604 draw_graph_ascii,
7605 draw_graph_chtype,
7606 draw_graph_utf8
7608 draw_graph_fn fn = fns[opt_line_graphics];
7609 int i;
7611 for (i = 0; i < canvas->size; i++) {
7612 struct graph_symbol *symbol = &canvas->symbols[i];
7613 enum line_type color = get_graph_color(symbol);
7615 if (fn(view, symbol, color, i == 0))
7616 return TRUE;
7619 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7623 * Main view backend
7626 struct commit {
7627 char id[SIZEOF_REV]; /* SHA1 ID. */
7628 const struct ident *author; /* Author of the commit. */
7629 struct time time; /* Date from the author ident. */
7630 struct graph_canvas graph; /* Ancestry chain graphics. */
7631 char title[1]; /* First line of the commit message. */
7634 struct main_state {
7635 struct graph graph;
7636 struct commit current;
7637 int id_width;
7638 bool in_header;
7639 bool added_changes_commits;
7640 bool with_graph;
7643 static void
7644 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7646 struct main_state *state = view->private;
7648 string_copy_rev(commit->id, ids);
7649 if (state->with_graph)
7650 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7653 static struct commit *
7654 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7655 const char *title, bool custom)
7657 struct main_state *state = view->private;
7658 size_t titlelen = strlen(title);
7659 struct commit *commit;
7660 char buf[SIZEOF_STR / 2];
7662 /* FIXME: More graceful handling of titles; append "..." to
7663 * shortened titles, etc. */
7664 string_expand(buf, sizeof(buf), title, 1);
7665 title = buf;
7666 titlelen = strlen(title);
7668 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7669 return NULL;
7671 *commit = *template;
7672 strncpy(commit->title, title, titlelen);
7673 state->graph.canvas = &commit->graph;
7674 memset(template, 0, sizeof(*template));
7675 return commit;
7678 static inline void
7679 main_flush_commit(struct view *view, struct commit *commit)
7681 if (*commit->id)
7682 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7685 static bool
7686 main_has_changes(const char *argv[])
7688 struct io io;
7690 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7691 return FALSE;
7692 io_done(&io);
7693 return io.status == 1;
7696 static void
7697 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7699 char ids[SIZEOF_STR] = NULL_ID " ";
7700 struct main_state *state = view->private;
7701 struct commit commit = {};
7702 struct timeval now;
7703 struct timezone tz;
7705 if (!parent)
7706 return;
7708 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7710 if (!gettimeofday(&now, &tz)) {
7711 commit.time.tz = tz.tz_minuteswest * 60;
7712 commit.time.sec = now.tv_sec - commit.time.tz;
7715 commit.author = &unknown_ident;
7716 main_register_commit(view, &commit, ids, FALSE);
7717 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7718 graph_render_parents(&state->graph);
7721 static void
7722 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7724 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7725 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7726 const char *staged_parent = NULL_ID;
7727 const char *unstaged_parent = parent;
7729 if (!is_head_commit(parent))
7730 return;
7732 state->added_changes_commits = TRUE;
7734 io_run_bg(update_index_argv);
7736 if (!main_has_changes(unstaged_argv)) {
7737 unstaged_parent = NULL;
7738 staged_parent = parent;
7741 if (!main_has_changes(staged_argv)) {
7742 staged_parent = NULL;
7745 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7746 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7749 static bool
7750 main_open(struct view *view, enum open_flags flags)
7752 static const char *main_argv[] = {
7753 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7755 struct main_state *state = view->private;
7757 state->with_graph = opt_rev_graph;
7758 return begin_update(view, NULL, main_argv, flags);
7761 static void
7762 main_done(struct view *view)
7764 int i;
7766 for (i = 0; i < view->lines; i++) {
7767 struct commit *commit = view->line[i].data;
7769 free(commit->graph.symbols);
7773 #define MAIN_NO_COMMIT_REFS 1
7774 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
7775 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
7777 static inline struct ref_list *
7778 main_get_commit_refs(struct line *line, struct commit *commit)
7780 struct ref_list *refs = NULL;
7782 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
7783 main_mark_no_commit_refs(line);
7785 return refs;
7788 static bool
7789 main_draw(struct view *view, struct line *line, unsigned int lineno)
7791 struct main_state *state = view->private;
7792 struct commit *commit = line->data;
7793 struct ref_list *refs = NULL;
7795 if (!commit->author)
7796 return FALSE;
7798 if (draw_lineno(view, lineno))
7799 return TRUE;
7801 if (opt_show_id) {
7802 if (state->id_width) {
7803 if (draw_formatted_field(view, LINE_ID, state->id_width,
7804 "stash@{%d}", line->lineno - 1))
7805 return TRUE;
7806 } else if (draw_id(view, commit->id)) {
7807 return TRUE;
7811 if (draw_date(view, &commit->time))
7812 return TRUE;
7814 if (draw_author(view, commit->author))
7815 return TRUE;
7817 if (state->with_graph && draw_graph(view, &commit->graph))
7818 return TRUE;
7820 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
7821 return TRUE;
7823 if (commit->title)
7824 draw_commit_title(view, commit->title, 0);
7825 return TRUE;
7828 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7829 static bool
7830 main_read(struct view *view, char *line)
7832 struct main_state *state = view->private;
7833 struct graph *graph = &state->graph;
7834 enum line_type type;
7835 struct commit *commit = &state->current;
7837 if (!line) {
7838 main_flush_commit(view, commit);
7840 if (!view->lines && !view->prev)
7841 die("No revisions match the given arguments.");
7842 if (view->lines > 0) {
7843 struct commit *last = view->line[view->lines - 1].data;
7845 view->line[view->lines - 1].dirty = 1;
7846 if (!last->author) {
7847 view->lines--;
7848 free(last);
7852 if (state->with_graph)
7853 done_graph(graph);
7854 return TRUE;
7857 type = get_line_type(line);
7858 if (type == LINE_COMMIT) {
7859 bool is_boundary;
7861 state->in_header = TRUE;
7862 line += STRING_SIZE("commit ");
7863 is_boundary = *line == '-';
7864 if (is_boundary || !isalnum(*line))
7865 line++;
7867 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7868 main_add_changes_commits(view, state, line);
7869 else
7870 main_flush_commit(view, commit);
7872 main_register_commit(view, &state->current, line, is_boundary);
7873 return TRUE;
7876 if (!*commit->id)
7877 return TRUE;
7879 /* Empty line separates the commit header from the log itself. */
7880 if (*line == '\0')
7881 state->in_header = FALSE;
7883 switch (type) {
7884 case LINE_PARENT:
7885 if (state->with_graph && !graph->has_parents)
7886 graph_add_parent(graph, line + STRING_SIZE("parent "));
7887 break;
7889 case LINE_AUTHOR:
7890 parse_author_line(line + STRING_SIZE("author "),
7891 &commit->author, &commit->time);
7892 if (state->with_graph)
7893 graph_render_parents(graph);
7894 break;
7896 default:
7897 /* Fill in the commit title if it has not already been set. */
7898 if (*commit->title)
7899 break;
7901 /* Skip lines in the commit header. */
7902 if (state->in_header)
7903 break;
7905 /* Require titles to start with a non-space character at the
7906 * offset used by git log. */
7907 if (strncmp(line, " ", 4))
7908 break;
7909 line += 4;
7910 /* Well, if the title starts with a whitespace character,
7911 * try to be forgiving. Otherwise we end up with no title. */
7912 while (isspace(*line))
7913 line++;
7914 if (*line == '\0')
7915 break;
7916 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
7919 return TRUE;
7922 static enum request
7923 main_request(struct view *view, enum request request, struct line *line)
7925 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7926 ? OPEN_SPLIT : OPEN_DEFAULT;
7928 switch (request) {
7929 case REQ_NEXT:
7930 case REQ_PREVIOUS:
7931 if (view_is_displayed(view) && display[0] != view)
7932 return request;
7933 /* Do not pass navigation requests to the branch view
7934 * when the main view is maximized. (GH #38) */
7935 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
7937 case REQ_VIEW_DIFF:
7938 case REQ_ENTER:
7939 if (view_is_displayed(view) && display[0] != view)
7940 maximize_view(view, TRUE);
7942 if (line->type == LINE_STAT_UNSTAGED
7943 || line->type == LINE_STAT_STAGED) {
7944 struct view *diff = VIEW(REQ_VIEW_DIFF);
7945 const char *diff_staged_argv[] = {
7946 GIT_DIFF_STAGED(opt_encoding_arg,
7947 opt_diff_context_arg,
7948 opt_ignore_space_arg, NULL, NULL)
7950 const char *diff_unstaged_argv[] = {
7951 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7952 opt_diff_context_arg,
7953 opt_ignore_space_arg, NULL, NULL)
7955 const char **diff_argv = line->type == LINE_STAT_STAGED
7956 ? diff_staged_argv : diff_unstaged_argv;
7958 open_argv(view, diff, diff_argv, NULL, flags);
7959 break;
7962 open_view(view, REQ_VIEW_DIFF, flags);
7963 break;
7965 case REQ_REFRESH:
7966 load_refs();
7967 refresh_view(view);
7968 break;
7970 case REQ_JUMP_COMMIT:
7972 int lineno;
7974 for (lineno = 0; lineno < view->lines; lineno++) {
7975 struct commit *commit = view->line[lineno].data;
7977 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7978 select_view_line(view, lineno);
7979 report_clear();
7980 return REQ_NONE;
7984 report("Unable to find commit '%s'", opt_search);
7985 break;
7987 default:
7988 return request;
7991 return REQ_NONE;
7994 static bool
7995 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
7997 struct ref_list *list;
7998 regmatch_t pmatch;
7999 size_t i;
8001 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8002 return FALSE;
8004 for (i = 0; i < list->size; i++) {
8005 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8006 return TRUE;
8009 return FALSE;
8012 static bool
8013 main_grep(struct view *view, struct line *line)
8015 struct commit *commit = line->data;
8016 const char *text[] = {
8017 commit->id,
8018 commit->title,
8019 mkauthor(commit->author, opt_author_width, opt_author),
8020 mkdate(&commit->time, opt_date),
8021 NULL
8024 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8027 static void
8028 main_select(struct view *view, struct line *line)
8030 struct commit *commit = line->data;
8032 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8033 string_ncopy(view->ref, commit->title, strlen(commit->title));
8034 else
8035 string_copy_rev(view->ref, commit->id);
8036 string_copy_rev(ref_commit, commit->id);
8039 static struct view_ops main_ops = {
8040 "commit",
8041 { "main" },
8042 VIEW_STDIN | VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER,
8043 sizeof(struct main_state),
8044 main_open,
8045 main_read,
8046 main_draw,
8047 main_request,
8048 main_grep,
8049 main_select,
8050 main_done,
8053 static bool
8054 stash_open(struct view *view, enum open_flags flags)
8056 static const char *stash_argv[] = { "git", "stash", "list",
8057 opt_encoding_arg, "--no-color", "--pretty=raw", NULL };
8059 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8062 static bool
8063 stash_read(struct view *view, char *line)
8065 struct main_state *state = view->private;
8066 struct commit *commit = &state->current;
8068 if (!state->added_changes_commits) {
8069 state->added_changes_commits = TRUE;
8070 state->with_graph = FALSE;
8073 if (commit && line && get_line_type(line) == LINE_PP_REFLOG) {
8074 int id_width = STRING_SIZE("stash@{}") + count_digits(view->lines);
8076 if (state->id_width < id_width) {
8077 state->id_width = id_width;
8078 if (opt_show_id)
8079 view->force_redraw = TRUE;
8083 return main_read(view, line);
8086 static void
8087 stash_select(struct view *view, struct line *line)
8089 main_select(view, line);
8090 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8091 string_copy(view->ref, ref_stash);
8094 static struct view_ops stash_ops = {
8095 "stash",
8096 { "stash" },
8097 VIEW_SEND_CHILD_ENTER,
8098 sizeof(struct main_state),
8099 stash_open,
8100 stash_read,
8101 main_draw,
8102 main_request,
8103 main_grep,
8104 stash_select,
8108 * Status management
8111 /* Whether or not the curses interface has been initialized. */
8112 static bool cursed = FALSE;
8114 /* Terminal hacks and workarounds. */
8115 static bool use_scroll_redrawwin;
8116 static bool use_scroll_status_wclear;
8118 /* The status window is used for polling keystrokes. */
8119 static WINDOW *status_win;
8121 /* Reading from the prompt? */
8122 static bool input_mode = FALSE;
8124 static bool status_empty = FALSE;
8126 /* Update status and title window. */
8127 static void
8128 report(const char *msg, ...)
8130 struct view *view = display[current_view];
8132 if (input_mode)
8133 return;
8135 if (!view) {
8136 char buf[SIZEOF_STR];
8137 int retval;
8139 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8140 die("%s", buf);
8143 if (!status_empty || *msg) {
8144 va_list args;
8146 va_start(args, msg);
8148 wmove(status_win, 0, 0);
8149 if (view->has_scrolled && use_scroll_status_wclear)
8150 wclear(status_win);
8151 if (*msg) {
8152 vwprintw(status_win, msg, args);
8153 status_empty = FALSE;
8154 } else {
8155 status_empty = TRUE;
8157 wclrtoeol(status_win);
8158 wnoutrefresh(status_win);
8160 va_end(args);
8163 update_view_title(view);
8166 static void
8167 init_display(void)
8169 const char *term;
8170 int x, y;
8172 /* Initialize the curses library */
8173 if (isatty(STDIN_FILENO)) {
8174 cursed = !!initscr();
8175 opt_tty = stdin;
8176 } else {
8177 /* Leave stdin and stdout alone when acting as a pager. */
8178 opt_tty = fopen("/dev/tty", "r+");
8179 if (!opt_tty)
8180 die("Failed to open /dev/tty");
8181 cursed = !!newterm(NULL, opt_tty, opt_tty);
8184 if (!cursed)
8185 die("Failed to initialize curses");
8187 nonl(); /* Disable conversion and detect newlines from input. */
8188 cbreak(); /* Take input chars one at a time, no wait for \n */
8189 noecho(); /* Don't echo input */
8190 leaveok(stdscr, FALSE);
8192 if (has_colors())
8193 init_colors();
8195 getmaxyx(stdscr, y, x);
8196 status_win = newwin(1, x, y - 1, 0);
8197 if (!status_win)
8198 die("Failed to create status window");
8200 /* Enable keyboard mapping */
8201 keypad(status_win, TRUE);
8202 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8204 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8205 set_tabsize(opt_tab_size);
8206 #else
8207 TABSIZE = opt_tab_size;
8208 #endif
8210 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8211 if (term && !strcmp(term, "gnome-terminal")) {
8212 /* In the gnome-terminal-emulator, the message from
8213 * scrolling up one line when impossible followed by
8214 * scrolling down one line causes corruption of the
8215 * status line. This is fixed by calling wclear. */
8216 use_scroll_status_wclear = TRUE;
8217 use_scroll_redrawwin = FALSE;
8219 } else if (term && !strcmp(term, "xrvt-xpm")) {
8220 /* No problems with full optimizations in xrvt-(unicode)
8221 * and aterm. */
8222 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8224 } else {
8225 /* When scrolling in (u)xterm the last line in the
8226 * scrolling direction will update slowly. */
8227 use_scroll_redrawwin = TRUE;
8228 use_scroll_status_wclear = FALSE;
8232 static int
8233 get_input(int prompt_position)
8235 struct view *view;
8236 int i, key, cursor_y, cursor_x;
8238 if (prompt_position)
8239 input_mode = TRUE;
8241 while (TRUE) {
8242 bool loading = FALSE;
8244 foreach_view (view, i) {
8245 update_view(view);
8246 if (view_is_displayed(view) && view->has_scrolled &&
8247 use_scroll_redrawwin)
8248 redrawwin(view->win);
8249 view->has_scrolled = FALSE;
8250 if (view->pipe)
8251 loading = TRUE;
8254 /* Update the cursor position. */
8255 if (prompt_position) {
8256 getbegyx(status_win, cursor_y, cursor_x);
8257 cursor_x = prompt_position;
8258 } else {
8259 view = display[current_view];
8260 getbegyx(view->win, cursor_y, cursor_x);
8261 cursor_x = view->width - 1;
8262 cursor_y += view->pos.lineno - view->pos.offset;
8264 setsyx(cursor_y, cursor_x);
8266 /* Refresh, accept single keystroke of input */
8267 doupdate();
8268 nodelay(status_win, loading);
8269 key = wgetch(status_win);
8271 /* wgetch() with nodelay() enabled returns ERR when
8272 * there's no input. */
8273 if (key == ERR) {
8275 } else if (key == KEY_RESIZE) {
8276 int height, width;
8278 getmaxyx(stdscr, height, width);
8280 wresize(status_win, 1, width);
8281 mvwin(status_win, height - 1, 0);
8282 wnoutrefresh(status_win);
8283 resize_display();
8284 redraw_display(TRUE);
8286 } else {
8287 input_mode = FALSE;
8288 if (key == erasechar())
8289 key = KEY_BACKSPACE;
8290 return key;
8295 static char *
8296 prompt_input(const char *prompt, input_handler handler, void *data)
8298 enum input_status status = INPUT_OK;
8299 static char buf[SIZEOF_STR];
8300 size_t pos = 0;
8302 buf[pos] = 0;
8304 while (status == INPUT_OK || status == INPUT_SKIP) {
8305 int key;
8307 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8308 wclrtoeol(status_win);
8310 key = get_input(pos + 1);
8311 switch (key) {
8312 case KEY_RETURN:
8313 case KEY_ENTER:
8314 case '\n':
8315 status = pos ? INPUT_STOP : INPUT_CANCEL;
8316 break;
8318 case KEY_BACKSPACE:
8319 if (pos > 0)
8320 buf[--pos] = 0;
8321 else
8322 status = INPUT_CANCEL;
8323 break;
8325 case KEY_ESC:
8326 status = INPUT_CANCEL;
8327 break;
8329 default:
8330 if (pos >= sizeof(buf)) {
8331 report("Input string too long");
8332 return NULL;
8335 status = handler(data, buf, key);
8336 if (status == INPUT_OK)
8337 buf[pos++] = (char) key;
8341 /* Clear the status window */
8342 status_empty = FALSE;
8343 report_clear();
8345 if (status == INPUT_CANCEL)
8346 return NULL;
8348 buf[pos++] = 0;
8350 return buf;
8353 static enum input_status
8354 prompt_yesno_handler(void *data, char *buf, int c)
8356 if (c == 'y' || c == 'Y')
8357 return INPUT_STOP;
8358 if (c == 'n' || c == 'N')
8359 return INPUT_CANCEL;
8360 return INPUT_SKIP;
8363 static bool
8364 prompt_yesno(const char *prompt)
8366 char prompt2[SIZEOF_STR];
8368 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8369 return FALSE;
8371 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8374 static enum input_status
8375 read_prompt_handler(void *data, char *buf, int c)
8377 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8380 static char *
8381 read_prompt(const char *prompt)
8383 return prompt_input(prompt, read_prompt_handler, NULL);
8386 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8388 enum input_status status = INPUT_OK;
8389 int size = 0;
8391 while (items[size].text)
8392 size++;
8394 assert(size > 0);
8396 while (status == INPUT_OK) {
8397 const struct menu_item *item = &items[*selected];
8398 int key;
8399 int i;
8401 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8402 prompt, *selected + 1, size);
8403 if (item->hotkey)
8404 wprintw(status_win, "[%c] ", (char) item->hotkey);
8405 wprintw(status_win, "%s", item->text);
8406 wclrtoeol(status_win);
8408 key = get_input(COLS - 1);
8409 switch (key) {
8410 case KEY_RETURN:
8411 case KEY_ENTER:
8412 case '\n':
8413 status = INPUT_STOP;
8414 break;
8416 case KEY_LEFT:
8417 case KEY_UP:
8418 *selected = *selected - 1;
8419 if (*selected < 0)
8420 *selected = size - 1;
8421 break;
8423 case KEY_RIGHT:
8424 case KEY_DOWN:
8425 *selected = (*selected + 1) % size;
8426 break;
8428 case KEY_ESC:
8429 status = INPUT_CANCEL;
8430 break;
8432 default:
8433 for (i = 0; items[i].text; i++)
8434 if (items[i].hotkey == key) {
8435 *selected = i;
8436 status = INPUT_STOP;
8437 break;
8442 /* Clear the status window */
8443 status_empty = FALSE;
8444 report_clear();
8446 return status != INPUT_CANCEL;
8450 * Repository properties
8454 static void
8455 set_remote_branch(const char *name, const char *value, size_t valuelen)
8457 if (!strcmp(name, ".remote")) {
8458 string_ncopy(opt_remote, value, valuelen);
8460 } else if (*opt_remote && !strcmp(name, ".merge")) {
8461 size_t from = strlen(opt_remote);
8463 if (!prefixcmp(value, "refs/heads/"))
8464 value += STRING_SIZE("refs/heads/");
8466 if (!string_format_from(opt_remote, &from, "/%s", value))
8467 opt_remote[0] = 0;
8471 static void
8472 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
8474 const char *argv[SIZEOF_ARG] = { name, "=" };
8475 int argc = 1 + (cmd == option_set_command);
8476 enum option_code error;
8478 if (!argv_from_string(argv, &argc, value))
8479 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
8480 else
8481 error = cmd(argc, argv);
8483 if (error != OPT_OK)
8484 warn("Option 'tig.%s': %s", name, option_errors[error]);
8487 static void
8488 set_work_tree(const char *value)
8490 char cwd[SIZEOF_STR];
8492 if (!getcwd(cwd, sizeof(cwd)))
8493 die("Failed to get cwd path: %s", strerror(errno));
8494 if (chdir(cwd) < 0)
8495 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8496 if (chdir(opt_git_dir) < 0)
8497 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8498 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8499 die("Failed to get git path: %s", strerror(errno));
8500 if (chdir(value) < 0)
8501 die("Failed to chdir(%s): %s", value, strerror(errno));
8502 if (!getcwd(cwd, sizeof(cwd)))
8503 die("Failed to get cwd path: %s", strerror(errno));
8504 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8505 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8506 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8507 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8508 opt_is_inside_work_tree = TRUE;
8511 static void
8512 parse_git_color_option(enum line_type type, char *value)
8514 struct line_info *info = &line_info[type];
8515 const char *argv[SIZEOF_ARG];
8516 int argc = 0;
8517 bool first_color = TRUE;
8518 int i;
8520 if (!argv_from_string(argv, &argc, value))
8521 return;
8523 info->fg = COLOR_DEFAULT;
8524 info->bg = COLOR_DEFAULT;
8525 info->attr = 0;
8527 for (i = 0; i < argc; i++) {
8528 int attr = 0;
8530 if (set_attribute(&attr, argv[i])) {
8531 info->attr |= attr;
8533 } else if (set_color(&attr, argv[i])) {
8534 if (first_color)
8535 info->fg = attr;
8536 else
8537 info->bg = attr;
8538 first_color = FALSE;
8543 static void
8544 set_git_color_option(const char *name, char *value)
8546 static const struct enum_map color_option_map[] = {
8547 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8548 ENUM_MAP("branch.local", LINE_MAIN_REF),
8549 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8550 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8552 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8553 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8554 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8555 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8556 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8557 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8558 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8560 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8562 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8563 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8564 ENUM_MAP("status.added", LINE_STAT_STAGED),
8565 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8566 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8567 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8570 int type = LINE_NONE;
8572 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8573 parse_git_color_option(type, value);
8577 static void
8578 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8580 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
8581 opt_encoding_arg[0] = 0;
8584 static int
8585 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8587 if (!strcmp(name, "i18n.commitencoding"))
8588 set_encoding(&opt_encoding, value, FALSE);
8590 else if (!strcmp(name, "gui.encoding"))
8591 set_encoding(&opt_encoding, value, TRUE);
8593 else if (!strcmp(name, "core.editor"))
8594 string_ncopy(opt_editor, value, valuelen);
8596 else if (!strcmp(name, "core.worktree"))
8597 set_work_tree(value);
8599 else if (!strcmp(name, "core.abbrev"))
8600 parse_id(&opt_id_cols, value);
8602 else if (!prefixcmp(name, "tig.color."))
8603 set_repo_config_option(name + 10, value, option_color_command);
8605 else if (!prefixcmp(name, "tig.bind."))
8606 set_repo_config_option(name + 9, value, option_bind_command);
8608 else if (!prefixcmp(name, "tig."))
8609 set_repo_config_option(name + 4, value, option_set_command);
8611 else if (!prefixcmp(name, "color."))
8612 set_git_color_option(name + STRING_SIZE("color."), value);
8614 else if (*opt_head && !prefixcmp(name, "branch.") &&
8615 !strncmp(name + 7, opt_head, strlen(opt_head)))
8616 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8618 return OK;
8621 static int
8622 load_git_config(void)
8624 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8626 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8629 #define REPO_INFO_GIT_DIR "--git-dir"
8630 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8631 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8632 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8633 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8634 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8636 struct repo_info_state {
8637 const char **argv;
8638 char head_id[SIZEOF_REV];
8641 static int
8642 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8644 struct repo_info_state *state = data;
8645 const char *arg = *state->argv ? *state->argv++ : "";
8647 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8648 string_ncopy(opt_git_dir, name, namelen);
8650 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8651 /* This can be 3 different values depending on the
8652 * version of git being used. If git-rev-parse does not
8653 * understand --is-inside-work-tree it will simply echo
8654 * the option else either "true" or "false" is printed.
8655 * Default to true for the unknown case. */
8656 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8658 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8659 string_ncopy(opt_cdup, name, namelen);
8661 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8662 string_ncopy(opt_prefix, name, namelen);
8664 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8665 string_ncopy(state->head_id, name, namelen);
8667 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8668 if (!prefixcmp(name, "refs/heads/")) {
8669 char *offset = name + STRING_SIZE("refs/heads/");
8671 string_ncopy(opt_head, offset, strlen(offset) + 1);
8672 add_ref(state->head_id, name, opt_remote, opt_head);
8674 state->argv++;
8677 return OK;
8680 static int
8681 load_repo_info(void)
8683 const char *rev_parse_argv[] = {
8684 "git", "rev-parse", REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8685 REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE, REPO_INFO_SHOW_CDUP,
8686 REPO_INFO_SHOW_PREFIX, NULL
8688 struct repo_info_state state = { rev_parse_argv + 2 };
8690 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8695 * Main
8698 static const char usage[] =
8699 "tig " TIG_VERSION " (" __DATE__ ")\n"
8700 "\n"
8701 "Usage: tig [options] [revs] [--] [paths]\n"
8702 " or: tig log [options] [revs] [--] [paths]\n"
8703 " or: tig show [options] [revs] [--] [paths]\n"
8704 " or: tig blame [options] [rev] [--] path\n"
8705 " or: tig stash\n"
8706 " or: tig status\n"
8707 " or: tig < [git command output]\n"
8708 "\n"
8709 "Options:\n"
8710 " +<number> Select line <number> in the first view\n"
8711 " -v, --version Show version and exit\n"
8712 " -h, --help Show help message and exit";
8714 static void TIG_NORETURN
8715 quit(int sig)
8717 if (sig)
8718 signal(sig, SIG_DFL);
8720 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8721 if (cursed)
8722 endwin();
8723 exit(0);
8726 static void TIG_NORETURN
8727 die(const char *err, ...)
8729 va_list args;
8731 endwin();
8733 va_start(args, err);
8734 fputs("tig: ", stderr);
8735 vfprintf(stderr, err, args);
8736 fputs("\n", stderr);
8737 va_end(args);
8739 exit(1);
8742 static void
8743 warn(const char *msg, ...)
8745 va_list args;
8747 va_start(args, msg);
8748 fputs("tig warning: ", stderr);
8749 vfprintf(stderr, msg, args);
8750 fputs("\n", stderr);
8751 va_end(args);
8754 static int
8755 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8757 const char ***filter_args = data;
8759 return argv_append(filter_args, name) ? OK : ERR;
8762 static void
8763 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8765 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8766 const char **all_argv = NULL;
8768 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8769 !argv_append_array(&all_argv, argv) ||
8770 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8771 die("Failed to split arguments");
8772 argv_free(all_argv);
8773 free(all_argv);
8776 static bool
8777 is_rev_flag(const char *flag)
8779 static const char *rev_flags[] = { GIT_REV_FLAGS };
8780 int i;
8782 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8783 if (!strcmp(flag, rev_flags[i]))
8784 return TRUE;
8786 return FALSE;
8789 static void
8790 filter_options(const char *argv[], bool blame)
8792 const char **flags = NULL;
8794 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8795 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8797 if (flags) {
8798 int next, flags_pos;
8800 for (next = flags_pos = 0; flags && flags[next]; next++) {
8801 const char *flag = flags[next];
8803 if (is_rev_flag(flag))
8804 argv_append(&opt_rev_argv, flag);
8805 else
8806 flags[flags_pos++] = flag;
8809 flags[flags_pos] = NULL;
8811 if (blame)
8812 opt_blame_argv = flags;
8813 else
8814 opt_diff_argv = flags;
8817 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8820 static enum request
8821 parse_options(int argc, const char *argv[])
8823 enum request request;
8824 const char *subcommand;
8825 bool seen_dashdash = FALSE;
8826 const char **filter_argv = NULL;
8827 int i;
8829 opt_stdin = !isatty(STDIN_FILENO);
8830 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8832 if (argc <= 1)
8833 return request;
8835 subcommand = argv[1];
8836 if (!strcmp(subcommand, "status")) {
8837 request = REQ_VIEW_STATUS;
8839 } else if (!strcmp(subcommand, "blame")) {
8840 request = REQ_VIEW_BLAME;
8842 } else if (!strcmp(subcommand, "show")) {
8843 request = REQ_VIEW_DIFF;
8845 } else if (!strcmp(subcommand, "log")) {
8846 request = REQ_VIEW_LOG;
8848 } else if (!strcmp(subcommand, "stash")) {
8849 request = REQ_VIEW_STASH;
8851 } else {
8852 subcommand = NULL;
8855 for (i = 1 + !!subcommand; i < argc; i++) {
8856 const char *opt = argv[i];
8858 // stop parsing our options after -- and let rev-parse handle the rest
8859 if (!seen_dashdash) {
8860 if (!strcmp(opt, "--")) {
8861 seen_dashdash = TRUE;
8862 continue;
8864 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8865 printf("tig version %s\n", TIG_VERSION);
8866 quit(0);
8868 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8869 printf("%s\n", usage);
8870 quit(0);
8872 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8873 opt_lineno = atoi(opt + 1);
8874 continue;
8879 if (!argv_append(&filter_argv, opt))
8880 die("command too long");
8883 if (filter_argv)
8884 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8886 /* Finish validating and setting up blame options */
8887 if (request == REQ_VIEW_BLAME) {
8888 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8889 die("invalid number of options to blame\n\n%s", usage);
8891 if (opt_rev_argv) {
8892 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8895 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8897 } else if (request == REQ_VIEW_PAGER) {
8898 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8899 if (!strcmp("--stdin", opt_rev_argv[i])) {
8900 request = REQ_VIEW_MAIN;
8901 break;
8906 return request;
8909 static enum request
8910 run_prompt_command(struct view *view, char *cmd) {
8911 enum request request;
8913 if (cmd && string_isnumber(cmd)) {
8914 int lineno = view->pos.lineno + 1;
8916 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8917 select_view_line(view, lineno - 1);
8918 report_clear();
8919 } else {
8920 report("Unable to parse '%s' as a line number", cmd);
8922 } else if (cmd && iscommit(cmd)) {
8923 string_ncopy(opt_search, cmd, strlen(cmd));
8925 request = view_request(view, REQ_JUMP_COMMIT);
8926 if (request == REQ_JUMP_COMMIT) {
8927 report("Jumping to commits is not supported by the '%s' view", view->name);
8930 } else if (cmd && strlen(cmd) == 1) {
8931 request = get_keybinding(&view->ops->keymap, cmd[0]);
8932 return request;
8934 } else if (cmd && cmd[0] == '!') {
8935 struct view *next = VIEW(REQ_VIEW_PAGER);
8936 const char *argv[SIZEOF_ARG];
8937 int argc = 0;
8939 cmd++;
8940 /* When running random commands, initially show the
8941 * command in the title. However, it maybe later be
8942 * overwritten if a commit line is selected. */
8943 string_ncopy(next->ref, cmd, strlen(cmd));
8945 if (!argv_from_string(argv, &argc, cmd)) {
8946 report("Too many arguments");
8947 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
8948 report("Argument formatting failed");
8949 } else {
8950 next->dir = NULL;
8951 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8954 } else if (cmd) {
8955 request = get_request(cmd);
8956 if (request != REQ_UNKNOWN)
8957 return request;
8959 char *args = strchr(cmd, ' ');
8960 if (args) {
8961 *args++ = 0;
8962 if (set_option(cmd, args) == OPT_OK) {
8963 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
8964 if (!strcmp(cmd, "color"))
8965 init_colors();
8968 return request;
8970 return REQ_NONE;
8974 main(int argc, const char *argv[])
8976 const char *codeset = ENCODING_UTF8;
8977 enum request request = parse_options(argc, argv);
8978 struct view *view;
8979 int i;
8981 signal(SIGINT, quit);
8982 signal(SIGQUIT, quit);
8983 signal(SIGPIPE, SIG_IGN);
8985 if (setlocale(LC_ALL, "")) {
8986 codeset = nl_langinfo(CODESET);
8989 foreach_view(view, i) {
8990 add_keymap(&view->ops->keymap);
8993 if (load_repo_info() == ERR)
8994 die("Failed to load repo info.");
8996 if (load_options() == ERR)
8997 die("Failed to load user config.");
8999 if (load_git_config() == ERR)
9000 die("Failed to load repo config.");
9002 /* Require a git repository unless when running in pager mode. */
9003 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9004 die("Not a git repository");
9006 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9007 char translit[SIZEOF_STR];
9009 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9010 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9011 else
9012 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9013 if (opt_iconv_out == ICONV_NONE)
9014 die("Failed to initialize character set conversion");
9017 if (load_refs() == ERR)
9018 die("Failed to load refs.");
9020 init_display();
9022 while (view_driver(display[current_view], request)) {
9023 int key = get_input(0);
9025 if (key == KEY_ESC)
9026 key = get_input(0) + 0x80;
9028 view = display[current_view];
9029 request = get_keybinding(&view->ops->keymap, key);
9031 /* Some low-level request handling. This keeps access to
9032 * status_win restricted. */
9033 switch (request) {
9034 case REQ_NONE:
9035 report("Unknown key, press %s for help",
9036 get_view_key(view, REQ_VIEW_HELP));
9037 break;
9038 case REQ_PROMPT:
9040 char *cmd = read_prompt(":");
9041 request = run_prompt_command(view, cmd);
9042 break;
9044 case REQ_SEARCH:
9045 case REQ_SEARCH_BACK:
9047 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9048 char *search = read_prompt(prompt);
9050 if (search)
9051 string_ncopy(opt_search, search, strlen(search));
9052 else if (*opt_search)
9053 request = request == REQ_SEARCH ?
9054 REQ_FIND_NEXT :
9055 REQ_FIND_PREV;
9056 else
9057 request = REQ_NONE;
9058 break;
9060 default:
9061 break;
9065 quit(0);
9067 return 0;
9070 /* vim: set ts=8 sw=8 noexpandtab: */