Disable graph drawing for reverse log order
[tig.git] / tig.c
blob35346483a02eec36647dddd49528f3ce5882eec8
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 "util.h"
18 #include "io.h"
19 #include "refs.h"
20 #include "graph.h"
21 #include "git.h"
23 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
24 #define report_clear() report("%s", "")
27 enum input_status {
28 INPUT_OK,
29 INPUT_SKIP,
30 INPUT_STOP,
31 INPUT_CANCEL
34 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
36 static char *prompt_input(const char *prompt, input_handler handler, void *data);
37 static bool prompt_yesno(const char *prompt);
38 static char *read_prompt(const char *prompt);
40 struct menu_item {
41 int hotkey;
42 const char *text;
43 void *data;
46 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
48 #define VERTICAL_SPLIT_ENUM(_) \
49 _(VERTICAL_SPLIT, HORIZONTAL), \
50 _(VERTICAL_SPLIT, VERTICAL), \
51 _(VERTICAL_SPLIT, AUTO)
53 DEFINE_ENUM(vertical_split, VERTICAL_SPLIT_ENUM);
55 #define GRAPHIC_ENUM(_) \
56 _(GRAPHIC, ASCII), \
57 _(GRAPHIC, DEFAULT), \
58 _(GRAPHIC, UTF_8)
60 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
62 #define DATE_ENUM(_) \
63 _(DATE, NO), \
64 _(DATE, DEFAULT), \
65 _(DATE, LOCAL), \
66 _(DATE, RELATIVE), \
67 _(DATE, SHORT)
69 DEFINE_ENUM(date, DATE_ENUM);
71 struct time {
72 time_t sec;
73 int tz;
76 static inline int timecmp(const struct time *t1, const struct time *t2)
78 return t1->sec - t2->sec;
81 static const char *
82 mkdate(const struct time *time, enum date date)
84 static char buf[DATE_WIDTH + 1];
85 static const struct enum_map_entry reldate[] = {
86 { "second", 1, 60 * 2 },
87 { "minute", 60, 60 * 60 * 2 },
88 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
89 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
90 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
91 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
92 { "year", 60 * 60 * 24 * 365, 0 },
94 struct tm tm;
96 if (!date || !time || !time->sec)
97 return "";
99 if (date == DATE_RELATIVE) {
100 struct timeval now;
101 time_t date = time->sec + time->tz;
102 time_t seconds;
103 int i;
105 gettimeofday(&now, NULL);
106 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
107 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
108 if (seconds >= reldate[i].value && reldate[i].value)
109 continue;
111 seconds /= reldate[i].namelen;
112 if (!string_format(buf, "%ld %s%s %s",
113 seconds, reldate[i].name,
114 seconds > 1 ? "s" : "",
115 now.tv_sec >= date ? "ago" : "ahead"))
116 break;
117 return buf;
121 if (date == DATE_LOCAL) {
122 time_t date = time->sec + time->tz;
123 localtime_r(&date, &tm);
125 else {
126 gmtime_r(&time->sec, &tm);
128 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
131 #define FILE_SIZE_ENUM(_) \
132 _(FILE_SIZE, NO), \
133 _(FILE_SIZE, DEFAULT), \
134 _(FILE_SIZE, UNITS)
136 DEFINE_ENUM(file_size, FILE_SIZE_ENUM);
138 static const char *
139 mkfilesize(unsigned long size, enum file_size format)
141 static char buf[64 + 1];
142 static const char relsize[] = {
143 'B', 'K', 'M', 'G', 'T', 'P'
146 if (!format)
147 return "";
149 if (format == FILE_SIZE_UNITS) {
150 const char *fmt = "%.0f%c";
151 double rsize = size;
152 int i;
154 for (i = 0; i < ARRAY_SIZE(relsize); i++) {
155 if (rsize > 1024.0 && i + 1 < ARRAY_SIZE(relsize)) {
156 rsize /= 1024;
157 continue;
160 size = rsize * 10;
161 if (size % 10 > 0)
162 fmt = "%.1f%c";
164 return string_format(buf, fmt, rsize, relsize[i])
165 ? buf : NULL;
169 return string_format(buf, "%ld", size) ? buf : NULL;
172 #define AUTHOR_ENUM(_) \
173 _(AUTHOR, NO), \
174 _(AUTHOR, FULL), \
175 _(AUTHOR, ABBREVIATED), \
176 _(AUTHOR, EMAIL), \
177 _(AUTHOR, EMAIL_USER)
179 DEFINE_ENUM(author, AUTHOR_ENUM);
181 struct ident {
182 const char *name;
183 const char *email;
186 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
188 static inline int
189 ident_compare(const struct ident *i1, const struct ident *i2)
191 if (!i1 || !i2)
192 return (!!i1) - (!!i2);
193 if (!i1->name || !i2->name)
194 return (!!i1->name) - (!!i2->name);
195 return strcmp(i1->name, i2->name);
198 static const char *
199 get_author_initials(const char *author)
201 static char initials[AUTHOR_WIDTH * 6 + 1];
202 size_t pos = 0;
203 const char *end = strchr(author, '\0');
205 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
207 memset(initials, 0, sizeof(initials));
208 while (author < end) {
209 unsigned char bytes;
210 size_t i;
212 while (author < end && is_initial_sep(*author))
213 author++;
215 bytes = utf8_char_length(author, end);
216 if (bytes >= sizeof(initials) - 1 - pos)
217 break;
218 while (bytes--) {
219 initials[pos++] = *author++;
222 i = pos;
223 while (author < end && !is_initial_sep(*author)) {
224 bytes = utf8_char_length(author, end);
225 if (bytes >= sizeof(initials) - 1 - i) {
226 while (author < end && !is_initial_sep(*author))
227 author++;
228 break;
230 while (bytes--) {
231 initials[i++] = *author++;
235 initials[i++] = 0;
238 return initials;
241 static const char *
242 get_email_user(const char *email)
244 static char user[AUTHOR_WIDTH * 6 + 1];
245 const char *end = strchr(email, '@');
246 int length = end ? end - email : strlen(email);
248 string_format(user, "%.*s%c", length, email, 0);
249 return user;
252 #define author_trim(cols) (cols == 0 || cols > 10)
254 static const char *
255 mkauthor(const struct ident *ident, int cols, enum author author)
257 bool trim = author_trim(cols);
258 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
260 if (author == AUTHOR_NO || !ident)
261 return "";
262 if (author == AUTHOR_EMAIL && ident->email)
263 return ident->email;
264 if (author == AUTHOR_EMAIL_USER && ident->email)
265 return get_email_user(ident->email);
266 if (abbreviate && ident->name)
267 return get_author_initials(ident->name);
268 return ident->name;
271 static const char *
272 mkmode(mode_t mode)
274 if (S_ISDIR(mode))
275 return "drwxr-xr-x";
276 else if (S_ISLNK(mode))
277 return "lrwxrwxrwx";
278 else if (S_ISGITLINK(mode))
279 return "m---------";
280 else if (S_ISREG(mode) && mode & S_IXUSR)
281 return "-rwxr-xr-x";
282 else if (S_ISREG(mode))
283 return "-rw-r--r--";
284 else
285 return "----------";
288 #define FILENAME_ENUM(_) \
289 _(FILENAME, NO), \
290 _(FILENAME, ALWAYS), \
291 _(FILENAME, AUTO)
293 DEFINE_ENUM(filename, FILENAME_ENUM);
295 #define IGNORE_SPACE_ENUM(_) \
296 _(IGNORE_SPACE, NO), \
297 _(IGNORE_SPACE, ALL), \
298 _(IGNORE_SPACE, SOME), \
299 _(IGNORE_SPACE, AT_EOL)
301 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
303 #define COMMIT_ORDER_ENUM(_) \
304 _(COMMIT_ORDER, DEFAULT), \
305 _(COMMIT_ORDER, TOPO), \
306 _(COMMIT_ORDER, DATE), \
307 _(COMMIT_ORDER, REVERSE)
309 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
311 #define VIEW_INFO(_) \
312 _(MAIN, main, ref_head), \
313 _(DIFF, diff, ref_commit), \
314 _(LOG, log, ref_head), \
315 _(TREE, tree, ref_commit), \
316 _(BLOB, blob, ref_blob), \
317 _(BLAME, blame, ref_commit), \
318 _(BRANCH, branch, ref_head), \
319 _(HELP, help, ""), \
320 _(PAGER, pager, ""), \
321 _(STATUS, status, "status"), \
322 _(STAGE, stage, ref_status), \
323 _(STASH, stash, ref_stash)
326 * User requests
329 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
331 #define REQ_INFO \
332 REQ_GROUP("View switching") \
333 VIEW_INFO(VIEW_REQ), \
335 REQ_GROUP("View manipulation") \
336 REQ_(ENTER, "Enter current line and scroll"), \
337 REQ_(BACK, "Go back to the previous view state"), \
338 REQ_(NEXT, "Move to next"), \
339 REQ_(PREVIOUS, "Move to previous"), \
340 REQ_(PARENT, "Move to parent"), \
341 REQ_(VIEW_NEXT, "Move focus to next view"), \
342 REQ_(REFRESH, "Reload and refresh"), \
343 REQ_(MAXIMIZE, "Maximize the current view"), \
344 REQ_(VIEW_CLOSE, "Close the current view"), \
345 REQ_(QUIT, "Close all views and quit"), \
347 REQ_GROUP("View specific requests") \
348 REQ_(STATUS_UPDATE, "Update file status"), \
349 REQ_(STATUS_REVERT, "Revert file changes"), \
350 REQ_(STATUS_MERGE, "Merge file using external tool"), \
351 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
352 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
353 REQ_(STAGE_SPLIT_CHUNK, "Split the current chunk"), \
354 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
355 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
357 REQ_GROUP("Cursor navigation") \
358 REQ_(MOVE_UP, "Move cursor one line up"), \
359 REQ_(MOVE_DOWN, "Move cursor one line down"), \
360 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
361 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
362 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
363 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
365 REQ_GROUP("Scrolling") \
366 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
367 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
368 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
369 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
370 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
371 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
372 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
374 REQ_GROUP("Searching") \
375 REQ_(SEARCH, "Search the view"), \
376 REQ_(SEARCH_BACK, "Search backwards in the view"), \
377 REQ_(FIND_NEXT, "Find next search match"), \
378 REQ_(FIND_PREV, "Find previous search match"), \
380 REQ_GROUP("Option manipulation") \
381 REQ_(OPTIONS, "Open option menu"), \
382 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
383 REQ_(TOGGLE_DATE, "Toggle date display"), \
384 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
385 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
386 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
387 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
388 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
389 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
390 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
391 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
392 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
393 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
394 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
395 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
396 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
397 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
398 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
399 REQ_(TOGGLE_VERTICAL_SPLIT, "Toggle vertical split"), \
401 REQ_GROUP("Misc") \
402 REQ_(PROMPT, "Bring up the prompt"), \
403 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
404 REQ_(SHOW_VERSION, "Show version information"), \
405 REQ_(STOP_LOADING, "Stop all loading views"), \
406 REQ_(EDIT, "Open in editor"), \
407 REQ_(NONE, "Do nothing")
410 /* User action requests. */
411 enum request {
412 #define REQ_GROUP(help)
413 #define REQ_(req, help) REQ_##req
415 /* Offset all requests to avoid conflicts with ncurses getch values. */
416 REQ_UNKNOWN = KEY_MAX + 1,
417 REQ_OFFSET,
418 REQ_INFO,
420 /* Internal requests. */
421 REQ_JUMP_COMMIT,
422 REQ_SCROLL_WHEEL_DOWN,
423 REQ_SCROLL_WHEEL_UP,
425 /* Start of the run request IDs */
426 REQ_RUN_REQUESTS
428 #undef REQ_GROUP
429 #undef REQ_
432 struct request_info {
433 enum request request;
434 const char *name;
435 int namelen;
436 const char *help;
439 static const struct request_info req_info[] = {
440 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
441 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
442 REQ_INFO
443 #undef REQ_GROUP
444 #undef REQ_
447 static enum request
448 get_request(const char *name)
450 int namelen = strlen(name);
451 int i;
453 for (i = 0; i < ARRAY_SIZE(req_info); i++)
454 if (enum_equals(req_info[i], name, namelen))
455 return req_info[i].request;
457 return REQ_UNKNOWN;
462 * Options
465 /* Option and state variables. */
466 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
467 static enum date opt_date = DATE_DEFAULT;
468 static enum author opt_author = AUTHOR_FULL;
469 static enum filename opt_filename = FILENAME_AUTO;
470 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
471 static bool opt_rev_graph = TRUE;
472 static bool opt_line_number = FALSE;
473 static bool opt_show_refs = TRUE;
474 static bool opt_show_changes = TRUE;
475 static bool opt_untracked_dirs_content = TRUE;
476 static bool opt_read_git_colors = TRUE;
477 static bool opt_wrap_lines = FALSE;
478 static bool opt_ignore_case = FALSE;
479 static bool opt_focus_child = TRUE;
480 static int opt_diff_context = 3;
481 static char opt_diff_context_arg[9] = "";
482 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
483 static char opt_ignore_space_arg[22] = "";
484 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
485 static char opt_commit_order_arg[22] = "";
486 static bool opt_notes = TRUE;
487 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
488 static int opt_num_interval = 5;
489 static double opt_hscroll = 0.50;
490 static double opt_scale_split_view = 2.0 / 3.0;
491 static double opt_scale_vsplit_view = 0.5;
492 static enum vertical_split opt_vertical_split = VERTICAL_SPLIT_AUTO;
493 static int opt_tab_size = 8;
494 static int opt_author_width = AUTHOR_WIDTH;
495 static int opt_filename_width = FILENAME_WIDTH;
496 static char opt_path[SIZEOF_STR] = "";
497 static char opt_file[SIZEOF_STR] = "";
498 static char opt_ref[SIZEOF_REF] = "";
499 static unsigned long opt_goto_line = 0;
500 static char opt_head[SIZEOF_REF] = "";
501 static char opt_remote[SIZEOF_REF] = "";
502 static iconv_t opt_iconv_out = ICONV_NONE;
503 static char opt_search[SIZEOF_STR] = "";
504 static char opt_cdup[SIZEOF_STR] = "";
505 static char opt_prefix[SIZEOF_STR] = "";
506 static char opt_git_dir[SIZEOF_STR] = "";
507 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
508 static char opt_editor[SIZEOF_STR] = "";
509 static bool opt_editor_lineno = TRUE;
510 static FILE *opt_tty = NULL;
511 static const char **opt_diff_argv = NULL;
512 static const char **opt_rev_argv = NULL;
513 static const char **opt_file_argv = NULL;
514 static const char **opt_blame_argv = NULL;
515 static int opt_lineno = 0;
516 static bool opt_show_id = FALSE;
517 static int opt_id_cols = ID_WIDTH;
518 static bool opt_file_filter = TRUE;
519 static bool opt_show_title_overflow = FALSE;
520 static int opt_title_overflow = 50;
521 static char opt_env_lines[64] = "";
522 static char opt_env_columns[64] = "";
523 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
524 static bool opt_mouse = FALSE;
525 static int opt_scroll_wheel_lines = 3;
527 #define is_initial_commit() (!get_ref_head())
528 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
530 static bool
531 vertical_split_is_enabled(void)
533 if (opt_vertical_split == VERTICAL_SPLIT_AUTO) {
534 int height, width;
536 getmaxyx(stdscr, height, width);
537 return width * opt_scale_vsplit_view > (height - 1) * 2;
540 return opt_vertical_split == VERTICAL_SPLIT_VERTICAL;
543 static inline int
544 load_refs(bool force)
546 static bool loaded = FALSE;
548 if (force)
549 opt_head[0] = 0;
550 else if (loaded)
551 return OK;
553 loaded = TRUE;
554 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
557 static inline void
558 update_diff_context_arg(int diff_context)
560 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
561 string_ncopy(opt_diff_context_arg, "-U3", 3);
564 #define ENUM_ARG(enum_name, arg_string) ENUM_MAP_ENTRY(arg_string, enum_name)
566 static const struct enum_map_entry ignore_space_arg_map[] = {
567 ENUM_ARG(IGNORE_SPACE_NO, ""),
568 ENUM_ARG(IGNORE_SPACE_ALL, "--ignore-all-space"),
569 ENUM_ARG(IGNORE_SPACE_SOME, "--ignore-space-change"),
570 ENUM_ARG(IGNORE_SPACE_AT_EOL, "--ignore-space-at-eol"),
573 static inline void
574 update_ignore_space_arg()
576 enum_copy_name(opt_ignore_space_arg, ignore_space_arg_map[opt_ignore_space]);
579 static const struct enum_map_entry commit_order_arg_map[] = {
580 ENUM_ARG(COMMIT_ORDER_DEFAULT, ""),
581 ENUM_ARG(COMMIT_ORDER_TOPO, "--topo-order"),
582 ENUM_ARG(COMMIT_ORDER_DATE, "--date-order"),
583 ENUM_ARG(COMMIT_ORDER_REVERSE, "--reverse"),
586 static inline void
587 update_commit_order_arg()
589 enum_copy_name(opt_commit_order_arg, commit_order_arg_map[opt_commit_order]);
592 static inline void
593 update_notes_arg()
595 if (opt_notes) {
596 string_copy(opt_notes_arg, "--show-notes");
597 } else {
598 /* Notes are disabled by default when passing --pretty args. */
599 string_copy(opt_notes_arg, "");
604 * Line-oriented content detection.
607 #define LINE_INFO \
608 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
609 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
610 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
611 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
612 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
613 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
614 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
615 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
616 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
617 LINE(DIFF_DELETED_FILE_MODE, \
618 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
619 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
620 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
621 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
622 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
623 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
624 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
625 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
626 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
627 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
628 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
629 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
630 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
631 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
632 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
633 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
634 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
635 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
636 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
637 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
638 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
639 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
640 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
641 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
642 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
644 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
645 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
646 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
647 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
648 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
649 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
650 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
651 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
652 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
653 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
654 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
655 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
656 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
657 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
658 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
659 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
660 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
661 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
662 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
663 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
664 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
665 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
666 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
667 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
668 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
669 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
670 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
671 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
672 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
673 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
674 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
675 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
676 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
677 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
678 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
679 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
680 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
681 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
682 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
683 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
684 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
685 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
686 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
688 enum line_type {
689 #define LINE(type, line, fg, bg, attr) \
690 LINE_##type
691 LINE_INFO,
692 LINE_NONE
693 #undef LINE
696 struct line_info {
697 const char *name; /* Option name. */
698 int namelen; /* Size of option name. */
699 const char *line; /* The start of line to match. */
700 int linelen; /* Size of string to match. */
701 int fg, bg, attr; /* Color and text attributes for the lines. */
702 int color_pair;
705 static struct line_info line_info[] = {
706 #define LINE(type, line, fg, bg, attr) \
707 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
708 LINE_INFO
709 #undef LINE
712 static struct line_info **color_pair;
713 static size_t color_pairs;
715 static struct line_info *custom_color;
716 static size_t custom_colors;
718 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
719 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
721 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
722 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
724 /* Color IDs must be 1 or higher. [GH #15] */
725 #define COLOR_ID(line_type) ((line_type) + 1)
727 static enum line_type
728 get_line_type(const char *line)
730 int linelen = strlen(line);
731 enum line_type type;
733 for (type = 0; type < custom_colors; type++)
734 /* Case insensitive search matches Signed-off-by lines better. */
735 if (linelen >= custom_color[type].linelen &&
736 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
737 return TO_CUSTOM_COLOR_TYPE(type);
739 for (type = 0; type < ARRAY_SIZE(line_info); type++)
740 /* Case insensitive search matches Signed-off-by lines better. */
741 if (linelen >= line_info[type].linelen &&
742 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
743 return type;
745 return LINE_DEFAULT;
748 static enum line_type
749 get_line_type_from_ref(const struct ref *ref)
751 if (ref->head)
752 return LINE_MAIN_HEAD;
753 else if (ref->ltag)
754 return LINE_MAIN_LOCAL_TAG;
755 else if (ref->tag)
756 return LINE_MAIN_TAG;
757 else if (ref->tracked)
758 return LINE_MAIN_TRACKED;
759 else if (ref->remote)
760 return LINE_MAIN_REMOTE;
761 else if (ref->replace)
762 return LINE_MAIN_REPLACE;
764 return LINE_MAIN_REF;
767 static inline struct line_info *
768 get_line(enum line_type type)
770 if (type > LINE_NONE) {
771 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
772 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
773 } else {
774 assert(type < ARRAY_SIZE(line_info));
775 return &line_info[type];
779 static inline int
780 get_line_color(enum line_type type)
782 return COLOR_ID(get_line(type)->color_pair);
785 static inline int
786 get_line_attr(enum line_type type)
788 struct line_info *info = get_line(type);
790 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
793 static struct line_info *
794 get_line_info(const char *name)
796 size_t namelen = strlen(name);
797 enum line_type type;
799 for (type = 0; type < ARRAY_SIZE(line_info); type++)
800 if (enum_equals(line_info[type], name, namelen))
801 return &line_info[type];
803 return NULL;
806 static struct line_info *
807 add_custom_color(const char *quoted_line)
809 struct line_info *info;
810 char *line;
811 size_t linelen;
813 if (!realloc_custom_color(&custom_color, custom_colors, 1))
814 die("Failed to alloc custom line info");
816 linelen = strlen(quoted_line) - 1;
817 line = malloc(linelen);
818 if (!line)
819 return NULL;
821 strncpy(line, quoted_line + 1, linelen);
822 line[linelen - 1] = 0;
824 info = &custom_color[custom_colors++];
825 info->name = info->line = line;
826 info->namelen = info->linelen = strlen(line);
828 return info;
831 static void
832 init_line_info_color_pair(struct line_info *info, enum line_type type,
833 int default_bg, int default_fg)
835 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
836 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
837 int i;
839 for (i = 0; i < color_pairs; i++) {
840 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
841 info->color_pair = i;
842 return;
846 if (!realloc_color_pair(&color_pair, color_pairs, 1))
847 die("Failed to alloc color pair");
849 color_pair[color_pairs] = info;
850 info->color_pair = color_pairs++;
851 init_pair(COLOR_ID(info->color_pair), fg, bg);
854 static void
855 init_colors(void)
857 int default_bg = line_info[LINE_DEFAULT].bg;
858 int default_fg = line_info[LINE_DEFAULT].fg;
859 enum line_type type;
861 start_color();
863 if (assume_default_colors(default_fg, default_bg) == ERR) {
864 default_bg = COLOR_BLACK;
865 default_fg = COLOR_WHITE;
868 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
869 struct line_info *info = &line_info[type];
871 init_line_info_color_pair(info, type, default_bg, default_fg);
874 for (type = 0; type < custom_colors; type++) {
875 struct line_info *info = &custom_color[type];
877 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
878 default_bg, default_fg);
882 struct line {
883 enum line_type type;
884 unsigned int lineno:24;
886 /* State flags */
887 unsigned int selected:1;
888 unsigned int dirty:1;
889 unsigned int cleareol:1;
890 unsigned int wrapped:1;
892 unsigned int user_flags:6;
893 void *data; /* User data */
898 * Keys
901 struct keybinding {
902 int alias;
903 enum request request;
906 static struct keybinding default_keybindings[] = {
907 /* View switching */
908 { 'm', REQ_VIEW_MAIN },
909 { 'd', REQ_VIEW_DIFF },
910 { 'l', REQ_VIEW_LOG },
911 { 't', REQ_VIEW_TREE },
912 { 'f', REQ_VIEW_BLOB },
913 { 'B', REQ_VIEW_BLAME },
914 { 'H', REQ_VIEW_BRANCH },
915 { 'p', REQ_VIEW_PAGER },
916 { 'h', REQ_VIEW_HELP },
917 { 'S', REQ_VIEW_STATUS },
918 { 'c', REQ_VIEW_STAGE },
919 { 'y', REQ_VIEW_STASH },
921 /* View manipulation */
922 { 'q', REQ_VIEW_CLOSE },
923 { KEY_TAB, REQ_VIEW_NEXT },
924 { KEY_RETURN, REQ_ENTER },
925 { KEY_UP, REQ_PREVIOUS },
926 { KEY_CTL('P'), REQ_PREVIOUS },
927 { KEY_DOWN, REQ_NEXT },
928 { KEY_CTL('N'), REQ_NEXT },
929 { 'R', REQ_REFRESH },
930 { KEY_F(5), REQ_REFRESH },
931 { 'O', REQ_MAXIMIZE },
932 { ',', REQ_PARENT },
933 { '<', REQ_BACK },
935 /* View specific */
936 { 'u', REQ_STATUS_UPDATE },
937 { '!', REQ_STATUS_REVERT },
938 { 'M', REQ_STATUS_MERGE },
939 { '1', REQ_STAGE_UPDATE_LINE },
940 { '@', REQ_STAGE_NEXT },
941 { '\\', REQ_STAGE_SPLIT_CHUNK },
942 { '[', REQ_DIFF_CONTEXT_DOWN },
943 { ']', REQ_DIFF_CONTEXT_UP },
945 /* Cursor navigation */
946 { 'k', REQ_MOVE_UP },
947 { 'j', REQ_MOVE_DOWN },
948 { KEY_HOME, REQ_MOVE_FIRST_LINE },
949 { KEY_END, REQ_MOVE_LAST_LINE },
950 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
951 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
952 { ' ', REQ_MOVE_PAGE_DOWN },
953 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
954 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
955 { 'b', REQ_MOVE_PAGE_UP },
956 { '-', REQ_MOVE_PAGE_UP },
958 /* Scrolling */
959 { '|', REQ_SCROLL_FIRST_COL },
960 { KEY_LEFT, REQ_SCROLL_LEFT },
961 { KEY_RIGHT, REQ_SCROLL_RIGHT },
962 { KEY_IC, REQ_SCROLL_LINE_UP },
963 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
964 { KEY_DC, REQ_SCROLL_LINE_DOWN },
965 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
966 { 'w', REQ_SCROLL_PAGE_UP },
967 { 's', REQ_SCROLL_PAGE_DOWN },
969 /* Searching */
970 { '/', REQ_SEARCH },
971 { '?', REQ_SEARCH_BACK },
972 { 'n', REQ_FIND_NEXT },
973 { 'N', REQ_FIND_PREV },
975 /* Misc */
976 { 'Q', REQ_QUIT },
977 { 'z', REQ_STOP_LOADING },
978 { 'v', REQ_SHOW_VERSION },
979 { 'r', REQ_SCREEN_REDRAW },
980 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
981 { 'o', REQ_OPTIONS },
982 { '.', REQ_TOGGLE_LINENO },
983 { 'D', REQ_TOGGLE_DATE },
984 { 'A', REQ_TOGGLE_AUTHOR },
985 { 'g', REQ_TOGGLE_REV_GRAPH },
986 { '~', REQ_TOGGLE_GRAPHIC },
987 { '#', REQ_TOGGLE_FILENAME },
988 { 'F', REQ_TOGGLE_REFS },
989 { 'I', REQ_TOGGLE_SORT_ORDER },
990 { 'i', REQ_TOGGLE_SORT_FIELD },
991 { 'W', REQ_TOGGLE_IGNORE_SPACE },
992 { 'X', REQ_TOGGLE_ID },
993 { '%', REQ_TOGGLE_FILES },
994 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
995 { ':', REQ_PROMPT },
996 { 'e', REQ_EDIT },
999 struct keymap {
1000 const char *name;
1001 struct keymap *next;
1002 struct keybinding *data;
1003 size_t size;
1004 bool hidden;
1007 static struct keymap generic_keymap = { "generic" };
1008 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
1010 static struct keymap *keymaps = &generic_keymap;
1012 static void
1013 add_keymap(struct keymap *keymap)
1015 keymap->next = keymaps;
1016 keymaps = keymap;
1019 static struct keymap *
1020 get_keymap(const char *name)
1022 struct keymap *keymap = keymaps;
1024 while (keymap) {
1025 if (!strcasecmp(keymap->name, name))
1026 return keymap;
1027 keymap = keymap->next;
1030 return NULL;
1034 static void
1035 add_keybinding(struct keymap *table, enum request request, int key)
1037 size_t i;
1039 for (i = 0; i < table->size; i++) {
1040 if (table->data[i].alias == key) {
1041 table->data[i].request = request;
1042 return;
1046 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1047 if (!table->data)
1048 die("Failed to allocate keybinding");
1049 table->data[table->size].alias = key;
1050 table->data[table->size++].request = request;
1052 if (request == REQ_NONE && is_generic_keymap(table)) {
1053 int i;
1055 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1056 if (default_keybindings[i].alias == key)
1057 default_keybindings[i].request = REQ_NONE;
1061 /* Looks for a key binding first in the given map, then in the generic map, and
1062 * lastly in the default keybindings. */
1063 static enum request
1064 get_keybinding(struct keymap *keymap, int key)
1066 size_t i;
1068 for (i = 0; i < keymap->size; i++)
1069 if (keymap->data[i].alias == key)
1070 return keymap->data[i].request;
1072 for (i = 0; i < generic_keymap.size; i++)
1073 if (generic_keymap.data[i].alias == key)
1074 return generic_keymap.data[i].request;
1076 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1077 if (default_keybindings[i].alias == key)
1078 return default_keybindings[i].request;
1080 return (enum request) key;
1084 struct key {
1085 const char *name;
1086 int value;
1089 static const struct key key_table[] = {
1090 { "Enter", KEY_RETURN },
1091 { "Space", ' ' },
1092 { "Backspace", KEY_BACKSPACE },
1093 { "Tab", KEY_TAB },
1094 { "Escape", KEY_ESC },
1095 { "Left", KEY_LEFT },
1096 { "Right", KEY_RIGHT },
1097 { "Up", KEY_UP },
1098 { "Down", KEY_DOWN },
1099 { "Insert", KEY_IC },
1100 { "Delete", KEY_DC },
1101 { "Hash", '#' },
1102 { "Home", KEY_HOME },
1103 { "End", KEY_END },
1104 { "PageUp", KEY_PPAGE },
1105 { "PageDown", KEY_NPAGE },
1106 { "F1", KEY_F(1) },
1107 { "F2", KEY_F(2) },
1108 { "F3", KEY_F(3) },
1109 { "F4", KEY_F(4) },
1110 { "F5", KEY_F(5) },
1111 { "F6", KEY_F(6) },
1112 { "F7", KEY_F(7) },
1113 { "F8", KEY_F(8) },
1114 { "F9", KEY_F(9) },
1115 { "F10", KEY_F(10) },
1116 { "F11", KEY_F(11) },
1117 { "F12", KEY_F(12) },
1120 static int
1121 get_key_value(const char *name)
1123 int i;
1125 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1126 if (!strcasecmp(key_table[i].name, name))
1127 return key_table[i].value;
1129 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1130 return (int)name[2] + 0x80;
1131 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1132 return (int)name[1] & 0x1f;
1133 if (strlen(name) == 1 && isprint(*name))
1134 return (int) *name;
1135 return ERR;
1138 static const char *
1139 get_key_name(int key_value)
1141 static char key_char[] = "'X'\0";
1142 const char *seq = NULL;
1143 int key;
1145 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1146 if (key_table[key].value == key_value)
1147 seq = key_table[key].name;
1149 if (seq == NULL && key_value < 0x7f) {
1150 char *s = key_char + 1;
1152 if (key_value >= 0x20) {
1153 *s++ = key_value;
1154 } else {
1155 *s++ = '^';
1156 *s++ = 0x40 | (key_value & 0x1f);
1158 *s++ = '\'';
1159 *s++ = '\0';
1160 seq = key_char;
1163 return seq ? seq : "(no key)";
1166 static bool
1167 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1169 const char *sep = *pos > 0 ? ", " : "";
1170 const char *keyname = get_key_name(keybinding->alias);
1172 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1175 static bool
1176 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1177 struct keymap *keymap, bool all)
1179 int i;
1181 for (i = 0; i < keymap->size; i++) {
1182 if (keymap->data[i].request == request) {
1183 if (!append_key(buf, pos, &keymap->data[i]))
1184 return FALSE;
1185 if (!all)
1186 break;
1190 return TRUE;
1193 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1195 static const char *
1196 get_keys(struct keymap *keymap, enum request request, bool all)
1198 static char buf[BUFSIZ];
1199 size_t pos = 0;
1200 int i;
1202 buf[pos] = 0;
1204 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1205 return "Too many keybindings!";
1206 if (pos > 0 && !all)
1207 return buf;
1209 if (!is_generic_keymap(keymap)) {
1210 /* Only the generic keymap includes the default keybindings when
1211 * listing all keys. */
1212 if (all)
1213 return buf;
1215 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1216 return "Too many keybindings!";
1217 if (pos)
1218 return buf;
1221 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1222 if (default_keybindings[i].request == request) {
1223 if (!append_key(buf, &pos, &default_keybindings[i]))
1224 return "Too many keybindings!";
1225 if (!all)
1226 return buf;
1230 return buf;
1233 enum run_request_flag {
1234 RUN_REQUEST_DEFAULT = 0,
1235 RUN_REQUEST_FORCE = 1,
1236 RUN_REQUEST_SILENT = 2,
1237 RUN_REQUEST_CONFIRM = 4,
1238 RUN_REQUEST_EXIT = 8,
1239 RUN_REQUEST_INTERNAL = 16,
1242 struct run_request {
1243 struct keymap *keymap;
1244 int key;
1245 const char **argv;
1246 bool silent;
1247 bool confirm;
1248 bool exit;
1249 bool internal;
1252 static struct run_request *run_request;
1253 static size_t run_requests;
1255 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1257 static bool
1258 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1260 bool force = flags & RUN_REQUEST_FORCE;
1261 struct run_request *req;
1263 if (!force && get_keybinding(keymap, key) != key)
1264 return TRUE;
1266 if (!realloc_run_requests(&run_request, run_requests, 1))
1267 return FALSE;
1269 if (!argv_copy(&run_request[run_requests].argv, argv))
1270 return FALSE;
1272 req = &run_request[run_requests++];
1273 req->silent = flags & RUN_REQUEST_SILENT;
1274 req->confirm = flags & RUN_REQUEST_CONFIRM;
1275 req->exit = flags & RUN_REQUEST_EXIT;
1276 req->internal = flags & RUN_REQUEST_INTERNAL;
1277 req->keymap = keymap;
1278 req->key = key;
1280 add_keybinding(keymap, REQ_RUN_REQUESTS + run_requests, key);
1281 return TRUE;
1284 static struct run_request *
1285 get_run_request(enum request request)
1287 if (request <= REQ_RUN_REQUESTS || request > REQ_RUN_REQUESTS + run_requests)
1288 return NULL;
1289 return &run_request[request - REQ_RUN_REQUESTS - 1];
1292 static void
1293 add_builtin_run_requests(void)
1295 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1296 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1297 const char *commit[] = { "git", "commit", NULL };
1298 const char *gc[] = { "git", "gc", NULL };
1299 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1301 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1302 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1303 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1304 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1305 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1309 * User config file handling.
1312 static const struct enum_map_entry color_map[] = {
1313 #define COLOR_MAP(name) ENUM_MAP_ENTRY(#name, COLOR_##name)
1314 COLOR_MAP(DEFAULT),
1315 COLOR_MAP(BLACK),
1316 COLOR_MAP(BLUE),
1317 COLOR_MAP(CYAN),
1318 COLOR_MAP(GREEN),
1319 COLOR_MAP(MAGENTA),
1320 COLOR_MAP(RED),
1321 COLOR_MAP(WHITE),
1322 COLOR_MAP(YELLOW),
1325 static const struct enum_map_entry attr_map[] = {
1326 #define ATTR_MAP(name) ENUM_MAP_ENTRY(#name, A_##name)
1327 ATTR_MAP(NORMAL),
1328 ATTR_MAP(BLINK),
1329 ATTR_MAP(BOLD),
1330 ATTR_MAP(DIM),
1331 ATTR_MAP(REVERSE),
1332 ATTR_MAP(STANDOUT),
1333 ATTR_MAP(UNDERLINE),
1336 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1338 static enum status_code
1339 parse_step(double *opt, const char *arg)
1341 *opt = atoi(arg);
1342 if (!strchr(arg, '%'))
1343 return SUCCESS;
1345 /* "Shift down" so 100% and 1 does not conflict. */
1346 *opt = (*opt - 1) / 100;
1347 if (*opt >= 1.0) {
1348 *opt = 0.99;
1349 return ERROR_INVALID_STEP_VALUE;
1351 if (*opt < 0.0) {
1352 *opt = 1;
1353 return ERROR_INVALID_STEP_VALUE;
1355 return SUCCESS;
1358 static enum status_code
1359 parse_int(int *opt, const char *arg, int min, int max)
1361 int value = atoi(arg);
1363 if (min <= value && value <= max) {
1364 *opt = value;
1365 return SUCCESS;
1368 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1371 #define parse_id(opt, arg) \
1372 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1374 static bool
1375 set_color(int *color, const char *name)
1377 if (map_enum(color, color_map, name))
1378 return TRUE;
1379 if (!prefixcmp(name, "color"))
1380 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1381 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1382 return parse_int(color, name, 0, 255) == SUCCESS;
1385 /* Wants: object fgcolor bgcolor [attribute] */
1386 static enum status_code
1387 option_color_command(int argc, const char *argv[])
1389 struct line_info *info;
1391 if (argc < 3)
1392 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1394 if (*argv[0] == '"' || *argv[0] == '\'') {
1395 info = add_custom_color(argv[0]);
1396 } else {
1397 info = get_line_info(argv[0]);
1399 if (!info) {
1400 static const struct enum_map_entry obsolete[] = {
1401 ENUM_MAP_ENTRY("main-delim", LINE_DELIMITER),
1402 ENUM_MAP_ENTRY("main-date", LINE_DATE),
1403 ENUM_MAP_ENTRY("main-author", LINE_AUTHOR),
1404 ENUM_MAP_ENTRY("blame-id", LINE_ID),
1406 int index;
1408 if (!map_enum(&index, obsolete, argv[0]))
1409 return ERROR_UNKNOWN_COLOR_NAME;
1410 info = &line_info[index];
1413 if (!set_color(&info->fg, argv[1]) ||
1414 !set_color(&info->bg, argv[2]))
1415 return ERROR_UNKNOWN_COLOR;
1417 info->attr = 0;
1418 while (argc-- > 3) {
1419 int attr;
1421 if (!set_attribute(&attr, argv[argc]))
1422 return ERROR_UNKNOWN_ATTRIBUTE;
1423 info->attr |= attr;
1426 return SUCCESS;
1429 static enum status_code
1430 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1432 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1433 ? TRUE : FALSE;
1434 if (matched)
1435 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1436 return SUCCESS;
1439 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1441 static enum status_code
1442 parse_enum(unsigned int *opt, const char *arg, const struct enum_map *map)
1444 bool is_true;
1446 assert(map->size > 1);
1448 if (map_enum_do(map->entries, map->size, (int *) opt, arg))
1449 return SUCCESS;
1451 parse_bool(&is_true, arg);
1452 *opt = is_true ? map->entries[1].value : map->entries[0].value;
1453 return SUCCESS;
1456 static enum status_code
1457 parse_string(char *opt, const char *arg, size_t optsize)
1459 int arglen = strlen(arg);
1461 switch (arg[0]) {
1462 case '\"':
1463 case '\'':
1464 if (arglen == 1 || arg[arglen - 1] != arg[0])
1465 return ERROR_UNMATCHED_QUOTATION;
1466 arg += 1; arglen -= 2;
1467 default:
1468 string_ncopy_do(opt, optsize, arg, arglen);
1469 return SUCCESS;
1473 static enum status_code
1474 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1476 char buf[SIZEOF_STR];
1477 enum status_code code = parse_string(buf, arg, sizeof(buf));
1479 if (code == SUCCESS) {
1480 struct encoding *encoding = *encoding_ref;
1482 if (encoding && !priority)
1483 return code;
1484 encoding = encoding_open(buf);
1485 if (encoding)
1486 *encoding_ref = encoding;
1489 return code;
1492 static enum status_code
1493 parse_args(const char ***args, const char *argv[])
1495 if (!argv_copy(args, argv))
1496 return ERROR_OUT_OF_MEMORY;
1497 return SUCCESS;
1500 /* Wants: name = value */
1501 static enum status_code
1502 option_set_command(int argc, const char *argv[])
1504 if (argc < 3)
1505 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1507 if (strcmp(argv[1], "="))
1508 return ERROR_NO_VALUE_ASSIGNED;
1510 if (!strcmp(argv[0], "blame-options"))
1511 return parse_args(&opt_blame_argv, argv + 2);
1513 if (!strcmp(argv[0], "diff-options"))
1514 return parse_args(&opt_diff_argv, argv + 2);
1516 if (argc != 3)
1517 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1519 if (!strcmp(argv[0], "show-author"))
1520 return parse_enum(&opt_author, argv[2], author_map);
1522 if (!strcmp(argv[0], "show-date"))
1523 return parse_enum(&opt_date, argv[2], date_map);
1525 if (!strcmp(argv[0], "show-rev-graph"))
1526 return parse_bool(&opt_rev_graph, argv[2]);
1528 if (!strcmp(argv[0], "show-refs"))
1529 return parse_bool(&opt_show_refs, argv[2]);
1531 if (!strcmp(argv[0], "show-changes"))
1532 return parse_bool(&opt_show_changes, argv[2]);
1534 if (!strcmp(argv[0], "show-notes")) {
1535 bool matched = FALSE;
1536 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1538 if (res == SUCCESS && matched) {
1539 update_notes_arg();
1540 return res;
1543 opt_notes = TRUE;
1544 strcpy(opt_notes_arg, "--show-notes=");
1545 res = parse_string(opt_notes_arg + 8, argv[2],
1546 sizeof(opt_notes_arg) - 8);
1547 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1548 opt_notes_arg[7] = '\0';
1549 return res;
1552 if (!strcmp(argv[0], "show-line-numbers"))
1553 return parse_bool(&opt_line_number, argv[2]);
1555 if (!strcmp(argv[0], "line-graphics"))
1556 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1558 if (!strcmp(argv[0], "line-number-interval"))
1559 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1561 if (!strcmp(argv[0], "author-width"))
1562 return parse_int(&opt_author_width, argv[2], 0, 1024);
1564 if (!strcmp(argv[0], "filename-width"))
1565 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1567 if (!strcmp(argv[0], "show-filename"))
1568 return parse_enum(&opt_filename, argv[2], filename_map);
1570 if (!strcmp(argv[0], "show-file-size"))
1571 return parse_enum(&opt_file_size, argv[2], file_size_map);
1573 if (!strcmp(argv[0], "horizontal-scroll"))
1574 return parse_step(&opt_hscroll, argv[2]);
1576 if (!strcmp(argv[0], "split-view-height"))
1577 return parse_step(&opt_scale_split_view, argv[2]);
1579 if (!strcmp(argv[0], "vertical-split"))
1580 return parse_enum(&opt_vertical_split, argv[2], vertical_split_map);
1582 if (!strcmp(argv[0], "tab-size"))
1583 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1585 if (!strcmp(argv[0], "diff-context")) {
1586 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1588 if (code == SUCCESS)
1589 update_diff_context_arg(opt_diff_context);
1590 return code;
1593 if (!strcmp(argv[0], "ignore-space") && !*opt_ignore_space_arg) {
1594 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1596 if (code == SUCCESS)
1597 update_ignore_space_arg();
1598 return code;
1601 if (!strcmp(argv[0], "commit-order") && !*opt_commit_order_arg) {
1602 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1604 if (code == SUCCESS)
1605 update_commit_order_arg();
1606 return code;
1609 if (!strcmp(argv[0], "status-untracked-dirs"))
1610 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1612 if (!strcmp(argv[0], "read-git-colors"))
1613 return parse_bool(&opt_read_git_colors, argv[2]);
1615 if (!strcmp(argv[0], "ignore-case"))
1616 return parse_bool(&opt_ignore_case, argv[2]);
1618 if (!strcmp(argv[0], "focus-child"))
1619 return parse_bool(&opt_focus_child, argv[2]);
1621 if (!strcmp(argv[0], "wrap-lines"))
1622 return parse_bool(&opt_wrap_lines, argv[2]);
1624 if (!strcmp(argv[0], "show-id"))
1625 return parse_bool(&opt_show_id, argv[2]);
1627 if (!strcmp(argv[0], "id-width"))
1628 return parse_id(&opt_id_cols, argv[2]);
1630 if (!strcmp(argv[0], "title-overflow")) {
1631 bool matched;
1632 enum status_code code;
1635 * "title-overflow" is considered a boolint.
1636 * We try to parse it as a boolean (and set the value to 50 if true),
1637 * otherwise we parse it as an integer and use the given value.
1639 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1640 if (code == SUCCESS && matched) {
1641 if (opt_show_title_overflow)
1642 opt_title_overflow = 50;
1643 } else {
1644 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1645 if (code == SUCCESS)
1646 opt_show_title_overflow = TRUE;
1649 return code;
1652 if (!strcmp(argv[0], "editor-line-number"))
1653 return parse_bool(&opt_editor_lineno, argv[2]);
1655 if (!strcmp(argv[0], "mouse"))
1656 return parse_bool(&opt_mouse, argv[2]);
1658 if (!strcmp(argv[0], "mouse-scroll"))
1659 return parse_int(&opt_scroll_wheel_lines, argv[2], 0, 1024);
1661 return ERROR_UNKNOWN_VARIABLE_NAME;
1664 /* Wants: mode request key */
1665 static enum status_code
1666 option_bind_command(int argc, const char *argv[])
1668 enum request request;
1669 struct keymap *keymap;
1670 int key;
1672 if (argc < 3)
1673 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1675 if (!(keymap = get_keymap(argv[0])))
1676 return ERROR_UNKNOWN_KEY_MAP;
1678 key = get_key_value(argv[1]);
1679 if (key == ERR)
1680 return ERROR_UNKNOWN_KEY;
1682 request = get_request(argv[2]);
1683 if (request == REQ_UNKNOWN) {
1684 static const struct enum_map_entry obsolete[] = {
1685 ENUM_MAP_ENTRY("cherry-pick", REQ_NONE),
1686 ENUM_MAP_ENTRY("screen-resize", REQ_NONE),
1687 ENUM_MAP_ENTRY("tree-parent", REQ_PARENT),
1689 int alias;
1691 if (map_enum(&alias, obsolete, argv[2])) {
1692 if (alias != REQ_NONE)
1693 add_keybinding(keymap, alias, key);
1694 return ERROR_OBSOLETE_REQUEST_NAME;
1698 if (request == REQ_UNKNOWN) {
1699 enum run_request_flag flags = RUN_REQUEST_FORCE;
1701 if (strchr("!?@<", *argv[2])) {
1702 while (*argv[2]) {
1703 if (*argv[2] == '@') {
1704 flags |= RUN_REQUEST_SILENT;
1705 } else if (*argv[2] == '?') {
1706 flags |= RUN_REQUEST_CONFIRM;
1707 } else if (*argv[2] == '<') {
1708 flags |= RUN_REQUEST_EXIT;
1709 } else if (*argv[2] != '!') {
1710 break;
1712 argv[2]++;
1715 } else if (*argv[2] == ':') {
1716 argv[2]++;
1717 flags |= RUN_REQUEST_INTERNAL;
1719 } else {
1720 return ERROR_UNKNOWN_REQUEST_NAME;
1723 return add_run_request(keymap, key, argv + 2, flags)
1724 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1727 add_keybinding(keymap, request, key);
1729 return SUCCESS;
1733 static enum status_code load_option_file(const char *path);
1735 static enum status_code
1736 option_source_command(int argc, const char *argv[])
1738 if (argc < 1)
1739 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1741 return load_option_file(argv[0]);
1744 static enum status_code
1745 set_option(const char *opt, char *value)
1747 const char *argv[SIZEOF_ARG];
1748 int argc = 0;
1750 if (!argv_from_string(argv, &argc, value))
1751 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1753 if (!strcmp(opt, "color"))
1754 return option_color_command(argc, argv);
1756 if (!strcmp(opt, "set"))
1757 return option_set_command(argc, argv);
1759 if (!strcmp(opt, "bind"))
1760 return option_bind_command(argc, argv);
1762 if (!strcmp(opt, "source"))
1763 return option_source_command(argc, argv);
1765 return ERROR_UNKNOWN_OPTION_COMMAND;
1768 struct config_state {
1769 const char *path;
1770 int lineno;
1771 bool errors;
1774 static int
1775 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1777 struct config_state *config = data;
1778 enum status_code status = ERROR_NO_OPTION_VALUE;
1780 config->lineno++;
1782 /* Check for comment markers, since read_properties() will
1783 * only ensure opt and value are split at first " \t". */
1784 optlen = strcspn(opt, "#");
1785 if (optlen == 0)
1786 return OK;
1788 if (opt[optlen] == 0) {
1789 /* Look for comment endings in the value. */
1790 size_t len = strcspn(value, "#");
1792 if (len < valuelen) {
1793 valuelen = len;
1794 value[valuelen] = 0;
1797 status = set_option(opt, value);
1800 if (status != SUCCESS) {
1801 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1802 get_status_message(status), (int) optlen, opt);
1803 config->errors = TRUE;
1806 /* Always keep going if errors are encountered. */
1807 return OK;
1810 static enum status_code
1811 load_option_file(const char *path)
1813 struct config_state config = { path, 0, FALSE };
1814 struct io io;
1815 char buf[SIZEOF_STR];
1817 /* Do not read configuration from stdin if set to "" */
1818 if (!path || !strlen(path))
1819 return SUCCESS;
1821 if (!prefixcmp(path, "~/")) {
1822 const char *home = getenv("HOME");
1824 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1825 return ERROR_HOME_UNRESOLVABLE;
1826 path = buf;
1829 /* It's OK that the file doesn't exist. */
1830 if (!io_open(&io, "%s", path))
1831 return ERROR_FILE_DOES_NOT_EXIST;
1833 if (io_load(&io, " \t", read_option, &config) == ERR ||
1834 config.errors == TRUE)
1835 warn("Errors while loading %s.", path);
1836 return SUCCESS;
1839 static int
1840 load_options(void)
1842 const char *tigrc_user = getenv("TIGRC_USER");
1843 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1844 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1845 const bool diff_opts_from_args = !!opt_diff_argv;
1847 if (!tigrc_system)
1848 tigrc_system = SYSCONFDIR "/tigrc";
1849 load_option_file(tigrc_system);
1851 if (!tigrc_user)
1852 tigrc_user = "~/.tigrc";
1853 load_option_file(tigrc_user);
1855 /* Add _after_ loading config files to avoid adding run requests
1856 * that conflict with keybindings. */
1857 add_builtin_run_requests();
1859 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1860 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1861 char buf[SIZEOF_STR];
1862 int argc = 0;
1864 if (!string_format(buf, "%s", tig_diff_opts) ||
1865 !argv_from_string(diff_opts, &argc, buf))
1866 die("TIG_DIFF_OPTS contains too many arguments");
1867 else if (!argv_copy(&opt_diff_argv, diff_opts))
1868 die("Failed to format TIG_DIFF_OPTS arguments");
1871 return OK;
1876 * The viewer
1879 struct view;
1880 struct view_ops;
1882 /* The display array of active views and the index of the current view. */
1883 static struct view *display[2];
1884 static WINDOW *display_win[2];
1885 static WINDOW *display_title[2];
1886 static WINDOW *display_sep;
1888 static unsigned int current_view;
1890 #define foreach_displayed_view(view, i) \
1891 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1893 #define displayed_views() (display[1] != NULL ? 2 : 1)
1895 /* Current head and commit ID */
1896 static char ref_blob[SIZEOF_REF] = "";
1897 static char ref_commit[SIZEOF_REF] = "HEAD";
1898 static char ref_head[SIZEOF_REF] = "HEAD";
1899 static char ref_branch[SIZEOF_REF] = "";
1900 static char ref_status[SIZEOF_STR] = "";
1901 static char ref_stash[SIZEOF_REF] = "";
1903 enum view_flag {
1904 VIEW_NO_FLAGS = 0,
1905 VIEW_ALWAYS_LINENO = 1 << 0,
1906 VIEW_CUSTOM_STATUS = 1 << 1,
1907 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1908 VIEW_ADD_PAGER_REFS = 1 << 3,
1909 VIEW_OPEN_DIFF = 1 << 4,
1910 VIEW_NO_REF = 1 << 5,
1911 VIEW_NO_GIT_DIR = 1 << 6,
1912 VIEW_DIFF_LIKE = 1 << 7,
1913 VIEW_SEND_CHILD_ENTER = 1 << 9,
1914 VIEW_FILE_FILTER = 1 << 10,
1915 VIEW_LOG_LIKE = 1 << 11,
1916 VIEW_STATUS_LIKE = 1 << 12,
1919 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1921 struct position {
1922 unsigned long offset; /* Offset of the window top */
1923 unsigned long col; /* Offset from the window side. */
1924 unsigned long lineno; /* Current line number */
1927 struct view {
1928 const char *name; /* View name */
1929 const char *id; /* Points to either of ref_{head,commit,blob} */
1931 struct view_ops *ops; /* View operations */
1933 char ref[SIZEOF_REF]; /* Hovered commit reference */
1934 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1936 int height, width; /* The width and height of the main window */
1937 WINDOW *win; /* The main window */
1939 /* Navigation */
1940 struct position pos; /* Current position. */
1941 struct position prev_pos; /* Previous position. */
1943 /* Searching */
1944 char grep[SIZEOF_STR]; /* Search string */
1945 regex_t *regex; /* Pre-compiled regexp */
1947 /* If non-NULL, points to the view that opened this view. If this view
1948 * is closed tig will switch back to the parent view. */
1949 struct view *parent;
1950 struct view *prev;
1952 /* Buffering */
1953 size_t lines; /* Total number of lines */
1954 struct line *line; /* Line index */
1955 unsigned int digits; /* Number of digits in the lines member. */
1957 /* Number of lines with custom status, not to be counted in the
1958 * view title. */
1959 unsigned int custom_lines;
1961 /* Drawing */
1962 struct line *curline; /* Line currently being drawn. */
1963 enum line_type curtype; /* Attribute currently used for drawing. */
1964 unsigned long col; /* Column when drawing. */
1965 bool has_scrolled; /* View was scrolled. */
1966 bool force_redraw; /* Whether to force a redraw after reading. */
1968 /* Loading */
1969 const char **argv; /* Shell command arguments. */
1970 const char *dir; /* Directory from which to execute. */
1971 struct io io;
1972 struct io *pipe;
1973 time_t start_time;
1974 time_t update_secs;
1975 struct encoding *encoding;
1976 bool unrefreshable;
1978 /* Private data */
1979 void *private;
1982 enum open_flags {
1983 OPEN_DEFAULT = 0, /* Use default view switching. */
1984 OPEN_STDIN = 1, /* Open in pager mode. */
1985 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1986 OPEN_SPLIT = 4, /* Split current view. */
1987 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1988 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1989 OPEN_PREPARED = 32, /* Open already prepared command. */
1990 OPEN_EXTRA = 64, /* Open extra data from command. */
1992 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1995 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1996 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
1998 struct view_ops {
1999 /* What type of content being displayed. Used in the title bar. */
2000 const char *type;
2001 /* What keymap does this view have */
2002 struct keymap keymap;
2003 /* Flags to control the view behavior. */
2004 enum view_flag flags;
2005 /* Size of private data. */
2006 size_t private_size;
2007 /* Open and reads in all view content. */
2008 bool (*open)(struct view *view, enum open_flags flags);
2009 /* Read one line; updates view->line. */
2010 bool (*read)(struct view *view, char *data);
2011 /* Draw one line; @lineno must be < view->height. */
2012 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
2013 /* Depending on view handle a special requests. */
2014 enum request (*request)(struct view *view, enum request request, struct line *line);
2015 /* Search for regexp in a line. */
2016 bool (*grep)(struct view *view, struct line *line);
2017 /* Select line */
2018 void (*select)(struct view *view, struct line *line);
2019 /* Release resources when reloading the view */
2020 void (*done)(struct view *view);
2023 #define VIEW_OPS(id, name, ref) name##_ops
2024 static struct view_ops VIEW_INFO(VIEW_OPS);
2026 static struct view views[] = {
2027 #define VIEW_DATA(id, name, ref) \
2028 { #name, ref, &name##_ops }
2029 VIEW_INFO(VIEW_DATA)
2032 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2034 #define foreach_view(view, i) \
2035 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2037 #define view_is_displayed(view) \
2038 (view == display[0] || view == display[1])
2040 #define view_has_line(view, line_) \
2041 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2043 static bool
2044 forward_request_to_child(struct view *child, enum request request)
2046 return displayed_views() == 2 && view_is_displayed(child) &&
2047 !strcmp(child->vid, child->id);
2050 static enum request
2051 view_request(struct view *view, enum request request)
2053 if (!view || !view->lines)
2054 return request;
2056 if (request == REQ_ENTER && !opt_focus_child &&
2057 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2058 struct view *child = display[1];
2060 if (forward_request_to_child(child, request)) {
2061 view_request(child, request);
2062 return REQ_NONE;
2066 if (request == REQ_REFRESH && view->unrefreshable) {
2067 report("This view can not be refreshed");
2068 return REQ_NONE;
2071 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2075 * View drawing.
2078 static inline void
2079 set_view_attr(struct view *view, enum line_type type)
2081 if (!view->curline->selected && view->curtype != type) {
2082 (void) wattrset(view->win, get_line_attr(type));
2083 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2084 view->curtype = type;
2088 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2090 static bool
2091 draw_chars(struct view *view, enum line_type type, const char *string,
2092 int max_len, bool use_tilde)
2094 int len = 0;
2095 int col = 0;
2096 int trimmed = FALSE;
2097 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2099 if (max_len <= 0)
2100 return VIEW_MAX_LEN(view) <= 0;
2102 if (opt_iconv_out != ICONV_NONE) {
2103 string = encoding_iconv(opt_iconv_out, string);
2104 if (!string)
2105 return VIEW_MAX_LEN(view) <= 0;
2108 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2110 set_view_attr(view, type);
2111 if (len > 0) {
2112 waddnstr(view->win, string, len);
2114 if (trimmed && use_tilde) {
2115 set_view_attr(view, LINE_DELIMITER);
2116 waddch(view->win, '~');
2117 col++;
2121 view->col += col;
2122 return VIEW_MAX_LEN(view) <= 0;
2125 static bool
2126 draw_space(struct view *view, enum line_type type, int max, int spaces)
2128 static char space[] = " ";
2130 spaces = MIN(max, spaces);
2132 while (spaces > 0) {
2133 int len = MIN(spaces, sizeof(space) - 1);
2135 if (draw_chars(view, type, space, len, FALSE))
2136 return TRUE;
2137 spaces -= len;
2140 return VIEW_MAX_LEN(view) <= 0;
2143 static bool
2144 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2146 static char text[SIZEOF_STR];
2148 do {
2149 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2151 if (draw_chars(view, type, text, max_len, use_tilde))
2152 return TRUE;
2153 string += pos;
2154 } while (*string);
2156 return VIEW_MAX_LEN(view) <= 0;
2159 static bool
2160 draw_text(struct view *view, enum line_type type, const char *string)
2162 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2165 static bool
2166 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2168 if (on) {
2169 int max = MIN(VIEW_MAX_LEN(view), overflow);
2170 int len = strlen(text);
2172 if (draw_text_expanded(view, type, text, max, max < overflow))
2173 return TRUE;
2175 text = len > overflow ? text + overflow : "";
2176 type = LINE_OVERFLOW;
2179 if (*text && draw_text(view, type, text))
2180 return TRUE;
2182 return VIEW_MAX_LEN(view) <= 0;
2185 #define draw_commit_title(view, text, offset) \
2186 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2188 static bool PRINTF_LIKE(3, 4)
2189 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2191 char text[SIZEOF_STR];
2192 int retval;
2194 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2195 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2198 static bool
2199 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2201 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2202 int max = VIEW_MAX_LEN(view);
2203 int i;
2205 if (max < size)
2206 size = max;
2208 set_view_attr(view, type);
2209 /* Using waddch() instead of waddnstr() ensures that
2210 * they'll be rendered correctly for the cursor line. */
2211 for (i = skip; i < size; i++)
2212 waddch(view->win, graphic[i]);
2214 view->col += size;
2215 if (separator) {
2216 if (size < max && skip <= size)
2217 waddch(view->win, ' ');
2218 view->col++;
2221 return VIEW_MAX_LEN(view) <= 0;
2224 enum align {
2225 ALIGN_LEFT,
2226 ALIGN_RIGHT
2229 static bool
2230 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2232 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2233 int col = view->col;
2235 if (!text)
2236 return draw_space(view, type, max, max);
2238 if (align == ALIGN_RIGHT) {
2239 int textlen = strlen(text);
2240 int leftpad = max - textlen - 1;
2242 if (leftpad > 0) {
2243 if (draw_space(view, type, leftpad, leftpad))
2244 return TRUE;
2245 max -= leftpad;
2246 col += leftpad;;
2250 return draw_chars(view, type, text, max - 1, trim)
2251 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2254 static bool
2255 draw_date(struct view *view, struct time *time)
2257 const char *date = mkdate(time, opt_date);
2258 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2260 if (opt_date == DATE_NO)
2261 return FALSE;
2263 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2266 static bool
2267 draw_author(struct view *view, const struct ident *author)
2269 bool trim = author_trim(opt_author_width);
2270 const char *text = mkauthor(author, opt_author_width, opt_author);
2272 if (opt_author == AUTHOR_NO)
2273 return FALSE;
2275 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2278 static bool
2279 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2281 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2284 static bool
2285 draw_id(struct view *view, const char *id)
2287 if (!opt_show_id)
2288 return FALSE;
2290 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2293 static bool
2294 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2296 bool trim = filename && strlen(filename) >= opt_filename_width;
2298 if (opt_filename == FILENAME_NO)
2299 return FALSE;
2301 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2302 return FALSE;
2304 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2307 static bool
2308 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2310 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2312 if (!width || opt_file_size == FILE_SIZE_NO)
2313 return FALSE;
2315 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2318 static bool
2319 draw_mode(struct view *view, mode_t mode)
2321 const char *str = mkmode(mode);
2323 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2326 static bool
2327 draw_lineno(struct view *view, unsigned int lineno)
2329 char number[10];
2330 int digits3 = view->digits < 3 ? 3 : view->digits;
2331 int max = MIN(VIEW_MAX_LEN(view), digits3);
2332 char *text = NULL;
2333 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2335 if (!opt_line_number)
2336 return FALSE;
2338 lineno += view->pos.offset + 1;
2339 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2340 static char fmt[] = "%1ld";
2342 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2343 if (string_format(number, fmt, lineno))
2344 text = number;
2346 if (text)
2347 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2348 else
2349 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2350 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2353 static bool
2354 draw_refs(struct view *view, struct ref_list *refs)
2356 size_t i;
2358 if (!opt_show_refs || !refs)
2359 return FALSE;
2361 for (i = 0; i < refs->size; i++) {
2362 struct ref *ref = refs->refs[i];
2363 enum line_type type = get_line_type_from_ref(ref);
2365 if (draw_formatted(view, type, "[%s]", ref->name))
2366 return TRUE;
2368 if (draw_text(view, LINE_DEFAULT, " "))
2369 return TRUE;
2372 return FALSE;
2375 static bool
2376 draw_view_line(struct view *view, unsigned int lineno)
2378 struct line *line;
2379 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2381 assert(view_is_displayed(view));
2383 if (view->pos.offset + lineno >= view->lines)
2384 return FALSE;
2386 line = &view->line[view->pos.offset + lineno];
2388 wmove(view->win, lineno, 0);
2389 if (line->cleareol)
2390 wclrtoeol(view->win);
2391 view->col = 0;
2392 view->curline = line;
2393 view->curtype = LINE_NONE;
2394 line->selected = FALSE;
2395 line->dirty = line->cleareol = 0;
2397 if (selected) {
2398 set_view_attr(view, LINE_CURSOR);
2399 line->selected = TRUE;
2400 view->ops->select(view, line);
2403 return view->ops->draw(view, line, lineno);
2406 static void
2407 redraw_view_dirty(struct view *view)
2409 bool dirty = FALSE;
2410 int lineno;
2412 for (lineno = 0; lineno < view->height; lineno++) {
2413 if (view->pos.offset + lineno >= view->lines)
2414 break;
2415 if (!view->line[view->pos.offset + lineno].dirty)
2416 continue;
2417 dirty = TRUE;
2418 if (!draw_view_line(view, lineno))
2419 break;
2422 if (!dirty)
2423 return;
2424 wnoutrefresh(view->win);
2427 static void
2428 redraw_view_from(struct view *view, int lineno)
2430 assert(0 <= lineno && lineno < view->height);
2432 for (; lineno < view->height; lineno++) {
2433 if (!draw_view_line(view, lineno))
2434 break;
2437 wnoutrefresh(view->win);
2440 static void
2441 redraw_view(struct view *view)
2443 werase(view->win);
2444 redraw_view_from(view, 0);
2448 static void
2449 update_view_title(struct view *view)
2451 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2452 struct line *line = &view->line[view->pos.lineno];
2453 unsigned int view_lines, lines;
2455 assert(view_is_displayed(view));
2457 if (view == display[current_view])
2458 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2459 else
2460 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2462 werase(window);
2463 mvwprintw(window, 0, 0, "[%s]", view->name);
2465 if (*view->ref) {
2466 wprintw(window, " %s", view->ref);
2469 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2470 line->lineno) {
2471 wprintw(window, " - %s %d of %zd",
2472 view->ops->type,
2473 line->lineno,
2474 view->lines - view->custom_lines);
2477 if (view->pipe) {
2478 time_t secs = time(NULL) - view->start_time;
2480 /* Three git seconds are a long time ... */
2481 if (secs > 2)
2482 wprintw(window, " loading %lds", secs);
2485 view_lines = view->pos.offset + view->height;
2486 lines = view->lines ? MIN(view_lines, view->lines) * 100 / view->lines : 0;
2487 mvwprintw(window, 0, view->width - count_digits(lines) - 1, "%d%%", lines);
2489 wnoutrefresh(window);
2492 static int
2493 apply_step(double step, int value)
2495 if (step >= 1)
2496 return (int) step;
2497 value *= step + 0.01;
2498 return value ? value : 1;
2501 static void
2502 apply_horizontal_split(struct view *base, struct view *view)
2504 view->width = base->width;
2505 view->height = apply_step(opt_scale_split_view, base->height);
2506 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2507 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2508 base->height -= view->height;
2511 static void
2512 apply_vertical_split(struct view *base, struct view *view)
2514 view->height = base->height;
2515 view->width = apply_step(opt_scale_vsplit_view, base->width);
2516 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2517 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2518 base->width -= view->width;
2521 static void
2522 redraw_display_separator(bool clear)
2524 if (displayed_views() > 1 && vertical_split_is_enabled()) {
2525 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2527 if (clear)
2528 wclear(display_sep);
2529 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2530 wnoutrefresh(display_sep);
2534 static void
2535 resize_display(void)
2537 int x, y, i;
2538 struct view *base = display[0];
2539 struct view *view = display[1] ? display[1] : display[0];
2540 bool vsplit;
2542 /* Setup window dimensions */
2544 getmaxyx(stdscr, base->height, base->width);
2545 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2546 string_format(opt_env_lines, "LINES=%d", base->height);
2548 /* Make room for the status window. */
2549 base->height -= 1;
2551 vsplit = vertical_split_is_enabled();
2553 if (view != base) {
2554 if (vsplit) {
2555 apply_vertical_split(base, view);
2557 /* Make room for the separator bar. */
2558 view->width -= 1;
2559 } else {
2560 apply_horizontal_split(base, view);
2563 /* Make room for the title bar. */
2564 view->height -= 1;
2567 /* Make room for the title bar. */
2568 base->height -= 1;
2570 x = y = 0;
2572 foreach_displayed_view (view, i) {
2573 if (!display_win[i]) {
2574 display_win[i] = newwin(view->height, view->width, y, x);
2575 if (!display_win[i])
2576 die("Failed to create %s view", view->name);
2578 scrollok(display_win[i], FALSE);
2580 display_title[i] = newwin(1, view->width, y + view->height, x);
2581 if (!display_title[i])
2582 die("Failed to create title window");
2584 } else {
2585 wresize(display_win[i], view->height, view->width);
2586 mvwin(display_win[i], y, x);
2587 wresize(display_title[i], 1, view->width);
2588 mvwin(display_title[i], y + view->height, x);
2591 if (i > 0 && vsplit) {
2592 if (!display_sep) {
2593 display_sep = newwin(view->height, 1, 0, x - 1);
2594 if (!display_sep)
2595 die("Failed to create separator window");
2597 } else {
2598 wresize(display_sep, view->height, 1);
2599 mvwin(display_sep, 0, x - 1);
2603 view->win = display_win[i];
2605 if (vsplit)
2606 x += view->width + 1;
2607 else
2608 y += view->height + 1;
2611 redraw_display_separator(FALSE);
2614 static void
2615 redraw_display(bool clear)
2617 struct view *view;
2618 int i;
2620 foreach_displayed_view (view, i) {
2621 if (clear)
2622 wclear(view->win);
2623 redraw_view(view);
2624 update_view_title(view);
2627 redraw_display_separator(clear);
2631 * Option management
2634 #define VIEW_FLAG_RESET_DISPLAY ((enum view_flag) -1)
2636 #define TOGGLE_MENU_INFO(_) \
2637 _(LINENO, '.', "line numbers", &opt_line_number, NULL, VIEW_NO_FLAGS), \
2638 _(DATE, 'D', "dates", &opt_date, date_map, VIEW_NO_FLAGS), \
2639 _(AUTHOR, 'A', "author", &opt_author, author_map, VIEW_NO_FLAGS), \
2640 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, VIEW_NO_FLAGS), \
2641 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, VIEW_LOG_LIKE), \
2642 _(FILENAME, '#', "file names", &opt_filename, filename_map, VIEW_NO_FLAGS), \
2643 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, VIEW_NO_FLAGS), \
2644 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, VIEW_DIFF_LIKE), \
2645 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, VIEW_LOG_LIKE), \
2646 _(REFS, 'F', "reference display", &opt_show_refs, NULL, VIEW_NO_FLAGS), \
2647 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, VIEW_NO_FLAGS), \
2648 _(ID, 'X', "commit ID display", &opt_show_id, NULL, VIEW_NO_FLAGS), \
2649 _(FILES, '%', "file filtering", &opt_file_filter, NULL, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2650 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, VIEW_NO_FLAGS), \
2651 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, VIEW_STATUS_LIKE), \
2652 _(VERTICAL_SPLIT, '|', "view split", &opt_vertical_split, vertical_split_map, VIEW_FLAG_RESET_DISPLAY), \
2654 static enum view_flag
2655 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2657 const struct {
2658 enum request request;
2659 const struct enum_map *map;
2660 enum view_flag reload_flags;
2661 } data[] = {
2662 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, vflags) { REQ_TOGGLE_ ## id, map, vflags }
2663 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2665 const struct menu_item menu[] = {
2666 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, vflags) { key, help, value }
2667 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2668 { 0 }
2670 int i = 0;
2672 if (request == REQ_OPTIONS) {
2673 if (!prompt_menu("Toggle option", menu, &i))
2674 return VIEW_NO_FLAGS;
2675 } else {
2676 while (i < ARRAY_SIZE(data) && data[i].request != request)
2677 i++;
2678 if (i >= ARRAY_SIZE(data))
2679 die("Invalid request (%d)", request);
2682 if (data[i].map != NULL) {
2683 unsigned int *opt = menu[i].data;
2685 *opt = (*opt + 1) % data[i].map->size;
2686 if (data[i].map == ignore_space_map) {
2687 update_ignore_space_arg();
2688 string_format_size(msg, SIZEOF_STR,
2689 "Ignoring %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2691 } else if (data[i].map == commit_order_map) {
2692 update_commit_order_arg();
2693 string_format_size(msg, SIZEOF_STR,
2694 "Using %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2696 } else {
2697 string_format_size(msg, SIZEOF_STR,
2698 "Displaying %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2701 } else {
2702 bool *option = menu[i].data;
2704 *option = !*option;
2705 string_format_size(msg, SIZEOF_STR,
2706 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2709 return data[i].reload_flags;
2714 * Navigation
2717 static bool
2718 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2720 if (lineno >= view->lines)
2721 lineno = view->lines > 0 ? view->lines - 1 : 0;
2723 if (offset > lineno || offset + view->height <= lineno) {
2724 unsigned long half = view->height / 2;
2726 if (lineno > half)
2727 offset = lineno - half;
2728 else
2729 offset = 0;
2732 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2733 view->pos.offset = offset;
2734 view->pos.lineno = lineno;
2735 return TRUE;
2738 return FALSE;
2741 /* Scrolling backend */
2742 static void
2743 do_scroll_view(struct view *view, int lines)
2745 bool redraw_current_line = FALSE;
2747 /* The rendering expects the new offset. */
2748 view->pos.offset += lines;
2750 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2751 assert(lines);
2753 /* Move current line into the view. */
2754 if (view->pos.lineno < view->pos.offset) {
2755 view->pos.lineno = view->pos.offset;
2756 redraw_current_line = TRUE;
2757 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2758 view->pos.lineno = view->pos.offset + view->height - 1;
2759 redraw_current_line = TRUE;
2762 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2764 /* Redraw the whole screen if scrolling is pointless. */
2765 if (view->height < ABS(lines)) {
2766 redraw_view(view);
2768 } else {
2769 int line = lines > 0 ? view->height - lines : 0;
2770 int end = line + ABS(lines);
2772 scrollok(view->win, TRUE);
2773 wscrl(view->win, lines);
2774 scrollok(view->win, FALSE);
2776 while (line < end && draw_view_line(view, line))
2777 line++;
2779 if (redraw_current_line)
2780 draw_view_line(view, view->pos.lineno - view->pos.offset);
2781 wnoutrefresh(view->win);
2784 view->has_scrolled = TRUE;
2785 report_clear();
2788 /* Scroll frontend */
2789 static void
2790 scroll_view(struct view *view, enum request request)
2792 int lines = 1;
2794 assert(view_is_displayed(view));
2796 if (request == REQ_SCROLL_WHEEL_DOWN || request == REQ_SCROLL_WHEEL_UP)
2797 lines = opt_scroll_wheel_lines;
2799 switch (request) {
2800 case REQ_SCROLL_FIRST_COL:
2801 view->pos.col = 0;
2802 redraw_view_from(view, 0);
2803 report_clear();
2804 return;
2805 case REQ_SCROLL_LEFT:
2806 if (view->pos.col == 0) {
2807 report("Cannot scroll beyond the first column");
2808 return;
2810 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2811 view->pos.col = 0;
2812 else
2813 view->pos.col -= apply_step(opt_hscroll, view->width);
2814 redraw_view_from(view, 0);
2815 report_clear();
2816 return;
2817 case REQ_SCROLL_RIGHT:
2818 view->pos.col += apply_step(opt_hscroll, view->width);
2819 redraw_view(view);
2820 report_clear();
2821 return;
2822 case REQ_SCROLL_PAGE_DOWN:
2823 lines = view->height;
2824 case REQ_SCROLL_WHEEL_DOWN:
2825 case REQ_SCROLL_LINE_DOWN:
2826 if (view->pos.offset + lines > view->lines)
2827 lines = view->lines - view->pos.offset;
2829 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2830 report("Cannot scroll beyond the last line");
2831 return;
2833 break;
2835 case REQ_SCROLL_PAGE_UP:
2836 lines = view->height;
2837 case REQ_SCROLL_LINE_UP:
2838 case REQ_SCROLL_WHEEL_UP:
2839 if (lines > view->pos.offset)
2840 lines = view->pos.offset;
2842 if (lines == 0) {
2843 report("Cannot scroll beyond the first line");
2844 return;
2847 lines = -lines;
2848 break;
2850 default:
2851 die("request %d not handled in switch", request);
2854 do_scroll_view(view, lines);
2857 /* Cursor moving */
2858 static void
2859 move_view(struct view *view, enum request request)
2861 int scroll_steps = 0;
2862 int steps;
2864 switch (request) {
2865 case REQ_MOVE_FIRST_LINE:
2866 steps = -view->pos.lineno;
2867 break;
2869 case REQ_MOVE_LAST_LINE:
2870 steps = view->lines - view->pos.lineno - 1;
2871 break;
2873 case REQ_MOVE_PAGE_UP:
2874 steps = view->height > view->pos.lineno
2875 ? -view->pos.lineno : -view->height;
2876 break;
2878 case REQ_MOVE_PAGE_DOWN:
2879 steps = view->pos.lineno + view->height >= view->lines
2880 ? view->lines - view->pos.lineno - 1 : view->height;
2881 break;
2883 case REQ_MOVE_UP:
2884 case REQ_PREVIOUS:
2885 steps = -1;
2886 break;
2888 case REQ_MOVE_DOWN:
2889 case REQ_NEXT:
2890 steps = 1;
2891 break;
2893 default:
2894 die("request %d not handled in switch", request);
2897 if (steps <= 0 && view->pos.lineno == 0) {
2898 report("Cannot move beyond the first line");
2899 return;
2901 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2902 report("Cannot move beyond the last line");
2903 return;
2906 /* Move the current line */
2907 view->pos.lineno += steps;
2908 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2910 /* Check whether the view needs to be scrolled */
2911 if (view->pos.lineno < view->pos.offset ||
2912 view->pos.lineno >= view->pos.offset + view->height) {
2913 scroll_steps = steps;
2914 if (steps < 0 && -steps > view->pos.offset) {
2915 scroll_steps = -view->pos.offset;
2917 } else if (steps > 0) {
2918 if (view->pos.lineno == view->lines - 1 &&
2919 view->lines > view->height) {
2920 scroll_steps = view->lines - view->pos.offset - 1;
2921 if (scroll_steps >= view->height)
2922 scroll_steps -= view->height - 1;
2927 if (!view_is_displayed(view)) {
2928 view->pos.offset += scroll_steps;
2929 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2930 view->ops->select(view, &view->line[view->pos.lineno]);
2931 return;
2934 /* Repaint the old "current" line if we be scrolling */
2935 if (ABS(steps) < view->height)
2936 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2938 if (scroll_steps) {
2939 do_scroll_view(view, scroll_steps);
2940 return;
2943 /* Draw the current line */
2944 draw_view_line(view, view->pos.lineno - view->pos.offset);
2946 wnoutrefresh(view->win);
2947 report_clear();
2952 * Searching
2955 static void search_view(struct view *view, enum request request);
2957 static bool
2958 grep_text(struct view *view, const char *text[])
2960 regmatch_t pmatch;
2961 size_t i;
2963 for (i = 0; text[i]; i++)
2964 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2965 return TRUE;
2966 return FALSE;
2969 static void
2970 select_view_line(struct view *view, unsigned long lineno)
2972 struct position old = view->pos;
2974 if (goto_view_line(view, view->pos.offset, lineno)) {
2975 if (view_is_displayed(view)) {
2976 if (old.offset != view->pos.offset) {
2977 redraw_view(view);
2978 } else {
2979 draw_view_line(view, old.lineno - view->pos.offset);
2980 draw_view_line(view, view->pos.lineno - view->pos.offset);
2981 wnoutrefresh(view->win);
2983 } else {
2984 view->ops->select(view, &view->line[view->pos.lineno]);
2989 static void
2990 find_next(struct view *view, enum request request)
2992 unsigned long lineno = view->pos.lineno;
2993 int direction;
2995 if (!*view->grep) {
2996 if (!*opt_search)
2997 report("No previous search");
2998 else
2999 search_view(view, request);
3000 return;
3003 switch (request) {
3004 case REQ_SEARCH:
3005 case REQ_FIND_NEXT:
3006 direction = 1;
3007 break;
3009 case REQ_SEARCH_BACK:
3010 case REQ_FIND_PREV:
3011 direction = -1;
3012 break;
3014 default:
3015 return;
3018 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
3019 lineno += direction;
3021 /* Note, lineno is unsigned long so will wrap around in which case it
3022 * will become bigger than view->lines. */
3023 for (; lineno < view->lines; lineno += direction) {
3024 if (view->ops->grep(view, &view->line[lineno])) {
3025 select_view_line(view, lineno);
3026 report("Line %ld matches '%s'", lineno + 1, view->grep);
3027 return;
3031 report("No match found for '%s'", view->grep);
3034 static void
3035 search_view(struct view *view, enum request request)
3037 int regex_err;
3038 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3040 if (view->regex) {
3041 regfree(view->regex);
3042 *view->grep = 0;
3043 } else {
3044 view->regex = calloc(1, sizeof(*view->regex));
3045 if (!view->regex)
3046 return;
3049 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3050 if (regex_err != 0) {
3051 char buf[SIZEOF_STR] = "unknown error";
3053 regerror(regex_err, view->regex, buf, sizeof(buf));
3054 report("Search failed: %s", buf);
3055 return;
3058 string_copy(view->grep, opt_search);
3060 find_next(view, request);
3064 * Incremental updating
3067 static inline bool
3068 check_position(struct position *pos)
3070 return pos->lineno || pos->col || pos->offset;
3073 static inline void
3074 clear_position(struct position *pos)
3076 memset(pos, 0, sizeof(*pos));
3079 static void
3080 reset_view(struct view *view)
3082 int i;
3084 if (view->ops->done)
3085 view->ops->done(view);
3087 for (i = 0; i < view->lines; i++)
3088 free(view->line[i].data);
3089 free(view->line);
3091 view->prev_pos = view->pos;
3092 clear_position(&view->pos);
3094 view->line = NULL;
3095 view->lines = 0;
3096 view->vid[0] = 0;
3097 view->custom_lines = 0;
3098 view->update_secs = 0;
3101 struct format_context {
3102 struct view *view;
3103 char buf[SIZEOF_STR];
3104 size_t bufpos;
3105 bool file_filter;
3108 static bool
3109 format_expand_arg(struct format_context *format, const char *name)
3111 static struct {
3112 const char *name;
3113 size_t namelen;
3114 const char *value;
3115 const char *value_if_empty;
3116 } vars[] = {
3117 #define FORMAT_VAR(name, value, value_if_empty) \
3118 { name, STRING_SIZE(name), value, value_if_empty }
3119 FORMAT_VAR("%(directory)", opt_path, "."),
3120 FORMAT_VAR("%(file)", opt_file, ""),
3121 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3122 FORMAT_VAR("%(head)", ref_head, ""),
3123 FORMAT_VAR("%(commit)", ref_commit, ""),
3124 FORMAT_VAR("%(blob)", ref_blob, ""),
3125 FORMAT_VAR("%(branch)", ref_branch, ""),
3126 FORMAT_VAR("%(stash)", ref_stash, ""),
3128 int i;
3130 if (!prefixcmp(name, "%(prompt)")) {
3131 const char *value = read_prompt("Command argument: ");
3133 return string_format_from(format->buf, &format->bufpos, "%s", value);
3136 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3137 const char *value;
3139 if (strncmp(name, vars[i].name, vars[i].namelen))
3140 continue;
3142 if (vars[i].value == opt_file && !format->file_filter)
3143 return TRUE;
3145 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3146 if (!*value)
3147 return TRUE;
3149 return string_format_from(format->buf, &format->bufpos, "%s", value);
3152 report("Unknown replacement: `%s`", name);
3153 return NULL;
3156 static bool
3157 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3159 memset(format->buf, 0, sizeof(format->buf));
3160 format->bufpos = 0;
3162 while (arg) {
3163 char *next = strstr(arg, "%(");
3164 int len = next ? next - arg : strlen(arg);
3166 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3167 return FALSE;
3169 if (next && !format_expand_arg(format, next))
3170 return FALSE;
3172 arg = next ? strchr(next, ')') + 1 : NULL;
3175 return argv_append(dst_argv, format->buf);
3178 static bool
3179 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3181 int argc;
3183 if (!src_argv)
3184 return TRUE;
3186 for (argc = 0; src_argv[argc]; argc++)
3187 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3188 return FALSE;
3190 return src_argv[argc] == NULL;
3193 static bool
3194 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3196 struct format_context format = { view, "", 0, file_filter };
3197 int argc;
3199 argv_free(*dst_argv);
3201 for (argc = 0; src_argv[argc]; argc++) {
3202 const char *arg = src_argv[argc];
3204 if (!strcmp(arg, "%(fileargs)")) {
3205 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3206 break;
3208 } else if (!strcmp(arg, "%(diffargs)")) {
3209 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3210 break;
3212 } else if (!strcmp(arg, "%(blameargs)")) {
3213 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3214 break;
3216 } else if (!strcmp(arg, "%(revargs)") ||
3217 (first && !strcmp(arg, "%(commit)"))) {
3218 if (!argv_append_array(dst_argv, opt_rev_argv))
3219 break;
3221 } else if (!format_append_arg(&format, dst_argv, arg)) {
3222 break;
3226 return src_argv[argc] == NULL;
3229 static bool
3230 restore_view_position(struct view *view)
3232 /* A view without a previous view is the first view */
3233 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3234 select_view_line(view, opt_lineno - 1);
3235 opt_lineno = 0;
3238 /* Ensure that the view position is in a valid state. */
3239 if (!check_position(&view->prev_pos) ||
3240 (view->pipe && view->lines <= view->prev_pos.lineno))
3241 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3243 /* Changing the view position cancels the restoring. */
3244 /* FIXME: Changing back to the first line is not detected. */
3245 if (check_position(&view->pos)) {
3246 clear_position(&view->prev_pos);
3247 return FALSE;
3250 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3251 view_is_displayed(view))
3252 werase(view->win);
3254 view->pos.col = view->prev_pos.col;
3255 clear_position(&view->prev_pos);
3257 return TRUE;
3260 static void
3261 end_update(struct view *view, bool force)
3263 if (!view->pipe)
3264 return;
3265 while (!view->ops->read(view, NULL))
3266 if (!force)
3267 return;
3268 if (force)
3269 io_kill(view->pipe);
3270 io_done(view->pipe);
3271 view->pipe = NULL;
3274 static void
3275 setup_update(struct view *view, const char *vid)
3277 reset_view(view);
3278 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3279 string_ncopy(view->vid, vid, strlen(vid));
3280 view->pipe = &view->io;
3281 view->start_time = time(NULL);
3284 static bool
3285 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3287 bool extra = !!(flags & (OPEN_EXTRA));
3288 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3289 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3290 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3291 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3293 if ((!reload && !strcmp(view->vid, view->id)) ||
3294 ((flags & OPEN_REFRESH) && view->unrefreshable))
3295 return TRUE;
3297 if (view->pipe) {
3298 if (extra)
3299 io_done(view->pipe);
3300 else
3301 end_update(view, TRUE);
3304 view->unrefreshable = open_in_pager_mode(flags);
3306 if (!refresh && argv) {
3307 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3309 view->dir = dir;
3310 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3311 report("Failed to format %s arguments", view->name);
3312 return FALSE;
3315 /* Put the current ref_* value to the view title ref
3316 * member. This is needed by the blob view. Most other
3317 * views sets it automatically after loading because the
3318 * first line is a commit line. */
3319 string_copy_rev(view->ref, view->id);
3322 if (view->argv && view->argv[0] &&
3323 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3324 report("Failed to open %s view", view->name);
3325 return FALSE;
3328 if (open_from_stdin(flags)) {
3329 if (!io_open(&view->io, "%s", ""))
3330 die("Failed to open stdin");
3333 if (!extra)
3334 setup_update(view, view->id);
3336 return TRUE;
3339 static bool
3340 update_view(struct view *view)
3342 char *line;
3343 /* Clear the view and redraw everything since the tree sorting
3344 * might have rearranged things. */
3345 bool redraw = view->lines == 0;
3346 bool can_read = TRUE;
3347 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3349 if (!view->pipe)
3350 return TRUE;
3352 if (!io_can_read(view->pipe, FALSE)) {
3353 if (view->lines == 0 && view_is_displayed(view)) {
3354 time_t secs = time(NULL) - view->start_time;
3356 if (secs > 1 && secs > view->update_secs) {
3357 if (view->update_secs == 0)
3358 redraw_view(view);
3359 update_view_title(view);
3360 view->update_secs = secs;
3363 return TRUE;
3366 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3367 if (encoding) {
3368 line = encoding_convert(encoding, line);
3371 if (!view->ops->read(view, line)) {
3372 report("Allocation failure");
3373 end_update(view, TRUE);
3374 return FALSE;
3379 int digits = count_digits(view->lines);
3381 /* Keep the displayed view in sync with line number scaling. */
3382 if (digits != view->digits) {
3383 view->digits = digits;
3384 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3385 redraw = TRUE;
3389 if (io_error(view->pipe)) {
3390 report("Failed to read: %s", io_strerror(view->pipe));
3391 end_update(view, TRUE);
3393 } else if (io_eof(view->pipe)) {
3394 end_update(view, FALSE);
3397 if (restore_view_position(view))
3398 redraw = TRUE;
3400 if (!view_is_displayed(view))
3401 return TRUE;
3403 if (redraw || view->force_redraw)
3404 redraw_view_from(view, 0);
3405 else
3406 redraw_view_dirty(view);
3407 view->force_redraw = FALSE;
3409 /* Update the title _after_ the redraw so that if the redraw picks up a
3410 * commit reference in view->ref it'll be available here. */
3411 update_view_title(view);
3412 return TRUE;
3415 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3417 static struct line *
3418 add_line_at(struct view *view, unsigned long pos, const void *data, enum line_type type, size_t data_size, bool custom)
3420 struct line *line;
3421 unsigned long lineno;
3423 if (!realloc_lines(&view->line, view->lines, 1))
3424 return NULL;
3426 if (data_size) {
3427 void *alloc_data = calloc(1, data_size);
3429 if (!alloc_data)
3430 return NULL;
3432 if (data)
3433 memcpy(alloc_data, data, data_size);
3434 data = alloc_data;
3437 if (pos < view->lines) {
3438 view->lines++;
3439 line = view->line + pos;
3440 lineno = line->lineno;
3442 memmove(line + 1, line, (view->lines - pos) * sizeof(*view->line));
3443 while (pos < view->lines) {
3444 view->line[pos].lineno++;
3445 view->line[pos++].dirty = 1;
3447 } else {
3448 line = &view->line[view->lines++];
3449 lineno = view->lines - view->custom_lines;
3452 memset(line, 0, sizeof(*line));
3453 line->type = type;
3454 line->data = (void *) data;
3455 line->dirty = 1;
3457 if (custom)
3458 view->custom_lines++;
3459 else
3460 line->lineno = lineno;
3462 return line;
3465 static struct line *
3466 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3468 return add_line_at(view, view->lines, data, type, data_size, custom);
3471 static struct line *
3472 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3474 struct line *line = add_line(view, NULL, type, data_size, custom);
3476 if (line)
3477 *ptr = line->data;
3478 return line;
3481 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3482 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3484 static struct line *
3485 add_line_nodata(struct view *view, enum line_type type)
3487 return add_line(view, NULL, type, 0, FALSE);
3490 static struct line *
3491 add_line_text(struct view *view, const char *text, enum line_type type)
3493 return add_line(view, text, type, strlen(text) + 1, FALSE);
3496 static struct line * PRINTF_LIKE(3, 4)
3497 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3499 char buf[SIZEOF_STR];
3500 int retval;
3502 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3503 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3507 * View opening
3510 static void
3511 split_view(struct view *prev, struct view *view)
3513 display[1] = view;
3514 current_view = opt_focus_child ? 1 : 0;
3515 view->parent = prev;
3516 resize_display();
3518 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3519 /* Take the title line into account. */
3520 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3522 /* Scroll the view that was split if the current line is
3523 * outside the new limited view. */
3524 do_scroll_view(prev, lines);
3527 if (view != prev && view_is_displayed(prev)) {
3528 /* "Blur" the previous view. */
3529 update_view_title(prev);
3533 static void
3534 maximize_view(struct view *view, bool redraw)
3536 memset(display, 0, sizeof(display));
3537 current_view = 0;
3538 display[current_view] = view;
3539 resize_display();
3540 if (redraw) {
3541 redraw_display(FALSE);
3542 report_clear();
3546 static void
3547 load_view(struct view *view, struct view *prev, enum open_flags flags)
3549 if (view->pipe)
3550 end_update(view, TRUE);
3551 if (view->ops->private_size) {
3552 if (!view->private)
3553 view->private = calloc(1, view->ops->private_size);
3554 else
3555 memset(view->private, 0, view->ops->private_size);
3558 /* When prev == view it means this is the first loaded view. */
3559 if (prev && view != prev) {
3560 view->prev = prev;
3563 if (!view->ops->open(view, flags))
3564 return;
3566 if (prev) {
3567 bool split = !!(flags & OPEN_SPLIT);
3569 if (split) {
3570 split_view(prev, view);
3571 } else {
3572 maximize_view(view, FALSE);
3576 restore_view_position(view);
3578 if (view->pipe && view->lines == 0) {
3579 /* Clear the old view and let the incremental updating refill
3580 * the screen. */
3581 werase(view->win);
3582 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3583 clear_position(&view->prev_pos);
3584 report_clear();
3585 } else if (view_is_displayed(view)) {
3586 redraw_view(view);
3587 report_clear();
3591 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3592 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3594 static void
3595 open_view(struct view *prev, enum request request, enum open_flags flags)
3597 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3598 struct view *view = VIEW(request);
3599 int nviews = displayed_views();
3601 assert(flags ^ OPEN_REFRESH);
3603 if (view == prev && nviews == 1 && !reload) {
3604 report("Already in %s view", view->name);
3605 return;
3608 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3609 report("The %s view is disabled in pager view", view->name);
3610 return;
3613 load_view(view, prev ? prev : view, flags);
3616 static void
3617 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3619 enum request request = view - views + REQ_OFFSET + 1;
3621 if (view->pipe)
3622 end_update(view, TRUE);
3623 view->dir = dir;
3625 if (!argv_copy(&view->argv, argv)) {
3626 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3627 } else {
3628 open_view(prev, request, flags | OPEN_PREPARED);
3632 static bool
3633 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3635 bool ok;
3637 def_prog_mode(); /* save current tty modes */
3638 endwin(); /* restore original tty modes */
3639 ok = io_run_fg(argv, dir);
3640 if (confirm) {
3641 if (!ok && *notice)
3642 fprintf(stderr, "%s", notice);
3643 fprintf(stderr, "Press Enter to continue");
3644 getc(opt_tty);
3646 reset_prog_mode();
3647 redraw_display(TRUE);
3648 return ok;
3651 static void
3652 open_mergetool(const char *file)
3654 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3656 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3659 #define EDITOR_LINENO_MSG \
3660 "*** Your editor reported an error while opening the file.\n" \
3661 "*** This is probably because it doesn't support the line\n" \
3662 "*** number argument added automatically. The line number\n" \
3663 "*** has been disabled for now. You can permanently disable\n" \
3664 "*** it by adding the following line to ~/.tigrc\n" \
3665 "*** set editor-line-number = no\n"
3667 static void
3668 open_editor(const char *file, unsigned int lineno)
3670 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3671 char editor_cmd[SIZEOF_STR];
3672 char lineno_cmd[SIZEOF_STR];
3673 const char *editor;
3674 int argc = 0;
3676 editor = getenv("GIT_EDITOR");
3677 if (!editor && *opt_editor)
3678 editor = opt_editor;
3679 if (!editor)
3680 editor = getenv("VISUAL");
3681 if (!editor)
3682 editor = getenv("EDITOR");
3683 if (!editor)
3684 editor = "vi";
3686 string_ncopy(editor_cmd, editor, strlen(editor));
3687 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3688 report("Failed to read editor command");
3689 return;
3692 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3693 editor_argv[argc++] = lineno_cmd;
3694 editor_argv[argc] = file;
3695 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3696 opt_editor_lineno = FALSE;
3699 static enum request run_prompt_command(struct view *view, char *cmd);
3701 static enum request
3702 open_run_request(struct view *view, enum request request)
3704 struct run_request *req = get_run_request(request);
3705 const char **argv = NULL;
3706 bool confirmed = FALSE;
3708 request = REQ_NONE;
3710 if (!req) {
3711 report("Unknown run request");
3712 return request;
3715 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3716 if (req->internal) {
3717 char cmd[SIZEOF_STR];
3719 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3720 request = run_prompt_command(view, cmd);
3723 else {
3724 confirmed = !req->confirm;
3726 if (req->confirm) {
3727 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3728 const char *and_exit = req->exit ? " and exit" : "";
3730 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3731 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3732 prompt_yesno(prompt)) {
3733 confirmed = TRUE;
3737 if (confirmed && argv_remove_quotes(argv)) {
3738 if (req->silent)
3739 io_run_bg(argv);
3740 else
3741 open_external_viewer(argv, NULL, !req->exit, "");
3746 if (argv)
3747 argv_free(argv);
3748 free(argv);
3750 if (request == REQ_NONE) {
3751 if (req->confirm && !confirmed)
3752 request = REQ_NONE;
3754 else if (req->exit)
3755 request = REQ_QUIT;
3757 else if (!view->unrefreshable)
3758 request = REQ_REFRESH;
3760 return request;
3764 * User request switch noodle
3767 static int
3768 view_driver(struct view *view, enum request request)
3770 int i;
3772 if (request == REQ_NONE)
3773 return TRUE;
3775 if (request >= REQ_RUN_REQUESTS) {
3776 request = open_run_request(view, request);
3778 // exit quickly rather than going through view_request and back
3779 if (request == REQ_QUIT)
3780 return FALSE;
3783 request = view_request(view, request);
3784 if (request == REQ_NONE)
3785 return TRUE;
3787 switch (request) {
3788 case REQ_MOVE_UP:
3789 case REQ_MOVE_DOWN:
3790 case REQ_MOVE_PAGE_UP:
3791 case REQ_MOVE_PAGE_DOWN:
3792 case REQ_MOVE_FIRST_LINE:
3793 case REQ_MOVE_LAST_LINE:
3794 move_view(view, request);
3795 break;
3797 case REQ_SCROLL_FIRST_COL:
3798 case REQ_SCROLL_LEFT:
3799 case REQ_SCROLL_RIGHT:
3800 case REQ_SCROLL_LINE_DOWN:
3801 case REQ_SCROLL_LINE_UP:
3802 case REQ_SCROLL_PAGE_DOWN:
3803 case REQ_SCROLL_PAGE_UP:
3804 case REQ_SCROLL_WHEEL_DOWN:
3805 case REQ_SCROLL_WHEEL_UP:
3806 scroll_view(view, request);
3807 break;
3809 case REQ_VIEW_MAIN:
3810 case REQ_VIEW_DIFF:
3811 case REQ_VIEW_LOG:
3812 case REQ_VIEW_TREE:
3813 case REQ_VIEW_HELP:
3814 case REQ_VIEW_BRANCH:
3815 case REQ_VIEW_BLAME:
3816 case REQ_VIEW_BLOB:
3817 case REQ_VIEW_STATUS:
3818 case REQ_VIEW_STAGE:
3819 case REQ_VIEW_PAGER:
3820 case REQ_VIEW_STASH:
3821 open_view(view, request, OPEN_DEFAULT);
3822 break;
3824 case REQ_NEXT:
3825 case REQ_PREVIOUS:
3826 if (view->parent) {
3827 int line;
3829 view = view->parent;
3830 line = view->pos.lineno;
3831 view_request(view, request);
3832 move_view(view, request);
3833 if (view_is_displayed(view))
3834 update_view_title(view);
3835 if (line != view->pos.lineno)
3836 view_request(view, REQ_ENTER);
3837 } else {
3838 move_view(view, request);
3840 break;
3842 case REQ_VIEW_NEXT:
3844 int nviews = displayed_views();
3845 int next_view = (current_view + 1) % nviews;
3847 if (next_view == current_view) {
3848 report("Only one view is displayed");
3849 break;
3852 current_view = next_view;
3853 /* Blur out the title of the previous view. */
3854 update_view_title(view);
3855 report_clear();
3856 break;
3858 case REQ_REFRESH:
3859 report("Refreshing is not supported by the %s view", view->name);
3860 break;
3862 case REQ_PARENT:
3863 report("Moving to parent is not supported by the the %s view", view->name);
3864 break;
3866 case REQ_BACK:
3867 report("Going back is not supported for by %s view", view->name);
3868 break;
3870 case REQ_MAXIMIZE:
3871 if (displayed_views() == 2)
3872 maximize_view(view, TRUE);
3873 break;
3875 case REQ_OPTIONS:
3876 case REQ_TOGGLE_LINENO:
3877 case REQ_TOGGLE_DATE:
3878 case REQ_TOGGLE_AUTHOR:
3879 case REQ_TOGGLE_FILENAME:
3880 case REQ_TOGGLE_GRAPHIC:
3881 case REQ_TOGGLE_REV_GRAPH:
3882 case REQ_TOGGLE_REFS:
3883 case REQ_TOGGLE_CHANGES:
3884 case REQ_TOGGLE_IGNORE_SPACE:
3885 case REQ_TOGGLE_ID:
3886 case REQ_TOGGLE_FILES:
3887 case REQ_TOGGLE_TITLE_OVERFLOW:
3888 case REQ_TOGGLE_FILE_SIZE:
3889 case REQ_TOGGLE_UNTRACKED_DIRS:
3890 case REQ_TOGGLE_VERTICAL_SPLIT:
3892 char action[SIZEOF_STR] = "";
3893 enum view_flag flags = toggle_option(view, request, action);
3895 if (flags == VIEW_FLAG_RESET_DISPLAY) {
3896 resize_display();
3897 redraw_display(TRUE);
3898 } else {
3899 foreach_displayed_view(view, i) {
3900 if (view_has_flags(view, flags) && !view->unrefreshable)
3901 reload_view(view);
3902 else
3903 redraw_view(view);
3907 if (*action)
3908 report("%s", action);
3910 break;
3912 case REQ_TOGGLE_SORT_FIELD:
3913 case REQ_TOGGLE_SORT_ORDER:
3914 report("Sorting is not yet supported for the %s view", view->name);
3915 break;
3917 case REQ_DIFF_CONTEXT_UP:
3918 case REQ_DIFF_CONTEXT_DOWN:
3919 report("Changing the diff context is not yet supported for the %s view", view->name);
3920 break;
3922 case REQ_SEARCH:
3923 case REQ_SEARCH_BACK:
3924 search_view(view, request);
3925 break;
3927 case REQ_FIND_NEXT:
3928 case REQ_FIND_PREV:
3929 find_next(view, request);
3930 break;
3932 case REQ_STOP_LOADING:
3933 foreach_view(view, i) {
3934 if (view->pipe)
3935 report("Stopped loading the %s view", view->name),
3936 end_update(view, TRUE);
3938 break;
3940 case REQ_SHOW_VERSION:
3941 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3942 return TRUE;
3944 case REQ_SCREEN_REDRAW:
3945 redraw_display(TRUE);
3946 break;
3948 case REQ_EDIT:
3949 report("Nothing to edit");
3950 break;
3952 case REQ_ENTER:
3953 report("Nothing to enter");
3954 break;
3956 case REQ_VIEW_CLOSE:
3957 /* XXX: Mark closed views by letting view->prev point to the
3958 * view itself. Parents to closed view should never be
3959 * followed. */
3960 if (view->prev && view->prev != view) {
3961 maximize_view(view->prev, TRUE);
3962 view->prev = view;
3963 break;
3965 /* Fall-through */
3966 case REQ_QUIT:
3967 return FALSE;
3969 default:
3970 report("Unknown key, press %s for help",
3971 get_view_key(view, REQ_VIEW_HELP));
3972 return TRUE;
3975 return TRUE;
3980 * View backend utilities
3983 enum sort_field {
3984 ORDERBY_NAME,
3985 ORDERBY_DATE,
3986 ORDERBY_AUTHOR,
3989 struct sort_state {
3990 const enum sort_field *fields;
3991 size_t size, current;
3992 bool reverse;
3995 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3996 #define get_sort_field(state) ((state).fields[(state).current])
3997 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3999 static void
4000 sort_view(struct view *view, enum request request, struct sort_state *state,
4001 int (*compare)(const void *, const void *))
4003 switch (request) {
4004 case REQ_TOGGLE_SORT_FIELD:
4005 state->current = (state->current + 1) % state->size;
4006 break;
4008 case REQ_TOGGLE_SORT_ORDER:
4009 state->reverse = !state->reverse;
4010 break;
4011 default:
4012 die("Not a sort request");
4015 qsort(view->line, view->lines, sizeof(*view->line), compare);
4016 redraw_view(view);
4019 static bool
4020 update_diff_context(enum request request)
4022 int diff_context = opt_diff_context;
4024 switch (request) {
4025 case REQ_DIFF_CONTEXT_UP:
4026 opt_diff_context += 1;
4027 update_diff_context_arg(opt_diff_context);
4028 break;
4030 case REQ_DIFF_CONTEXT_DOWN:
4031 if (opt_diff_context == 0) {
4032 report("Diff context cannot be less than zero");
4033 break;
4035 opt_diff_context -= 1;
4036 update_diff_context_arg(opt_diff_context);
4037 break;
4039 default:
4040 die("Not a diff context request");
4043 return diff_context != opt_diff_context;
4046 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
4048 /* Small cache to reduce memory consumption. It uses binary search to
4049 * lookup or find place to position new entries. No entries are ever
4050 * freed. */
4051 static const char *
4052 get_path(const char *path)
4054 static const char **paths;
4055 static size_t paths_size;
4056 int from = 0, to = paths_size - 1;
4057 char *entry;
4059 while (from <= to) {
4060 size_t pos = (to + from) / 2;
4061 int cmp = strcmp(path, paths[pos]);
4063 if (!cmp)
4064 return paths[pos];
4066 if (cmp < 0)
4067 to = pos - 1;
4068 else
4069 from = pos + 1;
4072 if (!realloc_paths(&paths, paths_size, 1))
4073 return NULL;
4074 entry = strdup(path);
4075 if (!entry)
4076 return NULL;
4078 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4079 paths[from] = entry;
4080 paths_size++;
4082 return entry;
4085 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4087 /* Small author cache to reduce memory consumption. It uses binary
4088 * search to lookup or find place to position new entries. No entries
4089 * are ever freed. */
4090 static struct ident *
4091 get_author(const char *name, const char *email)
4093 static struct ident **authors;
4094 static size_t authors_size;
4095 int from = 0, to = authors_size - 1;
4096 struct ident *ident;
4098 while (from <= to) {
4099 size_t pos = (to + from) / 2;
4100 int cmp = strcmp(name, authors[pos]->name);
4102 if (!cmp)
4103 return authors[pos];
4105 if (cmp < 0)
4106 to = pos - 1;
4107 else
4108 from = pos + 1;
4111 if (!realloc_authors(&authors, authors_size, 1))
4112 return NULL;
4113 ident = calloc(1, sizeof(*ident));
4114 if (!ident)
4115 return NULL;
4116 ident->name = strdup(name);
4117 ident->email = strdup(email);
4118 if (!ident->name || !ident->email) {
4119 free((void *) ident->name);
4120 free(ident);
4121 return NULL;
4124 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4125 authors[from] = ident;
4126 authors_size++;
4128 return ident;
4131 static void
4132 parse_timesec(struct time *time, const char *sec)
4134 time->sec = (time_t) atol(sec);
4137 static void
4138 parse_timezone(struct time *time, const char *zone)
4140 long tz;
4142 tz = ('0' - zone[1]) * 60 * 60 * 10;
4143 tz += ('0' - zone[2]) * 60 * 60;
4144 tz += ('0' - zone[3]) * 60 * 10;
4145 tz += ('0' - zone[4]) * 60;
4147 if (zone[0] == '-')
4148 tz = -tz;
4150 time->tz = tz;
4151 time->sec -= tz;
4154 /* Parse author lines where the name may be empty:
4155 * author <email@address.tld> 1138474660 +0100
4157 static void
4158 parse_author_line(char *ident, const struct ident **author, struct time *time)
4160 char *nameend = strchr(ident, '<');
4161 char *emailend = strchr(ident, '>');
4162 const char *name, *email = "";
4164 if (nameend && emailend)
4165 *nameend = *emailend = 0;
4166 name = chomp_string(ident);
4167 if (nameend)
4168 email = chomp_string(nameend + 1);
4169 if (!*name)
4170 name = *email ? email : unknown_ident.name;
4171 if (!*email)
4172 email = *name ? name : unknown_ident.email;
4174 *author = get_author(name, email);
4176 /* Parse epoch and timezone */
4177 if (time && emailend && emailend[1] == ' ') {
4178 char *secs = emailend + 2;
4179 char *zone = strchr(secs, ' ');
4181 parse_timesec(time, secs);
4183 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4184 parse_timezone(time, zone + 1);
4188 static struct line *
4189 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4191 for (; view_has_line(view, line); line += direction)
4192 if (line->type == type)
4193 return line;
4195 return NULL;
4198 #define find_prev_line_by_type(view, line, type) \
4199 find_line_by_type(view, line, type, -1)
4201 #define find_next_line_by_type(view, line, type) \
4202 find_line_by_type(view, line, type, 1)
4205 * View history
4208 struct view_state {
4209 struct view_state *prev; /* Entry below this in the stack */
4210 struct position position; /* View position to restore */
4211 void *data; /* View specific state */
4214 struct view_history {
4215 size_t state_alloc;
4216 struct view_state *stack;
4217 struct position position;
4220 static bool
4221 view_history_is_empty(struct view_history *history)
4223 return !history->stack;
4226 static struct view_state *
4227 push_view_history_state(struct view_history *history, struct position *position, void *data)
4229 struct view_state *state = history->stack;
4231 if (state && data && history->state_alloc &&
4232 !memcmp(state->data, data, history->state_alloc))
4233 return NULL;
4235 state = calloc(1, sizeof(*state) + history->state_alloc);
4236 if (!state)
4237 return NULL;
4239 state->prev = history->stack;
4240 history->stack = state;
4241 clear_position(&history->position);
4242 state->position = *position;
4243 state->data = &state[1];
4244 if (data && history->state_alloc)
4245 memcpy(state->data, data, history->state_alloc);
4246 return state;
4249 static bool
4250 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4252 struct view_state *state = history->stack;
4254 if (view_history_is_empty(history))
4255 return FALSE;
4257 history->position = state->position;
4258 history->stack = state->prev;
4260 if (data && history->state_alloc)
4261 memcpy(data, state->data, history->state_alloc);
4262 if (position)
4263 *position = state->position;
4265 free(state);
4266 return TRUE;
4269 static void
4270 reset_view_history(struct view_history *history)
4272 while (pop_view_history_state(history, NULL, NULL))
4277 * Blame
4280 struct blame_commit {
4281 char id[SIZEOF_REV]; /* SHA1 ID. */
4282 char title[128]; /* First line of the commit message. */
4283 const struct ident *author; /* Author of the commit. */
4284 struct time time; /* Date from the author ident. */
4285 const char *filename; /* Name of file. */
4286 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4287 const char *parent_filename; /* Parent/previous name of file. */
4290 struct blame_header {
4291 char id[SIZEOF_REV]; /* SHA1 ID. */
4292 size_t orig_lineno;
4293 size_t lineno;
4294 size_t group;
4297 static bool
4298 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4300 const char *pos = *posref;
4302 *posref = NULL;
4303 pos = strchr(pos + 1, ' ');
4304 if (!pos || !isdigit(pos[1]))
4305 return FALSE;
4306 *number = atoi(pos + 1);
4307 if (*number < min || *number > max)
4308 return FALSE;
4310 *posref = pos;
4311 return TRUE;
4314 static bool
4315 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4317 const char *pos = text + SIZEOF_REV - 2;
4319 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4320 return FALSE;
4322 string_ncopy(header->id, text, SIZEOF_REV);
4324 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4325 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4326 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4327 return FALSE;
4329 return TRUE;
4332 static bool
4333 match_blame_header(const char *name, char **line)
4335 size_t namelen = strlen(name);
4336 bool matched = !strncmp(name, *line, namelen);
4338 if (matched)
4339 *line += namelen;
4341 return matched;
4344 static bool
4345 parse_blame_info(struct blame_commit *commit, char *line)
4347 if (match_blame_header("author ", &line)) {
4348 parse_author_line(line, &commit->author, NULL);
4350 } else if (match_blame_header("author-time ", &line)) {
4351 parse_timesec(&commit->time, line);
4353 } else if (match_blame_header("author-tz ", &line)) {
4354 parse_timezone(&commit->time, line);
4356 } else if (match_blame_header("summary ", &line)) {
4357 string_ncopy(commit->title, line, strlen(line));
4359 } else if (match_blame_header("previous ", &line)) {
4360 if (strlen(line) <= SIZEOF_REV)
4361 return FALSE;
4362 string_copy_rev(commit->parent_id, line);
4363 line += SIZEOF_REV;
4364 commit->parent_filename = get_path(line);
4365 if (!commit->parent_filename)
4366 return TRUE;
4368 } else if (match_blame_header("filename ", &line)) {
4369 commit->filename = get_path(line);
4370 return TRUE;
4373 return FALSE;
4377 * Pager backend
4380 static bool
4381 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4383 if (draw_lineno(view, lineno))
4384 return TRUE;
4386 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4387 return TRUE;
4389 draw_text(view, line->type, line->data);
4390 return TRUE;
4393 static bool
4394 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4396 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4397 char ref[SIZEOF_STR];
4399 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4400 return TRUE;
4402 /* This is the only fatal call, since it can "corrupt" the buffer. */
4403 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4404 return FALSE;
4406 return TRUE;
4409 static void
4410 add_pager_refs(struct view *view, const char *commit_id)
4412 char buf[SIZEOF_STR];
4413 struct ref_list *list;
4414 size_t bufpos = 0, i;
4415 const char *sep = "Refs: ";
4416 bool is_tag = FALSE;
4418 list = get_ref_list(commit_id);
4419 if (!list) {
4420 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4421 goto try_add_describe_ref;
4422 return;
4425 for (i = 0; i < list->size; i++) {
4426 struct ref *ref = list->refs[i];
4427 const char *fmt = ref->tag ? "%s[%s]" :
4428 ref->remote ? "%s<%s>" : "%s%s";
4430 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4431 return;
4432 sep = ", ";
4433 if (ref->tag)
4434 is_tag = TRUE;
4437 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4438 try_add_describe_ref:
4439 /* Add <tag>-g<commit_id> "fake" reference. */
4440 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4441 return;
4444 if (bufpos == 0)
4445 return;
4447 add_line_text(view, buf, LINE_PP_REFS);
4450 static struct line *
4451 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4453 size_t first_line = 0;
4454 bool has_first_line = FALSE;
4455 size_t datalen = strlen(data);
4456 size_t lineno = 0;
4458 while (datalen > 0 || !has_first_line) {
4459 bool wrapped = !!first_line;
4460 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4461 struct line *line;
4462 char *text;
4464 line = add_line(view, NULL, type, linelen + 1, wrapped);
4465 if (!line)
4466 break;
4467 if (!has_first_line) {
4468 first_line = view->lines - 1;
4469 has_first_line = TRUE;
4472 if (!wrapped)
4473 lineno = line->lineno;
4475 line->wrapped = wrapped;
4476 line->lineno = lineno;
4477 text = line->data;
4478 if (linelen)
4479 strncpy(text, data, linelen);
4480 text[linelen] = 0;
4482 datalen -= linelen;
4483 data += linelen;
4486 return has_first_line ? &view->line[first_line] : NULL;
4489 static bool
4490 pager_common_read(struct view *view, const char *data, enum line_type type)
4492 struct line *line;
4494 if (!data)
4495 return TRUE;
4497 if (opt_wrap_lines) {
4498 line = pager_wrap_line(view, data, type);
4499 } else {
4500 line = add_line_text(view, data, type);
4503 if (!line)
4504 return FALSE;
4506 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4507 add_pager_refs(view, data + STRING_SIZE("commit "));
4509 return TRUE;
4512 static bool
4513 pager_read(struct view *view, char *data)
4515 if (!data)
4516 return TRUE;
4518 return pager_common_read(view, data, get_line_type(data));
4521 static enum request
4522 pager_request(struct view *view, enum request request, struct line *line)
4524 int split = 0;
4526 if (request != REQ_ENTER)
4527 return request;
4529 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4530 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4531 split = 1;
4534 /* Always scroll the view even if it was split. That way
4535 * you can use Enter to scroll through the log view and
4536 * split open each commit diff. */
4537 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4539 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4540 * but if we are scrolling a non-current view this won't properly
4541 * update the view title. */
4542 if (split)
4543 update_view_title(view);
4545 return REQ_NONE;
4548 static bool
4549 pager_grep(struct view *view, struct line *line)
4551 const char *text[] = { line->data, NULL };
4553 return grep_text(view, text);
4556 static void
4557 pager_select(struct view *view, struct line *line)
4559 if (line->type == LINE_COMMIT) {
4560 string_copy_rev_from_commit_line(ref_commit, line->data);
4561 if (!view_has_flags(view, VIEW_NO_REF))
4562 string_copy_rev(view->ref, ref_commit);
4566 struct log_state {
4567 /* Used for tracking when we need to recalculate the previous
4568 * commit, for example when the user scrolls up or uses the page
4569 * up/down in the log view. */
4570 int last_lineno;
4571 enum line_type last_type;
4574 static void
4575 log_select(struct view *view, struct line *line)
4577 struct log_state *state = view->private;
4578 int last_lineno = state->last_lineno;
4580 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4581 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4582 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4584 if (commit_line)
4585 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4588 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4589 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4591 string_copy_rev(ref_commit, view->ref);
4592 state->last_lineno = line->lineno;
4593 state->last_type = line->type;
4596 static bool
4597 pager_open(struct view *view, enum open_flags flags)
4599 if (!open_from_stdin(flags) && !view->lines) {
4600 report("No pager content, press %s to run command from prompt",
4601 get_view_key(view, REQ_PROMPT));
4602 return FALSE;
4605 return begin_update(view, NULL, NULL, flags);
4608 static struct view_ops pager_ops = {
4609 "line",
4610 { "pager" },
4611 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4613 pager_open,
4614 pager_read,
4615 pager_draw,
4616 pager_request,
4617 pager_grep,
4618 pager_select,
4621 static bool
4622 log_open(struct view *view, enum open_flags flags)
4624 static const char *log_argv[] = {
4625 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4628 return begin_update(view, NULL, log_argv, flags);
4631 static enum request
4632 log_request(struct view *view, enum request request, struct line *line)
4634 switch (request) {
4635 case REQ_REFRESH:
4636 load_refs(TRUE);
4637 refresh_view(view);
4638 return REQ_NONE;
4640 case REQ_ENTER:
4641 if (!display[1] || strcmp(display[1]->vid, view->ref))
4642 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4643 return REQ_NONE;
4645 default:
4646 return request;
4650 static struct view_ops log_ops = {
4651 "line",
4652 { "log" },
4653 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4654 sizeof(struct log_state),
4655 log_open,
4656 pager_read,
4657 pager_draw,
4658 log_request,
4659 pager_grep,
4660 log_select,
4663 struct diff_state {
4664 bool after_commit_title;
4665 bool after_diff;
4666 bool reading_diff_stat;
4667 bool combined_diff;
4670 #define DIFF_LINE_COMMIT_TITLE 1
4672 static bool
4673 diff_open(struct view *view, enum open_flags flags)
4675 static const char *diff_argv[] = {
4676 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4677 "--patch-with-stat",
4678 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4679 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4682 return begin_update(view, NULL, diff_argv, flags);
4685 static bool
4686 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4688 enum line_type type = get_line_type(data);
4690 if (!view->lines && type != LINE_COMMIT)
4691 state->reading_diff_stat = TRUE;
4693 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4694 state->reading_diff_stat = TRUE;
4696 if (state->reading_diff_stat) {
4697 size_t len = strlen(data);
4698 char *pipe = strchr(data, '|');
4699 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4700 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4701 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4702 bool has_no_change = pipe && strstr(pipe, " 0");
4704 if (pipe && (has_histogram || has_bin_diff || has_rename || has_no_change)) {
4705 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4706 } else {
4707 state->reading_diff_stat = FALSE;
4710 } else if (!strcmp(data, "---")) {
4711 state->reading_diff_stat = TRUE;
4714 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4715 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4717 if (line)
4718 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4719 state->after_commit_title = TRUE;
4720 return line != NULL;
4723 if (type == LINE_DIFF_HEADER) {
4724 const int len = line_info[LINE_DIFF_HEADER].linelen;
4726 state->after_diff = TRUE;
4727 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4728 !strncmp(data + len, "cc ", strlen("cc ")))
4729 state->combined_diff = TRUE;
4731 } else if (type == LINE_PP_MERGE) {
4732 state->combined_diff = TRUE;
4735 /* ADD2 and DEL2 are only valid in combined diff hunks */
4736 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4737 type = LINE_DEFAULT;
4739 return pager_common_read(view, data, type);
4742 static bool
4743 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4745 struct line *marker = find_next_line_by_type(view, line, type);
4747 return marker &&
4748 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4751 static enum request
4752 diff_common_enter(struct view *view, enum request request, struct line *line)
4754 if (line->type == LINE_DIFF_STAT) {
4755 int file_number = 0;
4757 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4758 file_number++;
4759 line--;
4762 for (line = view->line; view_has_line(view, line); line++) {
4763 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4764 if (!line)
4765 break;
4767 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4768 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4769 if (file_number == 1) {
4770 break;
4772 file_number--;
4776 if (!line) {
4777 report("Failed to find file diff");
4778 return REQ_NONE;
4781 select_view_line(view, line - view->line);
4782 report_clear();
4783 return REQ_NONE;
4785 } else {
4786 return pager_request(view, request, line);
4790 static bool
4791 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4793 char *sep = strchr(*text, c);
4795 if (sep != NULL) {
4796 *sep = 0;
4797 draw_text(view, *type, *text);
4798 *sep = c;
4799 *text = sep;
4800 *type = next_type;
4803 return sep != NULL;
4806 static bool
4807 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4809 char *text = line->data;
4810 enum line_type type = line->type;
4812 if (draw_lineno(view, lineno))
4813 return TRUE;
4815 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4816 return TRUE;
4818 if (type == LINE_DIFF_STAT) {
4819 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4820 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4821 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4822 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4823 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4824 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4825 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4827 } else {
4828 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4829 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4833 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4834 draw_commit_title(view, text, 4);
4835 else
4836 draw_text(view, type, text);
4837 return TRUE;
4840 static bool
4841 diff_read(struct view *view, char *data)
4843 struct diff_state *state = view->private;
4845 if (!data) {
4846 /* Fall back to retry if no diff will be shown. */
4847 if (view->lines == 0 && opt_file_argv) {
4848 int pos = argv_size(view->argv)
4849 - argv_size(opt_file_argv) - 1;
4851 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4852 for (; view->argv[pos]; pos++) {
4853 free((void *) view->argv[pos]);
4854 view->argv[pos] = NULL;
4857 if (view->pipe)
4858 io_done(view->pipe);
4859 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4860 return FALSE;
4863 return TRUE;
4866 return diff_common_read(view, data, state);
4869 static bool
4870 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4871 struct blame_header *header, struct blame_commit *commit)
4873 char line_arg[SIZEOF_STR];
4874 const char *blame_argv[] = {
4875 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4877 struct io io;
4878 bool ok = FALSE;
4879 char *buf;
4881 if (!string_format(line_arg, "-L%ld,+1", lineno))
4882 return FALSE;
4884 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4885 return FALSE;
4887 while ((buf = io_get(&io, '\n', TRUE))) {
4888 if (header) {
4889 if (!parse_blame_header(header, buf, 9999999))
4890 break;
4891 header = NULL;
4893 } else if (parse_blame_info(commit, buf)) {
4894 ok = commit->filename != NULL;
4895 break;
4899 if (io_error(&io))
4900 ok = FALSE;
4902 io_done(&io);
4903 return ok;
4906 struct chunk_header_position {
4907 unsigned long position;
4908 unsigned long lines;
4911 struct chunk_header {
4912 struct chunk_header_position old;
4913 struct chunk_header_position new;
4916 static bool
4917 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
4919 const char *start = *pos_ptr;
4920 char *end;
4922 if (!isdigit(*start))
4923 return 0;
4925 *value = strtoul(start, &end, 10);
4926 if (end == start)
4927 return FALSE;
4929 start = end;
4930 while (skip && *start && strchr(skip, *start))
4931 start++;
4932 *pos_ptr = start;
4933 return TRUE;
4936 static bool
4937 parse_chunk_header(struct chunk_header *header, const char *line)
4939 memset(header, 0, sizeof(*header));
4941 if (prefixcmp(line, "@@ -"))
4942 return FALSE;
4944 line += STRING_SIZE("@@ -");
4946 return parse_ulong(&line, &header->old.position, ",") &&
4947 parse_ulong(&line, &header->old.lines, " +") &&
4948 parse_ulong(&line, &header->new.position, ",") &&
4949 parse_ulong(&line, &header->new.lines, NULL);
4952 static unsigned int
4953 diff_get_lineno(struct view *view, struct line *line)
4955 const struct line *header, *chunk;
4956 unsigned int lineno;
4957 struct chunk_header chunk_header;
4959 /* Verify that we are after a diff header and one of its chunks */
4960 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4961 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4962 if (!header || !chunk || chunk < header)
4963 return 0;
4966 * In a chunk header, the number after the '+' sign is the number of its
4967 * following line, in the new version of the file. We increment this
4968 * number for each non-deletion line, until the given line position.
4970 if (!parse_chunk_header(&chunk_header, chunk->data))
4971 return 0;
4973 lineno = chunk_header.new.position;
4974 chunk++;
4975 while (chunk++ < line)
4976 if (chunk->type != LINE_DIFF_DEL)
4977 lineno++;
4979 return lineno;
4982 static bool
4983 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
4985 struct chunk_header chunk_header;
4987 *lineno = 0;
4989 if (!parse_chunk_header(&chunk_header, chunk))
4990 return FALSE;
4992 *lineno = marker == '-' ? chunk_header.old.position : chunk_header.new.position;
4993 return TRUE;
4996 static enum request
4997 diff_trace_origin(struct view *view, struct line *line)
4999 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5000 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
5001 const char *chunk_data;
5002 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
5003 unsigned long lineno = 0;
5004 const char *file = NULL;
5005 char ref[SIZEOF_REF];
5006 struct blame_header header;
5007 struct blame_commit commit;
5009 if (!diff || !chunk || chunk == line) {
5010 report("The line to trace must be inside a diff chunk");
5011 return REQ_NONE;
5014 for (; diff < line && !file; diff++) {
5015 const char *data = diff->data;
5017 if (!prefixcmp(data, "--- a/")) {
5018 file = data + STRING_SIZE("--- a/");
5019 break;
5023 if (diff == line || !file) {
5024 report("Failed to read the file name");
5025 return REQ_NONE;
5028 chunk_data = chunk->data;
5030 if (!parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
5031 report("Failed to read the line number");
5032 return REQ_NONE;
5035 if (lineno == 0) {
5036 report("This is the origin of the line");
5037 return REQ_NONE;
5040 for (chunk += 1; chunk < line; chunk++) {
5041 if (chunk->type == LINE_DIFF_ADD) {
5042 lineno += chunk_marker == '+';
5043 } else if (chunk->type == LINE_DIFF_DEL) {
5044 lineno += chunk_marker == '-';
5045 } else {
5046 lineno++;
5050 if (chunk_marker == '+')
5051 string_copy(ref, view->vid);
5052 else
5053 string_format(ref, "%s^", view->vid);
5055 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
5056 report("Failed to read blame data");
5057 return REQ_NONE;
5060 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
5061 string_copy(opt_ref, header.id);
5062 opt_goto_line = header.orig_lineno - 1;
5064 return REQ_VIEW_BLAME;
5067 static const char *
5068 diff_get_pathname(struct view *view, struct line *line)
5070 const struct line *header;
5071 const char *dst = NULL;
5072 const char *prefixes[] = { " b/", "cc ", "combined " };
5073 int i;
5075 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5076 if (!header)
5077 return NULL;
5079 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
5080 dst = strstr(header->data, prefixes[i]);
5082 return dst ? dst + strlen(prefixes[--i]) : NULL;
5085 static enum request
5086 diff_common_edit(struct view *view, enum request request, struct line *line)
5088 const char *file = diff_get_pathname(view, line);
5089 char path[SIZEOF_STR];
5090 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
5092 if (has_path && access(path, R_OK)) {
5093 report("Failed to open file: %s", file);
5094 return REQ_NONE;
5097 open_editor(file, diff_get_lineno(view, line));
5098 return REQ_NONE;
5101 static enum request
5102 diff_request(struct view *view, enum request request, struct line *line)
5104 switch (request) {
5105 case REQ_VIEW_BLAME:
5106 return diff_trace_origin(view, line);
5108 case REQ_DIFF_CONTEXT_UP:
5109 case REQ_DIFF_CONTEXT_DOWN:
5110 if (!update_diff_context(request))
5111 return REQ_NONE;
5112 reload_view(view);
5113 return REQ_NONE;
5116 case REQ_EDIT:
5117 return diff_common_edit(view, request, line);
5119 case REQ_ENTER:
5120 return diff_common_enter(view, request, line);
5122 case REQ_REFRESH:
5123 if (string_rev_is_null(view->vid))
5124 refresh_view(view);
5125 else
5126 reload_view(view);
5127 return REQ_NONE;
5129 default:
5130 return pager_request(view, request, line);
5134 static void
5135 diff_select(struct view *view, struct line *line)
5137 if (line->type == LINE_DIFF_STAT) {
5138 string_format(view->ref, "Press '%s' to jump to file diff",
5139 get_view_key(view, REQ_ENTER));
5140 } else {
5141 const char *file = diff_get_pathname(view, line);
5143 if (file) {
5144 string_format(view->ref, "Changes to '%s'", file);
5145 string_format(opt_file, "%s", file);
5146 ref_blob[0] = 0;
5147 } else {
5148 string_ncopy(view->ref, view->id, strlen(view->id));
5149 pager_select(view, line);
5154 static struct view_ops diff_ops = {
5155 "line",
5156 { "diff" },
5157 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5158 sizeof(struct diff_state),
5159 diff_open,
5160 diff_read,
5161 diff_common_draw,
5162 diff_request,
5163 pager_grep,
5164 diff_select,
5168 * Help backend
5171 static bool
5172 help_draw(struct view *view, struct line *line, unsigned int lineno)
5174 if (line->type == LINE_HELP_KEYMAP) {
5175 struct keymap *keymap = line->data;
5177 draw_formatted(view, line->type, "[%c] %s bindings",
5178 keymap->hidden ? '+' : '-', keymap->name);
5179 return TRUE;
5180 } else {
5181 return pager_draw(view, line, lineno);
5185 static bool
5186 help_open_keymap_title(struct view *view, struct keymap *keymap)
5188 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5189 return keymap->hidden;
5192 static void
5193 help_open_keymap(struct view *view, struct keymap *keymap)
5195 const char *group = NULL;
5196 char buf[SIZEOF_STR];
5197 bool add_title = TRUE;
5198 int i;
5200 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5201 const char *key = NULL;
5203 if (req_info[i].request == REQ_NONE)
5204 continue;
5206 if (!req_info[i].request) {
5207 group = req_info[i].help;
5208 continue;
5211 key = get_keys(keymap, req_info[i].request, TRUE);
5212 if (!key || !*key)
5213 continue;
5215 if (add_title && help_open_keymap_title(view, keymap))
5216 return;
5217 add_title = FALSE;
5219 if (group) {
5220 add_line_text(view, group, LINE_HELP_GROUP);
5221 group = NULL;
5224 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5225 enum_name(req_info[i]), req_info[i].help);
5228 group = "External commands:";
5230 for (i = 0; i < run_requests; i++) {
5231 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5232 const char *key;
5234 if (!req || req->keymap != keymap)
5235 continue;
5237 key = get_key_name(req->key);
5238 if (!*key)
5239 key = "(no key defined)";
5241 if (add_title && help_open_keymap_title(view, keymap))
5242 return;
5243 add_title = FALSE;
5245 if (group) {
5246 add_line_text(view, group, LINE_HELP_GROUP);
5247 group = NULL;
5250 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5251 return;
5253 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5257 static bool
5258 help_open(struct view *view, enum open_flags flags)
5260 struct keymap *keymap;
5262 reset_view(view);
5263 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5264 add_line_text(view, "", LINE_DEFAULT);
5266 for (keymap = keymaps; keymap; keymap = keymap->next)
5267 help_open_keymap(view, keymap);
5269 return TRUE;
5272 static enum request
5273 help_request(struct view *view, enum request request, struct line *line)
5275 switch (request) {
5276 case REQ_ENTER:
5277 if (line->type == LINE_HELP_KEYMAP) {
5278 struct keymap *keymap = line->data;
5280 keymap->hidden = !keymap->hidden;
5281 refresh_view(view);
5284 return REQ_NONE;
5285 default:
5286 return pager_request(view, request, line);
5290 static void
5291 help_done(struct view *view)
5293 int i;
5295 for (i = 0; i < view->lines; i++)
5296 if (view->line[i].type == LINE_HELP_KEYMAP)
5297 view->line[i].data = NULL;
5300 static struct view_ops help_ops = {
5301 "line",
5302 { "help" },
5303 VIEW_NO_GIT_DIR,
5305 help_open,
5306 NULL,
5307 help_draw,
5308 help_request,
5309 pager_grep,
5310 pager_select,
5311 help_done,
5316 * Tree backend
5319 /* The top of the path stack. */
5320 static struct view_history tree_view_history = { sizeof(char *) };
5322 static void
5323 pop_tree_stack_entry(struct position *position)
5325 char *path_position = NULL;
5327 pop_view_history_state(&tree_view_history, position, &path_position);
5328 path_position[0] = 0;
5331 static void
5332 push_tree_stack_entry(const char *name, struct position *position)
5334 size_t pathlen = strlen(opt_path);
5335 char *path_position = opt_path + pathlen;
5336 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5338 if (!state)
5339 return;
5341 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5342 pop_tree_stack_entry(NULL);
5343 return;
5346 clear_position(position);
5349 /* Parse output from git-ls-tree(1):
5351 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5354 #define SIZEOF_TREE_ATTR \
5355 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5357 #define SIZEOF_TREE_MODE \
5358 STRING_SIZE("100644 ")
5360 #define TREE_ID_OFFSET \
5361 STRING_SIZE("100644 blob ")
5363 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5365 struct tree_entry {
5366 char id[SIZEOF_REV];
5367 char commit[SIZEOF_REV];
5368 mode_t mode;
5369 struct time time; /* Date from the author ident. */
5370 const struct ident *author; /* Author of the commit. */
5371 unsigned long size;
5372 char name[1];
5375 struct tree_state {
5376 char commit[SIZEOF_REV];
5377 const struct ident *author;
5378 struct time author_time;
5379 int size_width;
5380 bool read_date;
5383 static const char *
5384 tree_path(const struct line *line)
5386 return ((struct tree_entry *) line->data)->name;
5389 static int
5390 tree_compare_entry(const struct line *line1, const struct line *line2)
5392 if (line1->type != line2->type)
5393 return line1->type == LINE_TREE_DIR ? -1 : 1;
5394 return strcmp(tree_path(line1), tree_path(line2));
5397 static const enum sort_field tree_sort_fields[] = {
5398 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5400 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5402 static int
5403 tree_compare(const void *l1, const void *l2)
5405 const struct line *line1 = (const struct line *) l1;
5406 const struct line *line2 = (const struct line *) l2;
5407 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5408 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5410 if (line1->type == LINE_TREE_HEAD)
5411 return -1;
5412 if (line2->type == LINE_TREE_HEAD)
5413 return 1;
5415 switch (get_sort_field(tree_sort_state)) {
5416 case ORDERBY_DATE:
5417 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5419 case ORDERBY_AUTHOR:
5420 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5422 case ORDERBY_NAME:
5423 default:
5424 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5429 static struct line *
5430 tree_entry(struct view *view, enum line_type type, const char *path,
5431 const char *mode, const char *id, unsigned long size)
5433 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5434 struct tree_entry *entry;
5435 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5437 if (!line)
5438 return NULL;
5440 strncpy(entry->name, path, strlen(path));
5441 if (mode)
5442 entry->mode = strtoul(mode, NULL, 8);
5443 if (id)
5444 string_copy_rev(entry->id, id);
5445 entry->size = size;
5447 return line;
5450 static bool
5451 tree_read_date(struct view *view, char *text, struct tree_state *state)
5453 if (!text && state->read_date) {
5454 state->read_date = FALSE;
5455 return TRUE;
5457 } else if (!text) {
5458 /* Find next entry to process */
5459 const char *log_file[] = {
5460 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5461 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5464 if (!view->lines) {
5465 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5466 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5467 report("Tree is empty");
5468 return TRUE;
5471 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5472 report("Failed to load tree data");
5473 return TRUE;
5476 state->read_date = TRUE;
5477 return FALSE;
5479 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5480 string_copy_rev_from_commit_line(state->commit, text);
5482 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5483 parse_author_line(text + STRING_SIZE("author "),
5484 &state->author, &state->author_time);
5486 } else if (*text == ':') {
5487 char *pos;
5488 size_t annotated = 1;
5489 size_t i;
5491 pos = strchr(text, '\t');
5492 if (!pos)
5493 return TRUE;
5494 text = pos + 1;
5495 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5496 text += strlen(opt_path);
5497 pos = strchr(text, '/');
5498 if (pos)
5499 *pos = 0;
5501 for (i = 1; i < view->lines; i++) {
5502 struct line *line = &view->line[i];
5503 struct tree_entry *entry = line->data;
5505 annotated += !!entry->author;
5506 if (entry->author || strcmp(entry->name, text))
5507 continue;
5509 string_copy_rev(entry->commit, state->commit);
5510 entry->author = state->author;
5511 entry->time = state->author_time;
5512 line->dirty = 1;
5513 break;
5516 if (annotated == view->lines)
5517 io_kill(view->pipe);
5519 return TRUE;
5522 static inline size_t
5523 parse_size(const char *text, int *max_digits)
5525 size_t size = 0;
5526 int digits = 0;
5528 while (*text == ' ')
5529 text++;
5531 while (isdigit(*text)) {
5532 size = (size * 10) + (*text++ - '0');
5533 digits++;
5536 if (digits > *max_digits)
5537 *max_digits = digits;
5539 return size;
5542 static bool
5543 tree_read(struct view *view, char *text)
5545 struct tree_state *state = view->private;
5546 struct tree_entry *data;
5547 struct line *entry, *line;
5548 enum line_type type;
5549 size_t textlen = text ? strlen(text) : 0;
5550 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5551 char *path;
5552 size_t size;
5554 if (state->read_date || !text)
5555 return tree_read_date(view, text, state);
5557 if (textlen <= SIZEOF_TREE_ATTR)
5558 return FALSE;
5559 if (view->lines == 0 &&
5560 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5561 return FALSE;
5563 size = parse_size(attr_offset, &state->size_width);
5564 path = strchr(attr_offset, '\t');
5565 if (!path)
5566 return FALSE;
5567 path++;
5569 /* Strip the path part ... */
5570 if (*opt_path) {
5571 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5572 size_t striplen = strlen(opt_path);
5574 if (pathlen > striplen)
5575 memmove(path, path + striplen,
5576 pathlen - striplen + 1);
5578 /* Insert "link" to parent directory. */
5579 if (view->lines == 1 &&
5580 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5581 return FALSE;
5584 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5585 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5586 if (!entry)
5587 return FALSE;
5588 data = entry->data;
5590 /* Skip "Directory ..." and ".." line. */
5591 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5592 if (tree_compare_entry(line, entry) <= 0)
5593 continue;
5595 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5597 line->data = data;
5598 line->type = type;
5599 for (; line <= entry; line++)
5600 line->dirty = line->cleareol = 1;
5601 return TRUE;
5604 /* Move the current line to the first tree entry. */
5605 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5606 goto_view_line(view, 0, 1);
5608 return TRUE;
5611 static bool
5612 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5614 struct tree_state *state = view->private;
5615 struct tree_entry *entry = line->data;
5617 if (line->type == LINE_TREE_HEAD) {
5618 if (draw_text(view, line->type, "Directory path /"))
5619 return TRUE;
5620 } else {
5621 if (draw_mode(view, entry->mode))
5622 return TRUE;
5624 if (draw_author(view, entry->author))
5625 return TRUE;
5627 if (draw_file_size(view, entry->size, state->size_width,
5628 line->type != LINE_TREE_FILE))
5629 return TRUE;
5631 if (draw_date(view, &entry->time))
5632 return TRUE;
5634 if (draw_id(view, entry->commit))
5635 return TRUE;
5638 draw_text(view, line->type, entry->name);
5639 return TRUE;
5642 static void
5643 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5645 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5646 char file[SIZEOF_STR];
5647 int fd;
5649 if (!name)
5650 name = "unknown";
5652 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5653 report("Temporary file name is too long");
5654 return;
5657 fd = mkstemps(file, strlen(name) + 1);
5659 if (fd == -1)
5660 report("Failed to create temporary file");
5661 else if (!io_run_append(blob_argv, fd))
5662 report("Failed to save blob data to file");
5663 else
5664 open_editor(file, lineno);
5665 if (fd != -1)
5666 unlink(file);
5669 static enum request
5670 tree_request(struct view *view, enum request request, struct line *line)
5672 enum open_flags flags;
5673 struct tree_entry *entry = line->data;
5675 switch (request) {
5676 case REQ_VIEW_BLAME:
5677 if (line->type != LINE_TREE_FILE) {
5678 report("Blame only supported for files");
5679 return REQ_NONE;
5682 string_copy(opt_ref, view->vid);
5683 return request;
5685 case REQ_EDIT:
5686 if (line->type != LINE_TREE_FILE) {
5687 report("Edit only supported for files");
5688 } else if (!is_head_commit(view->vid)) {
5689 open_blob_editor(entry->id, entry->name, 0);
5690 } else {
5691 open_editor(opt_file, 0);
5693 return REQ_NONE;
5695 case REQ_TOGGLE_SORT_FIELD:
5696 case REQ_TOGGLE_SORT_ORDER:
5697 sort_view(view, request, &tree_sort_state, tree_compare);
5698 return REQ_NONE;
5700 case REQ_PARENT:
5701 case REQ_BACK:
5702 if (!*opt_path) {
5703 /* quit view if at top of tree */
5704 return REQ_VIEW_CLOSE;
5706 /* fake 'cd ..' */
5707 line = &view->line[1];
5708 break;
5710 case REQ_ENTER:
5711 break;
5713 default:
5714 return request;
5717 /* Cleanup the stack if the tree view is at a different tree. */
5718 if (!*opt_path)
5719 reset_view_history(&tree_view_history);
5721 switch (line->type) {
5722 case LINE_TREE_DIR:
5723 /* Depending on whether it is a subdirectory or parent link
5724 * mangle the path buffer. */
5725 if (line == &view->line[1] && *opt_path) {
5726 pop_tree_stack_entry(&view->pos);
5728 } else {
5729 const char *basename = tree_path(line);
5731 push_tree_stack_entry(basename, &view->pos);
5734 /* Trees and subtrees share the same ID, so they are not not
5735 * unique like blobs. */
5736 flags = OPEN_RELOAD;
5737 request = REQ_VIEW_TREE;
5738 break;
5740 case LINE_TREE_FILE:
5741 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5742 request = REQ_VIEW_BLOB;
5743 break;
5745 default:
5746 return REQ_NONE;
5749 open_view(view, request, flags);
5751 return REQ_NONE;
5754 static bool
5755 tree_grep(struct view *view, struct line *line)
5757 struct tree_entry *entry = line->data;
5758 const char *text[] = {
5759 entry->name,
5760 mkauthor(entry->author, opt_author_width, opt_author),
5761 mkdate(&entry->time, opt_date),
5762 NULL
5765 return grep_text(view, text);
5768 static void
5769 tree_select(struct view *view, struct line *line)
5771 struct tree_entry *entry = line->data;
5773 if (line->type == LINE_TREE_HEAD) {
5774 string_format(view->ref, "Files in /%s", opt_path);
5775 return;
5778 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5779 string_copy(view->ref, "Open parent directory");
5780 ref_blob[0] = 0;
5781 return;
5784 if (line->type == LINE_TREE_FILE) {
5785 string_copy_rev(ref_blob, entry->id);
5786 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5789 string_copy_rev(view->ref, entry->id);
5792 static bool
5793 tree_open(struct view *view, enum open_flags flags)
5795 static const char *tree_argv[] = {
5796 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5799 if (string_rev_is_null(ref_commit)) {
5800 report("No tree exists for this commit");
5801 return FALSE;
5804 if (view->lines == 0 && opt_prefix[0]) {
5805 char *pos = opt_prefix;
5807 while (pos && *pos) {
5808 char *end = strchr(pos, '/');
5810 if (end)
5811 *end = 0;
5812 push_tree_stack_entry(pos, &view->pos);
5813 pos = end;
5814 if (end) {
5815 *end = '/';
5816 pos++;
5820 } else if (strcmp(view->vid, view->id)) {
5821 opt_path[0] = 0;
5824 return begin_update(view, opt_cdup, tree_argv, flags);
5827 static struct view_ops tree_ops = {
5828 "file",
5829 { "tree" },
5830 VIEW_SEND_CHILD_ENTER,
5831 sizeof(struct tree_state),
5832 tree_open,
5833 tree_read,
5834 tree_draw,
5835 tree_request,
5836 tree_grep,
5837 tree_select,
5840 static bool
5841 blob_open(struct view *view, enum open_flags flags)
5843 static const char *blob_argv[] = {
5844 "git", "cat-file", "blob", "%(blob)", NULL
5847 if (!ref_blob[0] && opt_file[0]) {
5848 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5849 char blob_spec[SIZEOF_STR];
5850 const char *rev_parse_argv[] = {
5851 "git", "rev-parse", blob_spec, NULL
5854 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5855 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5856 report("Failed to resolve blob from file name");
5857 return FALSE;
5861 if (!ref_blob[0]) {
5862 report("No file chosen, press %s to open tree view",
5863 get_view_key(view, REQ_VIEW_TREE));
5864 return FALSE;
5867 view->encoding = get_path_encoding(opt_file, default_encoding);
5869 return begin_update(view, NULL, blob_argv, flags);
5872 static bool
5873 blob_read(struct view *view, char *line)
5875 if (!line)
5876 return TRUE;
5877 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5880 static enum request
5881 blob_request(struct view *view, enum request request, struct line *line)
5883 switch (request) {
5884 case REQ_VIEW_BLAME:
5885 if (view->parent)
5886 string_copy(opt_ref, view->parent->vid);
5887 return request;
5889 case REQ_EDIT:
5890 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5891 return REQ_NONE;
5892 default:
5893 return pager_request(view, request, line);
5897 static struct view_ops blob_ops = {
5898 "line",
5899 { "blob" },
5900 VIEW_NO_FLAGS,
5902 blob_open,
5903 blob_read,
5904 pager_draw,
5905 blob_request,
5906 pager_grep,
5907 pager_select,
5911 * Blame backend
5913 * Loading the blame view is a two phase job:
5915 * 1. File content is read either using opt_file from the
5916 * filesystem or using git-cat-file.
5917 * 2. Then blame information is incrementally added by
5918 * reading output from git-blame.
5921 struct blame_history_state {
5922 char id[SIZEOF_REV]; /* SHA1 ID. */
5923 const char *filename; /* Name of file. */
5926 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5928 struct blame {
5929 struct blame_commit *commit;
5930 unsigned long lineno;
5931 char text[1];
5934 struct blame_state {
5935 struct blame_commit *commit;
5936 int blamed;
5937 bool done_reading;
5938 bool auto_filename_display;
5939 /* The history state for the current view is cached in the view
5940 * state so it always matches what was used to load the current blame
5941 * view. */
5942 struct blame_history_state history_state;
5945 static bool
5946 blame_detect_filename_display(struct view *view)
5948 bool show_filenames = FALSE;
5949 const char *filename = NULL;
5950 int i;
5952 if (opt_blame_argv) {
5953 for (i = 0; opt_blame_argv[i]; i++) {
5954 if (prefixcmp(opt_blame_argv[i], "-C"))
5955 continue;
5957 show_filenames = TRUE;
5961 for (i = 0; i < view->lines; i++) {
5962 struct blame *blame = view->line[i].data;
5964 if (blame->commit && blame->commit->id[0]) {
5965 if (!filename)
5966 filename = blame->commit->filename;
5967 else if (strcmp(filename, blame->commit->filename))
5968 show_filenames = TRUE;
5972 return show_filenames;
5975 static bool
5976 blame_open(struct view *view, enum open_flags flags)
5978 struct blame_state *state = view->private;
5979 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5980 char path[SIZEOF_STR];
5981 size_t i;
5983 if (!opt_file[0]) {
5984 report("No file chosen, press %s to open tree view",
5985 get_view_key(view, REQ_VIEW_TREE));
5986 return FALSE;
5989 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5990 string_copy(path, opt_file);
5991 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5992 report("Failed to setup the blame view");
5993 return FALSE;
5997 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5998 const char *blame_cat_file_argv[] = {
5999 "git", "cat-file", "blob", "%(ref):%(file)", NULL
6002 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
6003 return FALSE;
6006 /* First pass: remove multiple references to the same commit. */
6007 for (i = 0; i < view->lines; i++) {
6008 struct blame *blame = view->line[i].data;
6010 if (blame->commit && blame->commit->id[0])
6011 blame->commit->id[0] = 0;
6012 else
6013 blame->commit = NULL;
6016 /* Second pass: free existing references. */
6017 for (i = 0; i < view->lines; i++) {
6018 struct blame *blame = view->line[i].data;
6020 if (blame->commit)
6021 free(blame->commit);
6024 if (!(flags & OPEN_RELOAD))
6025 reset_view_history(&blame_view_history);
6026 string_copy_rev(state->history_state.id, opt_ref);
6027 state->history_state.filename = get_path(opt_file);
6028 if (!state->history_state.filename)
6029 return FALSE;
6030 string_format(view->vid, "%s", opt_file);
6031 string_format(view->ref, "%s ...", opt_file);
6033 return TRUE;
6036 static struct blame_commit *
6037 get_blame_commit(struct view *view, const char *id)
6039 size_t i;
6041 for (i = 0; i < view->lines; i++) {
6042 struct blame *blame = view->line[i].data;
6044 if (!blame->commit)
6045 continue;
6047 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
6048 return blame->commit;
6052 struct blame_commit *commit = calloc(1, sizeof(*commit));
6054 if (commit)
6055 string_ncopy(commit->id, id, SIZEOF_REV);
6056 return commit;
6060 static struct blame_commit *
6061 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
6063 struct blame_header header;
6064 struct blame_commit *commit;
6065 struct blame *blame;
6067 if (!parse_blame_header(&header, text, view->lines))
6068 return NULL;
6070 commit = get_blame_commit(view, text);
6071 if (!commit)
6072 return NULL;
6074 state->blamed += header.group;
6075 while (header.group--) {
6076 struct line *line = &view->line[header.lineno + header.group - 1];
6078 blame = line->data;
6079 blame->commit = commit;
6080 blame->lineno = header.orig_lineno + header.group - 1;
6081 line->dirty = 1;
6084 return commit;
6087 static bool
6088 blame_read_file(struct view *view, const char *text, struct blame_state *state)
6090 if (!text) {
6091 const char *blame_argv[] = {
6092 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
6093 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
6096 if (view->lines == 0 && !view->prev)
6097 die("No blame exist for %s", view->vid);
6099 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
6100 report("Failed to load blame data");
6101 return TRUE;
6104 if (opt_goto_line > 0) {
6105 select_view_line(view, opt_goto_line);
6106 opt_goto_line = 0;
6109 state->done_reading = TRUE;
6110 return FALSE;
6112 } else {
6113 size_t textlen = strlen(text);
6114 struct blame *blame;
6116 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
6117 return FALSE;
6119 blame->commit = NULL;
6120 strncpy(blame->text, text, textlen);
6121 blame->text[textlen] = 0;
6122 return TRUE;
6126 static bool
6127 blame_read(struct view *view, char *line)
6129 struct blame_state *state = view->private;
6131 if (!state->done_reading)
6132 return blame_read_file(view, line, state);
6134 if (!line) {
6135 state->auto_filename_display = blame_detect_filename_display(view);
6136 string_format(view->ref, "%s", view->vid);
6137 if (view_is_displayed(view)) {
6138 update_view_title(view);
6139 redraw_view_from(view, 0);
6141 return TRUE;
6144 if (!state->commit) {
6145 state->commit = read_blame_commit(view, line, state);
6146 string_format(view->ref, "%s %2zd%%", view->vid,
6147 view->lines ? state->blamed * 100 / view->lines : 0);
6149 } else if (parse_blame_info(state->commit, line)) {
6150 if (!state->commit->filename)
6151 return FALSE;
6152 state->commit = NULL;
6155 return TRUE;
6158 static bool
6159 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6161 struct blame_state *state = view->private;
6162 struct blame *blame = line->data;
6163 struct time *time = NULL;
6164 const char *id = NULL, *filename = NULL;
6165 const struct ident *author = NULL;
6166 enum line_type id_type = LINE_ID;
6167 static const enum line_type blame_colors[] = {
6168 LINE_PALETTE_0,
6169 LINE_PALETTE_1,
6170 LINE_PALETTE_2,
6171 LINE_PALETTE_3,
6172 LINE_PALETTE_4,
6173 LINE_PALETTE_5,
6174 LINE_PALETTE_6,
6177 #define BLAME_COLOR(i) \
6178 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6180 if (blame->commit && blame->commit->filename) {
6181 id = blame->commit->id;
6182 author = blame->commit->author;
6183 filename = blame->commit->filename;
6184 time = &blame->commit->time;
6185 id_type = BLAME_COLOR((long) blame->commit);
6188 if (draw_date(view, time))
6189 return TRUE;
6191 if (draw_author(view, author))
6192 return TRUE;
6194 if (draw_filename(view, filename, state->auto_filename_display))
6195 return TRUE;
6197 if (draw_id_custom(view, id_type, id, opt_id_cols))
6198 return TRUE;
6200 if (draw_lineno(view, lineno))
6201 return TRUE;
6203 draw_text(view, LINE_DEFAULT, blame->text);
6204 return TRUE;
6207 static bool
6208 check_blame_commit(struct blame *blame, bool check_null_id)
6210 if (!blame->commit)
6211 report("Commit data not loaded yet");
6212 else if (check_null_id && string_rev_is_null(blame->commit->id))
6213 report("No commit exist for the selected line");
6214 else
6215 return TRUE;
6216 return FALSE;
6219 static void
6220 setup_blame_parent_line(struct view *view, struct blame *blame)
6222 char from[SIZEOF_REF + SIZEOF_STR];
6223 char to[SIZEOF_REF + SIZEOF_STR];
6224 const char *diff_tree_argv[] = {
6225 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6226 "--no-color", "-U0", from, to, "--", NULL
6228 struct io io;
6229 int parent_lineno = -1;
6230 int blamed_lineno = -1;
6231 char *line;
6233 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6234 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6235 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6236 return;
6238 while ((line = io_get(&io, '\n', TRUE))) {
6239 if (*line == '@') {
6240 char *pos = strchr(line, '+');
6242 parent_lineno = atoi(line + 4);
6243 if (pos)
6244 blamed_lineno = atoi(pos + 1);
6246 } else if (*line == '+' && parent_lineno != -1) {
6247 if (blame->lineno == blamed_lineno - 1 &&
6248 !strcmp(blame->text, line + 1)) {
6249 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6250 break;
6252 blamed_lineno++;
6256 io_done(&io);
6259 static void
6260 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6262 struct blame_state *state = view->private;
6263 struct blame_history_state *history_state = &state->history_state;
6264 struct blame_commit *commit = blame->commit;
6265 const char *id = parent ? commit->parent_id : commit->id;
6266 const char *filename = parent ? commit->parent_filename : commit->filename;
6268 if (!*id && parent) {
6269 report("The selected commit has no parents");
6270 return;
6273 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6274 report("The selected commit is already displayed");
6275 return;
6278 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6279 report("Failed to save current view state");
6280 return;
6283 string_ncopy(opt_ref, id, sizeof(commit->id));
6284 string_ncopy(opt_file, filename, strlen(filename));
6285 if (parent)
6286 setup_blame_parent_line(view, blame);
6287 opt_goto_line = blame->lineno;
6288 reload_view(view);
6291 static void
6292 blame_go_back(struct view *view)
6294 struct blame_history_state history_state;
6296 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6297 report("Already at start of history");
6298 return;
6301 string_copy(opt_ref, history_state.id);
6302 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6303 opt_goto_line = view->pos.lineno;
6304 reload_view(view);
6307 static enum request
6308 blame_request(struct view *view, enum request request, struct line *line)
6310 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6311 struct blame *blame = line->data;
6313 switch (request) {
6314 case REQ_VIEW_BLAME:
6315 case REQ_PARENT:
6316 if (!check_blame_commit(blame, TRUE))
6317 break;
6318 blame_go_forward(view, blame, request == REQ_PARENT);
6319 break;
6321 case REQ_BACK:
6322 blame_go_back(view);
6323 break;
6325 case REQ_ENTER:
6326 if (!check_blame_commit(blame, FALSE))
6327 break;
6329 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6330 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6331 break;
6333 if (string_rev_is_null(blame->commit->id)) {
6334 struct view *diff = VIEW(REQ_VIEW_DIFF);
6335 const char *diff_parent_argv[] = {
6336 GIT_DIFF_BLAME(encoding_arg,
6337 opt_diff_context_arg,
6338 opt_ignore_space_arg, view->vid)
6340 const char *diff_no_parent_argv[] = {
6341 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6342 opt_diff_context_arg,
6343 opt_ignore_space_arg, view->vid)
6345 const char **diff_index_argv = *blame->commit->parent_id
6346 ? diff_parent_argv : diff_no_parent_argv;
6348 open_argv(view, diff, diff_index_argv, NULL, flags);
6349 if (diff->pipe)
6350 string_copy_rev(diff->ref, NULL_ID);
6351 } else {
6352 open_view(view, REQ_VIEW_DIFF, flags);
6354 break;
6356 default:
6357 return request;
6360 return REQ_NONE;
6363 static bool
6364 blame_grep(struct view *view, struct line *line)
6366 struct blame *blame = line->data;
6367 struct blame_commit *commit = blame->commit;
6368 const char *text[] = {
6369 blame->text,
6370 commit ? commit->title : "",
6371 commit ? commit->id : "",
6372 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6373 commit ? mkdate(&commit->time, opt_date) : "",
6374 NULL
6377 return grep_text(view, text);
6380 static void
6381 blame_select(struct view *view, struct line *line)
6383 struct blame *blame = line->data;
6384 struct blame_commit *commit = blame->commit;
6386 if (!commit)
6387 return;
6389 if (string_rev_is_null(commit->id))
6390 string_ncopy(ref_commit, "HEAD", 4);
6391 else
6392 string_copy_rev(ref_commit, commit->id);
6395 static struct view_ops blame_ops = {
6396 "line",
6397 { "blame" },
6398 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6399 sizeof(struct blame_state),
6400 blame_open,
6401 blame_read,
6402 blame_draw,
6403 blame_request,
6404 blame_grep,
6405 blame_select,
6409 * Branch backend
6412 struct branch {
6413 const struct ident *author; /* Author of the last commit. */
6414 struct time time; /* Date of the last activity. */
6415 char title[128]; /* First line of the commit message. */
6416 const struct ref *ref; /* Name and commit ID information. */
6419 static const struct ref branch_all;
6420 #define BRANCH_ALL_NAME "All branches"
6421 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6423 static const enum sort_field branch_sort_fields[] = {
6424 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6426 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6428 struct branch_state {
6429 char id[SIZEOF_REV];
6430 size_t max_ref_length;
6433 static int
6434 branch_compare(const void *l1, const void *l2)
6436 const struct branch *branch1 = ((const struct line *) l1)->data;
6437 const struct branch *branch2 = ((const struct line *) l2)->data;
6439 if (branch_is_all(branch1))
6440 return -1;
6441 else if (branch_is_all(branch2))
6442 return 1;
6444 switch (get_sort_field(branch_sort_state)) {
6445 case ORDERBY_DATE:
6446 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6448 case ORDERBY_AUTHOR:
6449 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6451 case ORDERBY_NAME:
6452 default:
6453 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6457 static bool
6458 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6460 struct branch_state *state = view->private;
6461 struct branch *branch = line->data;
6462 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6463 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6465 if (draw_lineno(view, lineno))
6466 return TRUE;
6468 if (draw_date(view, &branch->time))
6469 return TRUE;
6471 if (draw_author(view, branch->author))
6472 return TRUE;
6474 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6475 return TRUE;
6477 if (draw_id(view, branch->ref->id))
6478 return TRUE;
6480 draw_text(view, LINE_DEFAULT, branch->title);
6481 return TRUE;
6484 static enum request
6485 branch_request(struct view *view, enum request request, struct line *line)
6487 struct branch *branch = line->data;
6489 switch (request) {
6490 case REQ_REFRESH:
6491 load_refs(TRUE);
6492 refresh_view(view);
6493 return REQ_NONE;
6495 case REQ_TOGGLE_SORT_FIELD:
6496 case REQ_TOGGLE_SORT_ORDER:
6497 sort_view(view, request, &branch_sort_state, branch_compare);
6498 return REQ_NONE;
6500 case REQ_ENTER:
6502 const struct ref *ref = branch->ref;
6503 const char *all_branches_argv[] = {
6504 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6506 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6508 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6509 return REQ_NONE;
6511 case REQ_JUMP_COMMIT:
6513 int lineno;
6515 for (lineno = 0; lineno < view->lines; lineno++) {
6516 struct branch *branch = view->line[lineno].data;
6518 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6519 select_view_line(view, lineno);
6520 report_clear();
6521 return REQ_NONE;
6525 default:
6526 return request;
6530 static bool
6531 branch_read(struct view *view, char *line)
6533 struct branch_state *state = view->private;
6534 const char *title = NULL;
6535 const struct ident *author = NULL;
6536 struct time time = {};
6537 size_t i;
6539 if (!line)
6540 return TRUE;
6542 switch (get_line_type(line)) {
6543 case LINE_COMMIT:
6544 string_copy_rev_from_commit_line(state->id, line);
6545 return TRUE;
6547 case LINE_AUTHOR:
6548 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6549 break;
6551 default:
6552 title = line + STRING_SIZE("title ");
6555 for (i = 0; i < view->lines; i++) {
6556 struct branch *branch = view->line[i].data;
6558 if (strcmp(branch->ref->id, state->id))
6559 continue;
6561 if (author) {
6562 branch->author = author;
6563 branch->time = time;
6566 if (title)
6567 string_expand(branch->title, sizeof(branch->title), title, 1);
6569 view->line[i].dirty = TRUE;
6572 return TRUE;
6575 static bool
6576 branch_open_visitor(void *data, const struct ref *ref)
6578 struct view *view = data;
6579 struct branch_state *state = view->private;
6580 struct branch *branch;
6581 bool is_all = ref == &branch_all;
6582 size_t ref_length;
6584 if (ref->tag || ref->ltag)
6585 return TRUE;
6587 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6588 return FALSE;
6590 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6591 if (ref_length > state->max_ref_length)
6592 state->max_ref_length = ref_length;
6594 branch->ref = ref;
6595 return TRUE;
6598 static bool
6599 branch_open(struct view *view, enum open_flags flags)
6601 const char *branch_log[] = {
6602 "git", "log", encoding_arg, "--no-color", "--date=raw",
6603 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6604 "--all", "--simplify-by-decoration", NULL
6607 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6608 report("Failed to load branch data");
6609 return FALSE;
6612 branch_open_visitor(view, &branch_all);
6613 foreach_ref(branch_open_visitor, view);
6615 return TRUE;
6618 static bool
6619 branch_grep(struct view *view, struct line *line)
6621 struct branch *branch = line->data;
6622 const char *text[] = {
6623 branch->ref->name,
6624 mkauthor(branch->author, opt_author_width, opt_author),
6625 NULL
6628 return grep_text(view, text);
6631 static void
6632 branch_select(struct view *view, struct line *line)
6634 struct branch *branch = line->data;
6636 if (branch_is_all(branch)) {
6637 string_copy(view->ref, BRANCH_ALL_NAME);
6638 return;
6640 string_copy_rev(view->ref, branch->ref->id);
6641 string_copy_rev(ref_commit, branch->ref->id);
6642 string_copy_rev(ref_head, branch->ref->id);
6643 string_copy_rev(ref_branch, branch->ref->name);
6646 static struct view_ops branch_ops = {
6647 "branch",
6648 { "branch" },
6649 VIEW_NO_FLAGS,
6650 sizeof(struct branch_state),
6651 branch_open,
6652 branch_read,
6653 branch_draw,
6654 branch_request,
6655 branch_grep,
6656 branch_select,
6660 * Status backend
6663 struct status {
6664 char status;
6665 struct {
6666 mode_t mode;
6667 char rev[SIZEOF_REV];
6668 char name[SIZEOF_STR];
6669 } old;
6670 struct {
6671 mode_t mode;
6672 char rev[SIZEOF_REV];
6673 char name[SIZEOF_STR];
6674 } new;
6677 static char status_onbranch[SIZEOF_STR];
6678 static struct status stage_status;
6679 static enum line_type stage_line_type;
6681 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6683 /* This should work even for the "On branch" line. */
6684 static inline bool
6685 status_has_none(struct view *view, struct line *line)
6687 return view_has_line(view, line) && !line[1].data;
6690 /* Get fields from the diff line:
6691 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6693 static inline bool
6694 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6696 const char *old_mode = buf + 1;
6697 const char *new_mode = buf + 8;
6698 const char *old_rev = buf + 15;
6699 const char *new_rev = buf + 56;
6700 const char *status = buf + 97;
6702 if (bufsize < 98 ||
6703 old_mode[-1] != ':' ||
6704 new_mode[-1] != ' ' ||
6705 old_rev[-1] != ' ' ||
6706 new_rev[-1] != ' ' ||
6707 status[-1] != ' ')
6708 return FALSE;
6710 file->status = *status;
6712 string_copy_rev(file->old.rev, old_rev);
6713 string_copy_rev(file->new.rev, new_rev);
6715 file->old.mode = strtoul(old_mode, NULL, 8);
6716 file->new.mode = strtoul(new_mode, NULL, 8);
6718 file->old.name[0] = file->new.name[0] = 0;
6720 return TRUE;
6723 static bool
6724 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6726 struct status *unmerged = NULL;
6727 char *buf;
6728 struct io io;
6730 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6731 return FALSE;
6733 add_line_nodata(view, type);
6735 while ((buf = io_get(&io, 0, TRUE))) {
6736 struct status *file = unmerged;
6738 if (!file) {
6739 if (!add_line_alloc(view, &file, type, 0, FALSE))
6740 goto error_out;
6743 /* Parse diff info part. */
6744 if (status) {
6745 file->status = status;
6746 if (status == 'A')
6747 string_copy(file->old.rev, NULL_ID);
6749 } else if (!file->status || file == unmerged) {
6750 if (!status_get_diff(file, buf, strlen(buf)))
6751 goto error_out;
6753 buf = io_get(&io, 0, TRUE);
6754 if (!buf)
6755 break;
6757 /* Collapse all modified entries that follow an
6758 * associated unmerged entry. */
6759 if (unmerged == file) {
6760 unmerged->status = 'U';
6761 unmerged = NULL;
6762 } else if (file->status == 'U') {
6763 unmerged = file;
6767 /* Grab the old name for rename/copy. */
6768 if (!*file->old.name &&
6769 (file->status == 'R' || file->status == 'C')) {
6770 string_ncopy(file->old.name, buf, strlen(buf));
6772 buf = io_get(&io, 0, TRUE);
6773 if (!buf)
6774 break;
6777 /* git-ls-files just delivers a NUL separated list of
6778 * file names similar to the second half of the
6779 * git-diff-* output. */
6780 string_ncopy(file->new.name, buf, strlen(buf));
6781 if (!*file->old.name)
6782 string_copy(file->old.name, file->new.name);
6783 file = NULL;
6786 if (io_error(&io)) {
6787 error_out:
6788 io_done(&io);
6789 return FALSE;
6792 if (!view->line[view->lines - 1].data)
6793 add_line_nodata(view, LINE_STAT_NONE);
6795 io_done(&io);
6796 return TRUE;
6799 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6800 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6802 static const char *status_list_other_argv[] = {
6803 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6806 static const char *status_list_no_head_argv[] = {
6807 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6810 static const char *update_index_argv[] = {
6811 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6814 /* Restore the previous line number to stay in the context or select a
6815 * line with something that can be updated. */
6816 static void
6817 status_restore(struct view *view)
6819 if (!check_position(&view->prev_pos))
6820 return;
6822 if (view->prev_pos.lineno >= view->lines)
6823 view->prev_pos.lineno = view->lines - 1;
6824 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6825 view->prev_pos.lineno++;
6826 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6827 view->prev_pos.lineno--;
6829 /* If the above fails, always skip the "On branch" line. */
6830 if (view->prev_pos.lineno < view->lines)
6831 view->pos.lineno = view->prev_pos.lineno;
6832 else
6833 view->pos.lineno = 1;
6835 if (view->prev_pos.offset > view->pos.lineno)
6836 view->pos.offset = view->pos.lineno;
6837 else if (view->prev_pos.offset < view->lines)
6838 view->pos.offset = view->prev_pos.offset;
6840 clear_position(&view->prev_pos);
6843 static void
6844 status_update_onbranch(void)
6846 static const char *paths[][2] = {
6847 { "rebase-apply/rebasing", "Rebasing" },
6848 { "rebase-apply/applying", "Applying mailbox" },
6849 { "rebase-apply/", "Rebasing mailbox" },
6850 { "rebase-merge/interactive", "Interactive rebase" },
6851 { "rebase-merge/", "Rebase merge" },
6852 { "MERGE_HEAD", "Merging" },
6853 { "BISECT_LOG", "Bisecting" },
6854 { "HEAD", "On branch" },
6856 char buf[SIZEOF_STR];
6857 struct stat stat;
6858 int i;
6860 if (is_initial_commit()) {
6861 string_copy(status_onbranch, "Initial commit");
6862 return;
6865 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6866 char *head = opt_head;
6868 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6869 lstat(buf, &stat) < 0)
6870 continue;
6872 if (!*opt_head) {
6873 struct io io;
6875 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6876 io_read_buf(&io, buf, sizeof(buf))) {
6877 head = buf;
6878 if (!prefixcmp(head, "refs/heads/"))
6879 head += STRING_SIZE("refs/heads/");
6883 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6884 string_copy(status_onbranch, opt_head);
6885 return;
6888 string_copy(status_onbranch, "Not currently on any branch");
6891 /* First parse staged info using git-diff-index(1), then parse unstaged
6892 * info using git-diff-files(1), and finally untracked files using
6893 * git-ls-files(1). */
6894 static bool
6895 status_open(struct view *view, enum open_flags flags)
6897 const char **staged_argv = is_initial_commit() ?
6898 status_list_no_head_argv : status_diff_index_argv;
6899 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6901 if (opt_is_inside_work_tree == FALSE) {
6902 report("The status view requires a working tree");
6903 return FALSE;
6906 reset_view(view);
6908 add_line_nodata(view, LINE_STAT_HEAD);
6909 status_update_onbranch();
6911 io_run_bg(update_index_argv);
6913 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6914 opt_untracked_dirs_content ? NULL : "--directory";
6916 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6917 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6918 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6919 report("Failed to load status data");
6920 return FALSE;
6923 /* Restore the exact position or use the specialized restore
6924 * mode? */
6925 status_restore(view);
6926 return TRUE;
6929 static bool
6930 status_draw(struct view *view, struct line *line, unsigned int lineno)
6932 struct status *status = line->data;
6933 enum line_type type;
6934 const char *text;
6936 if (!status) {
6937 switch (line->type) {
6938 case LINE_STAT_STAGED:
6939 type = LINE_STAT_SECTION;
6940 text = "Changes to be committed:";
6941 break;
6943 case LINE_STAT_UNSTAGED:
6944 type = LINE_STAT_SECTION;
6945 text = "Changed but not updated:";
6946 break;
6948 case LINE_STAT_UNTRACKED:
6949 type = LINE_STAT_SECTION;
6950 text = "Untracked files:";
6951 break;
6953 case LINE_STAT_NONE:
6954 type = LINE_DEFAULT;
6955 text = " (no files)";
6956 break;
6958 case LINE_STAT_HEAD:
6959 type = LINE_STAT_HEAD;
6960 text = status_onbranch;
6961 break;
6963 default:
6964 return FALSE;
6966 } else {
6967 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6969 buf[0] = status->status;
6970 if (draw_text(view, line->type, buf))
6971 return TRUE;
6972 type = LINE_DEFAULT;
6973 text = status->new.name;
6976 draw_text(view, type, text);
6977 return TRUE;
6980 static enum request
6981 status_enter(struct view *view, struct line *line)
6983 struct status *status = line->data;
6984 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6986 if (line->type == LINE_STAT_NONE ||
6987 (!status && line[1].type == LINE_STAT_NONE)) {
6988 report("No file to diff");
6989 return REQ_NONE;
6992 switch (line->type) {
6993 case LINE_STAT_STAGED:
6994 case LINE_STAT_UNSTAGED:
6995 break;
6997 case LINE_STAT_UNTRACKED:
6998 if (!status) {
6999 report("No file to show");
7000 return REQ_NONE;
7003 if (!suffixcmp(status->new.name, -1, "/")) {
7004 report("Cannot display a directory");
7005 return REQ_NONE;
7007 break;
7009 case LINE_STAT_HEAD:
7010 return REQ_NONE;
7012 default:
7013 die("line type %d not handled in switch", line->type);
7016 if (status) {
7017 stage_status = *status;
7018 } else {
7019 memset(&stage_status, 0, sizeof(stage_status));
7022 stage_line_type = line->type;
7024 open_view(view, REQ_VIEW_STAGE, flags);
7025 return REQ_NONE;
7028 static bool
7029 status_exists(struct view *view, struct status *status, enum line_type type)
7031 unsigned long lineno;
7033 for (lineno = 0; lineno < view->lines; lineno++) {
7034 struct line *line = &view->line[lineno];
7035 struct status *pos = line->data;
7037 if (line->type != type)
7038 continue;
7039 if (!pos && (!status || !status->status) && line[1].data) {
7040 select_view_line(view, lineno);
7041 return TRUE;
7043 if (pos && !strcmp(status->new.name, pos->new.name)) {
7044 select_view_line(view, lineno);
7045 return TRUE;
7049 return FALSE;
7053 static bool
7054 status_update_prepare(struct io *io, enum line_type type)
7056 const char *staged_argv[] = {
7057 "git", "update-index", "-z", "--index-info", NULL
7059 const char *others_argv[] = {
7060 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
7063 switch (type) {
7064 case LINE_STAT_STAGED:
7065 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
7067 case LINE_STAT_UNSTAGED:
7068 case LINE_STAT_UNTRACKED:
7069 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
7071 default:
7072 die("line type %d not handled in switch", type);
7073 return FALSE;
7077 static bool
7078 status_update_write(struct io *io, struct status *status, enum line_type type)
7080 switch (type) {
7081 case LINE_STAT_STAGED:
7082 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
7083 status->old.rev, status->old.name, 0);
7085 case LINE_STAT_UNSTAGED:
7086 case LINE_STAT_UNTRACKED:
7087 return io_printf(io, "%s%c", status->new.name, 0);
7089 default:
7090 die("line type %d not handled in switch", type);
7091 return FALSE;
7095 static bool
7096 status_update_file(struct status *status, enum line_type type)
7098 struct io io;
7099 bool result;
7101 if (!status_update_prepare(&io, type))
7102 return FALSE;
7104 result = status_update_write(&io, status, type);
7105 return io_done(&io) && result;
7108 static bool
7109 status_update_files(struct view *view, struct line *line)
7111 char buf[sizeof(view->ref)];
7112 struct io io;
7113 bool result = TRUE;
7114 struct line *pos;
7115 int files = 0;
7116 int file, done;
7117 int cursor_y = -1, cursor_x = -1;
7119 if (!status_update_prepare(&io, line->type))
7120 return FALSE;
7122 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7123 files++;
7125 string_copy(buf, view->ref);
7126 getsyx(cursor_y, cursor_x);
7127 for (file = 0, done = 5; result && file < files; line++, file++) {
7128 int almost_done = file * 100 / files;
7130 if (almost_done > done) {
7131 done = almost_done;
7132 string_format(view->ref, "updating file %u of %u (%d%% done)",
7133 file, files, done);
7134 update_view_title(view);
7135 setsyx(cursor_y, cursor_x);
7136 doupdate();
7138 result = status_update_write(&io, line->data, line->type);
7140 string_copy(view->ref, buf);
7142 return io_done(&io) && result;
7145 static bool
7146 status_update(struct view *view)
7148 struct line *line = &view->line[view->pos.lineno];
7150 assert(view->lines);
7152 if (!line->data) {
7153 if (status_has_none(view, line)) {
7154 report("Nothing to update");
7155 return FALSE;
7158 if (!status_update_files(view, line + 1)) {
7159 report("Failed to update file status");
7160 return FALSE;
7163 } else if (!status_update_file(line->data, line->type)) {
7164 report("Failed to update file status");
7165 return FALSE;
7168 return TRUE;
7171 static bool
7172 status_revert(struct status *status, enum line_type type, bool has_none)
7174 if (!status || type != LINE_STAT_UNSTAGED) {
7175 if (type == LINE_STAT_STAGED) {
7176 report("Cannot revert changes to staged files");
7177 } else if (type == LINE_STAT_UNTRACKED) {
7178 report("Cannot revert changes to untracked files");
7179 } else if (has_none) {
7180 report("Nothing to revert");
7181 } else {
7182 report("Cannot revert changes to multiple files");
7185 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7186 char mode[10] = "100644";
7187 const char *reset_argv[] = {
7188 "git", "update-index", "--cacheinfo", mode,
7189 status->old.rev, status->old.name, NULL
7191 const char *checkout_argv[] = {
7192 "git", "checkout", "--", status->old.name, NULL
7195 if (status->status == 'U') {
7196 string_format(mode, "%5o", status->old.mode);
7198 if (status->old.mode == 0 && status->new.mode == 0) {
7199 reset_argv[2] = "--force-remove";
7200 reset_argv[3] = status->old.name;
7201 reset_argv[4] = NULL;
7204 if (!io_run_fg(reset_argv, opt_cdup))
7205 return FALSE;
7206 if (status->old.mode == 0 && status->new.mode == 0)
7207 return TRUE;
7210 return io_run_fg(checkout_argv, opt_cdup);
7213 return FALSE;
7216 static enum request
7217 status_request(struct view *view, enum request request, struct line *line)
7219 struct status *status = line->data;
7221 switch (request) {
7222 case REQ_STATUS_UPDATE:
7223 if (!status_update(view))
7224 return REQ_NONE;
7225 break;
7227 case REQ_STATUS_REVERT:
7228 if (!status_revert(status, line->type, status_has_none(view, line)))
7229 return REQ_NONE;
7230 break;
7232 case REQ_STATUS_MERGE:
7233 if (!status || status->status != 'U') {
7234 report("Merging only possible for files with unmerged status ('U').");
7235 return REQ_NONE;
7237 open_mergetool(status->new.name);
7238 break;
7240 case REQ_EDIT:
7241 if (!status)
7242 return request;
7243 if (status->status == 'D') {
7244 report("File has been deleted.");
7245 return REQ_NONE;
7248 open_editor(status->new.name, 0);
7249 break;
7251 case REQ_VIEW_BLAME:
7252 if (status)
7253 opt_ref[0] = 0;
7254 return request;
7256 case REQ_ENTER:
7257 /* After returning the status view has been split to
7258 * show the stage view. No further reloading is
7259 * necessary. */
7260 return status_enter(view, line);
7262 case REQ_REFRESH:
7263 /* Load the current branch information and then the view. */
7264 load_refs(TRUE);
7265 break;
7267 default:
7268 return request;
7271 refresh_view(view);
7273 return REQ_NONE;
7276 static bool
7277 status_stage_info_(char *buf, size_t bufsize,
7278 enum line_type type, struct status *status)
7280 const char *file = status ? status->new.name : "";
7281 const char *info;
7283 switch (type) {
7284 case LINE_STAT_STAGED:
7285 if (status && status->status)
7286 info = "Staged changes to %s";
7287 else
7288 info = "Staged changes";
7289 break;
7291 case LINE_STAT_UNSTAGED:
7292 if (status && status->status)
7293 info = "Unstaged changes to %s";
7294 else
7295 info = "Unstaged changes";
7296 break;
7298 case LINE_STAT_UNTRACKED:
7299 info = "Untracked file %s";
7300 break;
7302 case LINE_STAT_HEAD:
7303 default:
7304 info = "";
7307 return string_nformat(buf, bufsize, NULL, info, file);
7309 #define status_stage_info(buf, type, status) \
7310 status_stage_info_(buf, sizeof(buf), type, status)
7312 static void
7313 status_select(struct view *view, struct line *line)
7315 struct status *status = line->data;
7316 char file[SIZEOF_STR] = "all files";
7317 const char *text;
7318 const char *key;
7320 if (status && !string_format(file, "'%s'", status->new.name))
7321 return;
7323 if (!status && line[1].type == LINE_STAT_NONE)
7324 line++;
7326 switch (line->type) {
7327 case LINE_STAT_STAGED:
7328 text = "Press %s to unstage %s for commit";
7329 break;
7331 case LINE_STAT_UNSTAGED:
7332 text = "Press %s to stage %s for commit";
7333 break;
7335 case LINE_STAT_UNTRACKED:
7336 text = "Press %s to stage %s for addition";
7337 break;
7339 case LINE_STAT_HEAD:
7340 case LINE_STAT_NONE:
7341 text = "Nothing to update";
7342 break;
7344 default:
7345 die("line type %d not handled in switch", line->type);
7348 if (status && status->status == 'U') {
7349 text = "Press %s to resolve conflict in %s";
7350 key = get_view_key(view, REQ_STATUS_MERGE);
7352 } else {
7353 key = get_view_key(view, REQ_STATUS_UPDATE);
7356 string_format(view->ref, text, key, file);
7357 status_stage_info(ref_status, line->type, status);
7358 if (status)
7359 string_copy(opt_file, status->new.name);
7362 static bool
7363 status_grep(struct view *view, struct line *line)
7365 struct status *status = line->data;
7367 if (status) {
7368 const char buf[2] = { status->status, 0 };
7369 const char *text[] = { status->new.name, buf, NULL };
7371 return grep_text(view, text);
7374 return FALSE;
7377 static struct view_ops status_ops = {
7378 "file",
7379 { "status" },
7380 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7382 status_open,
7383 NULL,
7384 status_draw,
7385 status_request,
7386 status_grep,
7387 status_select,
7391 struct stage_state {
7392 struct diff_state diff;
7393 size_t chunks;
7394 int *chunk;
7397 static bool
7398 stage_diff_write(struct io *io, struct line *line, struct line *end)
7400 while (line < end) {
7401 if (!io_write(io, line->data, strlen(line->data)) ||
7402 !io_write(io, "\n", 1))
7403 return FALSE;
7404 line++;
7405 if (line->type == LINE_DIFF_CHUNK ||
7406 line->type == LINE_DIFF_HEADER)
7407 break;
7410 return TRUE;
7413 static bool
7414 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7416 const char *apply_argv[SIZEOF_ARG] = {
7417 "git", "apply", "--whitespace=nowarn", NULL
7419 struct line *diff_hdr;
7420 struct io io;
7421 int argc = 3;
7423 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7424 if (!diff_hdr)
7425 return FALSE;
7427 if (!revert)
7428 apply_argv[argc++] = "--cached";
7429 if (line != NULL)
7430 apply_argv[argc++] = "--unidiff-zero";
7431 if (revert || stage_line_type == LINE_STAT_STAGED)
7432 apply_argv[argc++] = "-R";
7433 apply_argv[argc++] = "-";
7434 apply_argv[argc++] = NULL;
7435 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7436 return FALSE;
7438 if (line != NULL) {
7439 unsigned long lineno = 0;
7440 struct line *context = chunk + 1;
7441 const char *markers[] = {
7442 line->type == LINE_DIFF_DEL ? "" : ",0",
7443 line->type == LINE_DIFF_DEL ? ",0" : "",
7446 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7448 while (context < line) {
7449 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7450 break;
7451 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7452 lineno++;
7454 context++;
7457 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7458 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
7459 lineno, markers[0], lineno, markers[1]) ||
7460 !stage_diff_write(&io, line, line + 1)) {
7461 chunk = NULL;
7463 } else {
7464 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7465 !stage_diff_write(&io, chunk, view->line + view->lines))
7466 chunk = NULL;
7469 io_done(&io);
7471 return chunk ? TRUE : FALSE;
7474 static bool
7475 stage_update(struct view *view, struct line *line, bool single)
7477 struct line *chunk = NULL;
7479 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7480 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7482 if (chunk) {
7483 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7484 report("Failed to apply chunk");
7485 return FALSE;
7488 } else if (!stage_status.status) {
7489 view = view->parent;
7491 for (line = view->line; view_has_line(view, line); line++)
7492 if (line->type == stage_line_type)
7493 break;
7495 if (!status_update_files(view, line + 1)) {
7496 report("Failed to update files");
7497 return FALSE;
7500 } else if (!status_update_file(&stage_status, stage_line_type)) {
7501 report("Failed to update file");
7502 return FALSE;
7505 return TRUE;
7508 static bool
7509 stage_revert(struct view *view, struct line *line)
7511 struct line *chunk = NULL;
7513 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7514 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7516 if (chunk) {
7517 if (!prompt_yesno("Are you sure you want to revert changes?"))
7518 return FALSE;
7520 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7521 report("Failed to revert chunk");
7522 return FALSE;
7524 return TRUE;
7526 } else {
7527 return status_revert(stage_status.status ? &stage_status : NULL,
7528 stage_line_type, FALSE);
7533 static void
7534 stage_next(struct view *view, struct line *line)
7536 struct stage_state *state = view->private;
7537 int i;
7539 if (!state->chunks) {
7540 for (line = view->line; view_has_line(view, line); line++) {
7541 if (line->type != LINE_DIFF_CHUNK)
7542 continue;
7544 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7545 report("Allocation failure");
7546 return;
7549 state->chunk[state->chunks++] = line - view->line;
7553 for (i = 0; i < state->chunks; i++) {
7554 if (state->chunk[i] > view->pos.lineno) {
7555 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7556 report("Chunk %d of %zd", i + 1, state->chunks);
7557 return;
7561 report("No next chunk found");
7564 static struct line *
7565 stage_insert_chunk(struct view *view, struct chunk_header *header,
7566 struct line *from, struct line *to, struct line *last_unchanged_line)
7568 char buf[SIZEOF_STR];
7569 char *chunk_line;
7570 unsigned long from_lineno = last_unchanged_line - view->line;
7571 unsigned long to_lineno = to - view->line;
7572 unsigned long after_lineno = to_lineno;
7574 if (!string_format(buf, "@@ -%lu,%lu +%lu,%lu @@",
7575 header->old.position, header->old.lines,
7576 header->new.position, header->new.lines))
7577 return NULL;
7579 chunk_line = strdup(buf);
7580 if (!chunk_line)
7581 return NULL;
7583 free(from->data);
7584 from->data = chunk_line;
7586 if (!to)
7587 return from;
7589 if (!add_line_at(view, after_lineno++, buf, LINE_DIFF_CHUNK, strlen(buf) + 1, FALSE))
7590 return NULL;
7592 while (from_lineno < to_lineno) {
7593 struct line *line = &view->line[from_lineno++];
7595 if (!add_line_at(view, after_lineno++, line->data, line->type, strlen(line->data) + 1, FALSE))
7596 return FALSE;
7599 return view->line + after_lineno;
7602 static void
7603 stage_split_chunk(struct view *view, struct line *chunk_start)
7605 struct chunk_header header;
7606 struct line *last_changed_line = NULL, *last_unchanged_line = NULL, *pos;
7607 int chunks = 0;
7609 if (!chunk_start || !parse_chunk_header(&header, chunk_start->data)) {
7610 report("Failed to parse chunk header");
7611 return;
7614 header.old.lines = header.new.lines = 0;
7616 for (pos = chunk_start + 1; view_has_line(view, pos); pos++) {
7617 const char *chunk_line = pos->data;
7619 if (*chunk_line == '@' || *chunk_line == '\\')
7620 break;
7622 if (*chunk_line == ' ') {
7623 header.old.lines++;
7624 header.new.lines++;
7625 if (last_unchanged_line < last_changed_line)
7626 last_unchanged_line = pos;
7627 continue;
7630 if (last_changed_line && last_changed_line < last_unchanged_line) {
7631 unsigned long chunk_start_lineno = pos - view->line;
7632 unsigned long diff = pos - last_unchanged_line;
7634 pos = stage_insert_chunk(view, &header, chunk_start, pos, last_unchanged_line);
7636 header.old.position += header.old.lines - diff;
7637 header.new.position += header.new.lines - diff;
7638 header.old.lines = header.new.lines = diff;
7640 chunk_start = view->line + chunk_start_lineno;
7641 last_changed_line = last_unchanged_line = NULL;
7642 chunks++;
7645 if (*chunk_line == '-') {
7646 header.old.lines++;
7647 last_changed_line = pos;
7648 } else if (*chunk_line == '+') {
7649 header.new.lines++;
7650 last_changed_line = pos;
7654 if (chunks) {
7655 stage_insert_chunk(view, &header, chunk_start, NULL, NULL);
7656 redraw_view(view);
7657 report("Split the chunk in %d", chunks + 1);
7658 } else {
7659 report("The chunk cannot be split");
7663 static enum request
7664 stage_request(struct view *view, enum request request, struct line *line)
7666 switch (request) {
7667 case REQ_STATUS_UPDATE:
7668 if (!stage_update(view, line, FALSE))
7669 return REQ_NONE;
7670 break;
7672 case REQ_STATUS_REVERT:
7673 if (!stage_revert(view, line))
7674 return REQ_NONE;
7675 break;
7677 case REQ_STAGE_UPDATE_LINE:
7678 if (stage_line_type == LINE_STAT_UNTRACKED ||
7679 stage_status.status == 'A') {
7680 report("Staging single lines is not supported for new files");
7681 return REQ_NONE;
7683 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7684 report("Please select a change to stage");
7685 return REQ_NONE;
7687 if (!stage_update(view, line, TRUE))
7688 return REQ_NONE;
7689 break;
7691 case REQ_STAGE_NEXT:
7692 if (stage_line_type == LINE_STAT_UNTRACKED) {
7693 report("File is untracked; press %s to add",
7694 get_view_key(view, REQ_STATUS_UPDATE));
7695 return REQ_NONE;
7697 stage_next(view, line);
7698 return REQ_NONE;
7700 case REQ_STAGE_SPLIT_CHUNK:
7701 if (stage_line_type == LINE_STAT_UNTRACKED ||
7702 !(line = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK))) {
7703 report("No chunks to split in sight");
7704 return REQ_NONE;
7706 stage_split_chunk(view, line);
7707 return REQ_NONE;
7709 case REQ_EDIT:
7710 if (!stage_status.new.name[0])
7711 return diff_common_edit(view, request, line);
7713 if (stage_status.status == 'D') {
7714 report("File has been deleted.");
7715 return REQ_NONE;
7718 if (stage_line_type == LINE_STAT_UNTRACKED) {
7719 open_editor(stage_status.new.name, (line - view->line) + 1);
7720 } else {
7721 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7723 break;
7725 case REQ_REFRESH:
7726 /* Reload everything(including current branch information) ... */
7727 load_refs(TRUE);
7728 break;
7730 case REQ_VIEW_BLAME:
7731 if (stage_status.new.name[0]) {
7732 string_copy(opt_file, stage_status.new.name);
7733 opt_ref[0] = 0;
7735 return request;
7737 case REQ_ENTER:
7738 return diff_common_enter(view, request, line);
7740 case REQ_DIFF_CONTEXT_UP:
7741 case REQ_DIFF_CONTEXT_DOWN:
7742 if (!update_diff_context(request))
7743 return REQ_NONE;
7744 break;
7746 default:
7747 return request;
7750 refresh_view(view->parent);
7752 /* Check whether the staged entry still exists, and close the
7753 * stage view if it doesn't. */
7754 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7755 status_restore(view->parent);
7756 return REQ_VIEW_CLOSE;
7759 refresh_view(view);
7761 return REQ_NONE;
7764 static bool
7765 stage_open(struct view *view, enum open_flags flags)
7767 static const char *no_head_diff_argv[] = {
7768 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7769 stage_status.new.name)
7771 static const char *index_show_argv[] = {
7772 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7773 stage_status.old.name, stage_status.new.name)
7775 static const char *files_show_argv[] = {
7776 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7777 stage_status.old.name, stage_status.new.name)
7779 /* Diffs for unmerged entries are empty when passing the new
7780 * path, so leave out the new path. */
7781 static const char *files_unmerged_argv[] = {
7782 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7783 opt_diff_context_arg, opt_ignore_space_arg, "--",
7784 stage_status.old.name, NULL
7786 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7787 const char **argv = NULL;
7789 if (!stage_line_type) {
7790 report("No stage content, press %s to open the status view and choose file",
7791 get_view_key(view, REQ_VIEW_STATUS));
7792 return FALSE;
7795 view->encoding = NULL;
7797 switch (stage_line_type) {
7798 case LINE_STAT_STAGED:
7799 if (is_initial_commit()) {
7800 argv = no_head_diff_argv;
7801 } else {
7802 argv = index_show_argv;
7804 break;
7806 case LINE_STAT_UNSTAGED:
7807 if (stage_status.status != 'U')
7808 argv = files_show_argv;
7809 else
7810 argv = files_unmerged_argv;
7811 break;
7813 case LINE_STAT_UNTRACKED:
7814 argv = file_argv;
7815 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7816 break;
7818 case LINE_STAT_HEAD:
7819 default:
7820 die("line type %d not handled in switch", stage_line_type);
7823 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7824 || !argv_copy(&view->argv, argv)) {
7825 report("Failed to open staged view");
7826 return FALSE;
7829 view->vid[0] = 0;
7830 view->dir = opt_cdup;
7831 return begin_update(view, NULL, NULL, flags);
7834 static bool
7835 stage_read(struct view *view, char *data)
7837 struct stage_state *state = view->private;
7839 if (stage_line_type == LINE_STAT_UNTRACKED)
7840 return pager_common_read(view, data, LINE_DEFAULT);
7842 if (data && diff_common_read(view, data, &state->diff))
7843 return TRUE;
7845 return pager_read(view, data);
7848 static struct view_ops stage_ops = {
7849 "line",
7850 { "stage" },
7851 VIEW_DIFF_LIKE,
7852 sizeof(struct stage_state),
7853 stage_open,
7854 stage_read,
7855 diff_common_draw,
7856 stage_request,
7857 pager_grep,
7858 pager_select,
7863 * Revision graph
7866 static const enum line_type graph_colors[] = {
7867 LINE_PALETTE_0,
7868 LINE_PALETTE_1,
7869 LINE_PALETTE_2,
7870 LINE_PALETTE_3,
7871 LINE_PALETTE_4,
7872 LINE_PALETTE_5,
7873 LINE_PALETTE_6,
7876 static enum line_type get_graph_color(struct graph_symbol *symbol)
7878 if (symbol->commit)
7879 return LINE_GRAPH_COMMIT;
7880 assert(symbol->color < ARRAY_SIZE(graph_colors));
7881 return graph_colors[symbol->color];
7884 static bool
7885 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7887 const char *chars = graph_symbol_to_utf8(symbol);
7889 return draw_text(view, color, chars + !!first);
7892 static bool
7893 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7895 const char *chars = graph_symbol_to_ascii(symbol);
7897 return draw_text(view, color, chars + !!first);
7900 static bool
7901 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7903 const chtype *chars = graph_symbol_to_chtype(symbol);
7905 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7908 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7910 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7912 static const draw_graph_fn fns[] = {
7913 draw_graph_ascii,
7914 draw_graph_chtype,
7915 draw_graph_utf8
7917 draw_graph_fn fn = fns[opt_line_graphics];
7918 int i;
7920 for (i = 0; i < canvas->size; i++) {
7921 struct graph_symbol *symbol = &canvas->symbols[i];
7922 enum line_type color = get_graph_color(symbol);
7924 if (fn(view, symbol, color, i == 0))
7925 return TRUE;
7928 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7932 * Main view backend
7935 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7937 struct commit {
7938 char id[SIZEOF_REV]; /* SHA1 ID. */
7939 const struct ident *author; /* Author of the commit. */
7940 struct time time; /* Date from the author ident. */
7941 struct graph_canvas graph; /* Ancestry chain graphics. */
7942 char title[1]; /* First line of the commit message. */
7945 struct main_state {
7946 struct graph graph;
7947 struct commit current;
7948 char **reflog;
7949 size_t reflogs;
7950 int reflog_width;
7951 char reflogmsg[SIZEOF_STR / 2];
7952 bool in_header;
7953 bool added_changes_commits;
7954 bool with_graph;
7957 static void
7958 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7960 struct main_state *state = view->private;
7962 string_copy_rev(commit->id, ids);
7963 if (state->with_graph)
7964 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7967 static struct commit *
7968 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7969 const char *title, bool custom)
7971 struct main_state *state = view->private;
7972 size_t titlelen = strlen(title);
7973 struct commit *commit;
7974 char buf[SIZEOF_STR / 2];
7976 /* FIXME: More graceful handling of titles; append "..." to
7977 * shortened titles, etc. */
7978 string_expand(buf, sizeof(buf), title, 1);
7979 title = buf;
7980 titlelen = strlen(title);
7982 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7983 return NULL;
7985 *commit = *template;
7986 strncpy(commit->title, title, titlelen);
7987 state->graph.canvas = &commit->graph;
7988 memset(template, 0, sizeof(*template));
7989 state->reflogmsg[0] = 0;
7990 return commit;
7993 static inline void
7994 main_flush_commit(struct view *view, struct commit *commit)
7996 if (*commit->id)
7997 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
8000 static bool
8001 main_has_changes(const char *argv[])
8003 struct io io;
8005 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
8006 return FALSE;
8007 io_done(&io);
8008 return io.status == 1;
8011 static void
8012 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
8014 char ids[SIZEOF_STR] = NULL_ID " ";
8015 struct main_state *state = view->private;
8016 struct commit commit = {};
8017 struct timeval now;
8018 struct timezone tz;
8020 if (!parent)
8021 return;
8023 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
8025 if (!gettimeofday(&now, &tz)) {
8026 commit.time.tz = tz.tz_minuteswest * 60;
8027 commit.time.sec = now.tv_sec - commit.time.tz;
8030 commit.author = &unknown_ident;
8031 main_register_commit(view, &commit, ids, FALSE);
8032 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
8033 graph_render_parents(&state->graph);
8036 static void
8037 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
8039 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
8040 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
8041 const char *staged_parent = NULL_ID;
8042 const char *unstaged_parent = parent;
8044 if (!is_head_commit(parent))
8045 return;
8047 state->added_changes_commits = TRUE;
8049 io_run_bg(update_index_argv);
8051 if (!main_has_changes(unstaged_argv)) {
8052 unstaged_parent = NULL;
8053 staged_parent = parent;
8056 if (!main_has_changes(staged_argv)) {
8057 staged_parent = NULL;
8060 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
8061 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
8064 static bool
8065 main_open(struct view *view, enum open_flags flags)
8067 static const char *main_argv[] = {
8068 GIT_MAIN_LOG(encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
8070 struct main_state *state = view->private;
8072 state->with_graph = opt_rev_graph &&
8073 opt_commit_order != COMMIT_ORDER_REVERSE;
8075 if (flags & OPEN_PAGER_MODE) {
8076 state->added_changes_commits = TRUE;
8077 state->with_graph = FALSE;
8080 return begin_update(view, NULL, main_argv, flags);
8083 static void
8084 main_done(struct view *view)
8086 struct main_state *state = view->private;
8087 int i;
8089 for (i = 0; i < view->lines; i++) {
8090 struct commit *commit = view->line[i].data;
8092 free(commit->graph.symbols);
8095 for (i = 0; i < state->reflogs; i++)
8096 free(state->reflog[i]);
8097 free(state->reflog);
8100 #define MAIN_NO_COMMIT_REFS 1
8101 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
8102 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
8104 static inline struct ref_list *
8105 main_get_commit_refs(struct line *line, struct commit *commit)
8107 struct ref_list *refs = NULL;
8109 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
8110 main_mark_no_commit_refs(line);
8112 return refs;
8115 static bool
8116 main_draw(struct view *view, struct line *line, unsigned int lineno)
8118 struct main_state *state = view->private;
8119 struct commit *commit = line->data;
8120 struct ref_list *refs = NULL;
8122 if (!commit->author)
8123 return FALSE;
8125 if (draw_lineno(view, lineno))
8126 return TRUE;
8128 if (opt_show_id) {
8129 if (state->reflogs) {
8130 const char *id = state->reflog[line->lineno - 1];
8132 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
8133 return TRUE;
8134 } else if (draw_id(view, commit->id)) {
8135 return TRUE;
8139 if (draw_date(view, &commit->time))
8140 return TRUE;
8142 if (draw_author(view, commit->author))
8143 return TRUE;
8145 if (state->with_graph && draw_graph(view, &commit->graph))
8146 return TRUE;
8148 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
8149 return TRUE;
8151 if (commit->title)
8152 draw_commit_title(view, commit->title, 0);
8153 return TRUE;
8156 static bool
8157 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
8159 char *end = strchr(reflog, ' ');
8160 int id_width;
8162 if (!end)
8163 return FALSE;
8164 *end = 0;
8166 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
8167 || !(reflog = strdup(reflog)))
8168 return FALSE;
8170 state->reflog[state->reflogs++] = reflog;
8171 id_width = strlen(reflog);
8172 if (state->reflog_width < id_width) {
8173 state->reflog_width = id_width;
8174 if (opt_show_id)
8175 view->force_redraw = TRUE;
8178 return TRUE;
8181 /* Reads git log --pretty=raw output and parses it into the commit struct. */
8182 static bool
8183 main_read(struct view *view, char *line)
8185 struct main_state *state = view->private;
8186 struct graph *graph = &state->graph;
8187 enum line_type type;
8188 struct commit *commit = &state->current;
8190 if (!line) {
8191 main_flush_commit(view, commit);
8193 if (!view->lines && !view->prev)
8194 die("No revisions match the given arguments.");
8195 if (view->lines > 0) {
8196 struct commit *last = view->line[view->lines - 1].data;
8198 view->line[view->lines - 1].dirty = 1;
8199 if (!last->author) {
8200 view->lines--;
8201 free(last);
8205 if (state->with_graph)
8206 done_graph(graph);
8207 return TRUE;
8210 type = get_line_type(line);
8211 if (type == LINE_COMMIT) {
8212 bool is_boundary;
8214 state->in_header = TRUE;
8215 line += STRING_SIZE("commit ");
8216 is_boundary = *line == '-';
8217 while (*line && !isalnum(*line))
8218 line++;
8220 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
8221 main_add_changes_commits(view, state, line);
8222 else
8223 main_flush_commit(view, commit);
8225 main_register_commit(view, &state->current, line, is_boundary);
8226 return TRUE;
8229 if (!*commit->id)
8230 return TRUE;
8232 /* Empty line separates the commit header from the log itself. */
8233 if (*line == '\0')
8234 state->in_header = FALSE;
8236 switch (type) {
8237 case LINE_PP_REFLOG:
8238 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8239 return FALSE;
8240 break;
8242 case LINE_PP_REFLOGMSG:
8243 line += STRING_SIZE("Reflog message: ");
8244 string_ncopy(state->reflogmsg, line, strlen(line));
8245 break;
8247 case LINE_PARENT:
8248 if (state->with_graph && !graph->has_parents)
8249 graph_add_parent(graph, line + STRING_SIZE("parent "));
8250 break;
8252 case LINE_AUTHOR:
8253 parse_author_line(line + STRING_SIZE("author "),
8254 &commit->author, &commit->time);
8255 if (state->with_graph)
8256 graph_render_parents(graph);
8257 break;
8259 default:
8260 /* Fill in the commit title if it has not already been set. */
8261 if (*commit->title)
8262 break;
8264 /* Skip lines in the commit header. */
8265 if (state->in_header)
8266 break;
8268 /* Require titles to start with a non-space character at the
8269 * offset used by git log. */
8270 if (strncmp(line, " ", 4))
8271 break;
8272 line += 4;
8273 /* Well, if the title starts with a whitespace character,
8274 * try to be forgiving. Otherwise we end up with no title. */
8275 while (isspace(*line))
8276 line++;
8277 if (*line == '\0')
8278 break;
8279 if (*state->reflogmsg)
8280 line = state->reflogmsg;
8281 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8284 return TRUE;
8287 static enum request
8288 main_request(struct view *view, enum request request, struct line *line)
8290 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8291 ? OPEN_SPLIT : OPEN_DEFAULT;
8293 switch (request) {
8294 case REQ_NEXT:
8295 case REQ_PREVIOUS:
8296 if (view_is_displayed(view) && display[0] != view)
8297 return request;
8298 /* Do not pass navigation requests to the branch view
8299 * when the main view is maximized. (GH #38) */
8300 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8302 case REQ_VIEW_DIFF:
8303 case REQ_ENTER:
8304 if (view_is_displayed(view) && display[0] != view)
8305 maximize_view(view, TRUE);
8307 if (line->type == LINE_STAT_UNSTAGED
8308 || line->type == LINE_STAT_STAGED) {
8309 struct view *diff = VIEW(REQ_VIEW_DIFF);
8310 const char *diff_staged_argv[] = {
8311 GIT_DIFF_STAGED(encoding_arg,
8312 opt_diff_context_arg,
8313 opt_ignore_space_arg, NULL, NULL)
8315 const char *diff_unstaged_argv[] = {
8316 GIT_DIFF_UNSTAGED(encoding_arg,
8317 opt_diff_context_arg,
8318 opt_ignore_space_arg, NULL, NULL)
8320 const char **diff_argv = line->type == LINE_STAT_STAGED
8321 ? diff_staged_argv : diff_unstaged_argv;
8323 open_argv(view, diff, diff_argv, NULL, flags);
8324 break;
8327 open_view(view, REQ_VIEW_DIFF, flags);
8328 break;
8330 case REQ_REFRESH:
8331 load_refs(TRUE);
8332 refresh_view(view);
8333 break;
8335 case REQ_JUMP_COMMIT:
8337 int lineno;
8339 for (lineno = 0; lineno < view->lines; lineno++) {
8340 struct commit *commit = view->line[lineno].data;
8342 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8343 select_view_line(view, lineno);
8344 report_clear();
8345 return REQ_NONE;
8349 report("Unable to find commit '%s'", opt_search);
8350 break;
8352 default:
8353 return request;
8356 return REQ_NONE;
8359 static bool
8360 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8362 struct ref_list *list;
8363 regmatch_t pmatch;
8364 size_t i;
8366 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8367 return FALSE;
8369 for (i = 0; i < list->size; i++) {
8370 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8371 return TRUE;
8374 return FALSE;
8377 static bool
8378 main_grep(struct view *view, struct line *line)
8380 struct commit *commit = line->data;
8381 const char *text[] = {
8382 commit->id,
8383 commit->title,
8384 mkauthor(commit->author, opt_author_width, opt_author),
8385 mkdate(&commit->time, opt_date),
8386 NULL
8389 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8392 static void
8393 main_select(struct view *view, struct line *line)
8395 struct commit *commit = line->data;
8397 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8398 string_ncopy(view->ref, commit->title, strlen(commit->title));
8399 else
8400 string_copy_rev(view->ref, commit->id);
8401 string_copy_rev(ref_commit, commit->id);
8404 static struct view_ops main_ops = {
8405 "commit",
8406 { "main" },
8407 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8408 sizeof(struct main_state),
8409 main_open,
8410 main_read,
8411 main_draw,
8412 main_request,
8413 main_grep,
8414 main_select,
8415 main_done,
8418 static bool
8419 stash_open(struct view *view, enum open_flags flags)
8421 static const char *stash_argv[] = { "git", "stash", "list",
8422 encoding_arg, "--no-color", "--pretty=raw", NULL };
8423 struct main_state *state = view->private;
8425 state->added_changes_commits = TRUE;
8426 state->with_graph = FALSE;
8427 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8430 static void
8431 stash_select(struct view *view, struct line *line)
8433 main_select(view, line);
8434 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8435 string_copy(view->ref, ref_stash);
8438 static struct view_ops stash_ops = {
8439 "stash",
8440 { "stash" },
8441 VIEW_SEND_CHILD_ENTER,
8442 sizeof(struct main_state),
8443 stash_open,
8444 main_read,
8445 main_draw,
8446 main_request,
8447 main_grep,
8448 stash_select,
8452 * Status management
8455 /* Whether or not the curses interface has been initialized. */
8456 static bool cursed = FALSE;
8458 /* Terminal hacks and workarounds. */
8459 static bool use_scroll_redrawwin;
8460 static bool use_scroll_status_wclear;
8462 /* The status window is used for polling keystrokes. */
8463 static WINDOW *status_win;
8465 /* Reading from the prompt? */
8466 static bool input_mode = FALSE;
8468 static bool status_empty = FALSE;
8470 /* Update status and title window. */
8471 static void
8472 report(const char *msg, ...)
8474 struct view *view = display[current_view];
8476 if (input_mode)
8477 return;
8479 if (!view) {
8480 char buf[SIZEOF_STR];
8481 int retval;
8483 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8484 die("%s", buf);
8487 if (!status_empty || *msg) {
8488 va_list args;
8490 va_start(args, msg);
8492 wmove(status_win, 0, 0);
8493 if (view->has_scrolled && use_scroll_status_wclear)
8494 wclear(status_win);
8495 if (*msg) {
8496 vwprintw(status_win, msg, args);
8497 status_empty = FALSE;
8498 } else {
8499 status_empty = TRUE;
8501 wclrtoeol(status_win);
8502 wnoutrefresh(status_win);
8504 va_end(args);
8507 update_view_title(view);
8510 static void
8511 done_display(void)
8513 endwin();
8516 static void
8517 init_display(void)
8519 const char *term;
8520 int x, y;
8522 die_callback = done_display;
8524 /* Initialize the curses library */
8525 if (isatty(STDIN_FILENO)) {
8526 cursed = !!initscr();
8527 opt_tty = stdin;
8528 } else {
8529 /* Leave stdin and stdout alone when acting as a pager. */
8530 opt_tty = fopen("/dev/tty", "r+");
8531 if (!opt_tty)
8532 die("Failed to open /dev/tty");
8533 cursed = !!newterm(NULL, opt_tty, opt_tty);
8536 if (!cursed)
8537 die("Failed to initialize curses");
8539 nonl(); /* Disable conversion and detect newlines from input. */
8540 cbreak(); /* Take input chars one at a time, no wait for \n */
8541 noecho(); /* Don't echo input */
8542 leaveok(stdscr, FALSE);
8544 if (has_colors())
8545 init_colors();
8547 getmaxyx(stdscr, y, x);
8548 status_win = newwin(1, x, y - 1, 0);
8549 if (!status_win)
8550 die("Failed to create status window");
8552 /* Enable keyboard mapping */
8553 keypad(status_win, TRUE);
8554 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8555 #ifdef NCURSES_MOUSE_VERSION
8556 /* Enable mouse */
8557 if (opt_mouse){
8558 mousemask(ALL_MOUSE_EVENTS, NULL);
8559 mouseinterval(0);
8561 #endif
8563 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8564 set_tabsize(opt_tab_size);
8565 #else
8566 TABSIZE = opt_tab_size;
8567 #endif
8569 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8570 if (term && !strcmp(term, "gnome-terminal")) {
8571 /* In the gnome-terminal-emulator, the message from
8572 * scrolling up one line when impossible followed by
8573 * scrolling down one line causes corruption of the
8574 * status line. This is fixed by calling wclear. */
8575 use_scroll_status_wclear = TRUE;
8576 use_scroll_redrawwin = FALSE;
8578 } else if (term && !strcmp(term, "xrvt-xpm")) {
8579 /* No problems with full optimizations in xrvt-(unicode)
8580 * and aterm. */
8581 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8583 } else {
8584 /* When scrolling in (u)xterm the last line in the
8585 * scrolling direction will update slowly. */
8586 use_scroll_redrawwin = TRUE;
8587 use_scroll_status_wclear = FALSE;
8591 static int
8592 get_input(int prompt_position)
8594 struct view *view;
8595 int i, key, cursor_y, cursor_x;
8597 if (prompt_position)
8598 input_mode = TRUE;
8600 while (TRUE) {
8601 bool loading = FALSE;
8603 foreach_view (view, i) {
8604 update_view(view);
8605 if (view_is_displayed(view) && view->has_scrolled &&
8606 use_scroll_redrawwin)
8607 redrawwin(view->win);
8608 view->has_scrolled = FALSE;
8609 if (view->pipe)
8610 loading = TRUE;
8613 /* Update the cursor position. */
8614 if (prompt_position) {
8615 getbegyx(status_win, cursor_y, cursor_x);
8616 cursor_x = prompt_position;
8617 } else {
8618 view = display[current_view];
8619 getbegyx(view->win, cursor_y, cursor_x);
8620 cursor_x = view->width - 1;
8621 cursor_y += view->pos.lineno - view->pos.offset;
8623 setsyx(cursor_y, cursor_x);
8625 /* Refresh, accept single keystroke of input */
8626 doupdate();
8627 nodelay(status_win, loading);
8628 key = wgetch(status_win);
8630 /* wgetch() with nodelay() enabled returns ERR when
8631 * there's no input. */
8632 if (key == ERR) {
8634 } else if (key == KEY_RESIZE) {
8635 int height, width;
8637 getmaxyx(stdscr, height, width);
8639 wresize(status_win, 1, width);
8640 mvwin(status_win, height - 1, 0);
8641 wnoutrefresh(status_win);
8642 resize_display();
8643 redraw_display(TRUE);
8645 } else {
8646 input_mode = FALSE;
8647 if (key == erasechar())
8648 key = KEY_BACKSPACE;
8649 return key;
8654 static char *
8655 prompt_input(const char *prompt, input_handler handler, void *data)
8657 enum input_status status = INPUT_OK;
8658 static char buf[SIZEOF_STR];
8659 size_t pos = 0;
8661 buf[pos] = 0;
8663 while (status == INPUT_OK || status == INPUT_SKIP) {
8664 int key;
8666 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8667 wclrtoeol(status_win);
8669 key = get_input(pos + 1);
8670 switch (key) {
8671 case KEY_RETURN:
8672 case KEY_ENTER:
8673 case '\n':
8674 status = pos ? INPUT_STOP : INPUT_CANCEL;
8675 break;
8677 case KEY_BACKSPACE:
8678 if (pos > 0)
8679 buf[--pos] = 0;
8680 else
8681 status = INPUT_CANCEL;
8682 break;
8684 case KEY_ESC:
8685 status = INPUT_CANCEL;
8686 break;
8688 default:
8689 if (pos >= sizeof(buf)) {
8690 report("Input string too long");
8691 return NULL;
8694 status = handler(data, buf, key);
8695 if (status == INPUT_OK)
8696 buf[pos++] = (char) key;
8700 /* Clear the status window */
8701 status_empty = FALSE;
8702 report_clear();
8704 if (status == INPUT_CANCEL)
8705 return NULL;
8707 buf[pos++] = 0;
8709 return buf;
8712 static enum input_status
8713 prompt_yesno_handler(void *data, char *buf, int c)
8715 if (c == 'y' || c == 'Y')
8716 return INPUT_STOP;
8717 if (c == 'n' || c == 'N')
8718 return INPUT_CANCEL;
8719 return INPUT_SKIP;
8722 static bool
8723 prompt_yesno(const char *prompt)
8725 char prompt2[SIZEOF_STR];
8727 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8728 return FALSE;
8730 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8733 static enum input_status
8734 read_prompt_handler(void *data, char *buf, int c)
8736 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8739 static char *
8740 read_prompt(const char *prompt)
8742 return prompt_input(prompt, read_prompt_handler, NULL);
8745 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8747 enum input_status status = INPUT_OK;
8748 int size = 0;
8750 while (items[size].text)
8751 size++;
8753 assert(size > 0);
8755 while (status == INPUT_OK) {
8756 const struct menu_item *item = &items[*selected];
8757 int key;
8758 int i;
8760 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8761 prompt, *selected + 1, size);
8762 if (item->hotkey)
8763 wprintw(status_win, "[%c] ", (char) item->hotkey);
8764 wprintw(status_win, "%s", item->text);
8765 wclrtoeol(status_win);
8767 key = get_input(COLS - 1);
8768 switch (key) {
8769 case KEY_RETURN:
8770 case KEY_ENTER:
8771 case '\n':
8772 status = INPUT_STOP;
8773 break;
8775 case KEY_LEFT:
8776 case KEY_UP:
8777 *selected = *selected - 1;
8778 if (*selected < 0)
8779 *selected = size - 1;
8780 break;
8782 case KEY_RIGHT:
8783 case KEY_DOWN:
8784 *selected = (*selected + 1) % size;
8785 break;
8787 case KEY_ESC:
8788 status = INPUT_CANCEL;
8789 break;
8791 default:
8792 for (i = 0; items[i].text; i++)
8793 if (items[i].hotkey == key) {
8794 *selected = i;
8795 status = INPUT_STOP;
8796 break;
8801 /* Clear the status window */
8802 status_empty = FALSE;
8803 report_clear();
8805 return status != INPUT_CANCEL;
8809 * Repository properties
8813 static void
8814 set_remote_branch(const char *name, const char *value, size_t valuelen)
8816 if (!strcmp(name, ".remote")) {
8817 string_ncopy(opt_remote, value, valuelen);
8819 } else if (*opt_remote && !strcmp(name, ".merge")) {
8820 size_t from = strlen(opt_remote);
8822 if (!prefixcmp(value, "refs/heads/"))
8823 value += STRING_SIZE("refs/heads/");
8825 if (!string_format_from(opt_remote, &from, "/%s", value))
8826 opt_remote[0] = 0;
8830 static void
8831 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8833 const char *argv[SIZEOF_ARG] = { name, "=" };
8834 int argc = 1 + (cmd == option_set_command);
8835 enum status_code error;
8837 if (!argv_from_string(argv, &argc, value))
8838 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8839 else
8840 error = cmd(argc, argv);
8842 if (error != SUCCESS)
8843 warn("Option 'tig.%s': %s", name, get_status_message(error));
8846 static void
8847 set_work_tree(const char *value)
8849 char cwd[SIZEOF_STR];
8851 if (!getcwd(cwd, sizeof(cwd)))
8852 die("Failed to get cwd path: %s", strerror(errno));
8853 if (chdir(cwd) < 0)
8854 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8855 if (chdir(opt_git_dir) < 0)
8856 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8857 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8858 die("Failed to get git path: %s", strerror(errno));
8859 if (chdir(value) < 0)
8860 die("Failed to chdir(%s): %s", value, strerror(errno));
8861 if (!getcwd(cwd, sizeof(cwd)))
8862 die("Failed to get cwd path: %s", strerror(errno));
8863 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8864 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8865 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8866 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8867 opt_is_inside_work_tree = TRUE;
8870 static void
8871 parse_git_color_option(enum line_type type, char *value)
8873 struct line_info *info = &line_info[type];
8874 const char *argv[SIZEOF_ARG];
8875 int argc = 0;
8876 bool first_color = TRUE;
8877 int i;
8879 if (!argv_from_string(argv, &argc, value))
8880 return;
8882 info->fg = COLOR_DEFAULT;
8883 info->bg = COLOR_DEFAULT;
8884 info->attr = 0;
8886 for (i = 0; i < argc; i++) {
8887 int attr = 0;
8889 if (set_attribute(&attr, argv[i])) {
8890 info->attr |= attr;
8892 } else if (set_color(&attr, argv[i])) {
8893 if (first_color)
8894 info->fg = attr;
8895 else
8896 info->bg = attr;
8897 first_color = FALSE;
8902 static void
8903 set_git_color_option(const char *name, char *value)
8905 static const struct enum_map_entry color_option_map[] = {
8906 ENUM_MAP_ENTRY("branch.current", LINE_MAIN_HEAD),
8907 ENUM_MAP_ENTRY("branch.local", LINE_MAIN_REF),
8908 ENUM_MAP_ENTRY("branch.plain", LINE_MAIN_REF),
8909 ENUM_MAP_ENTRY("branch.remote", LINE_MAIN_REMOTE),
8911 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_HEADER),
8912 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_INDEX),
8913 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_OLDMODE),
8914 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_NEWMODE),
8915 ENUM_MAP_ENTRY("diff.frag", LINE_DIFF_CHUNK),
8916 ENUM_MAP_ENTRY("diff.old", LINE_DIFF_DEL),
8917 ENUM_MAP_ENTRY("diff.new", LINE_DIFF_ADD),
8919 //ENUM_MAP_ENTRY("diff.commit", LINE_DIFF_ADD),
8921 ENUM_MAP_ENTRY("status.branch", LINE_STAT_HEAD),
8922 //ENUM_MAP_ENTRY("status.nobranch", LINE_STAT_HEAD),
8923 ENUM_MAP_ENTRY("status.added", LINE_STAT_STAGED),
8924 ENUM_MAP_ENTRY("status.updated", LINE_STAT_STAGED),
8925 ENUM_MAP_ENTRY("status.changed", LINE_STAT_UNSTAGED),
8926 ENUM_MAP_ENTRY("status.untracked", LINE_STAT_UNTRACKED),
8928 int type = LINE_NONE;
8930 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8931 parse_git_color_option(type, value);
8935 static void
8936 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8938 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
8939 encoding_arg[0] = 0;
8942 static int
8943 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8945 if (!strcmp(name, "i18n.commitencoding"))
8946 set_encoding(&default_encoding, value, FALSE);
8948 else if (!strcmp(name, "gui.encoding"))
8949 set_encoding(&default_encoding, value, TRUE);
8951 else if (!strcmp(name, "core.editor"))
8952 string_ncopy(opt_editor, value, valuelen);
8954 else if (!strcmp(name, "core.worktree"))
8955 set_work_tree(value);
8957 else if (!strcmp(name, "core.abbrev"))
8958 parse_id(&opt_id_cols, value);
8960 else if (!prefixcmp(name, "tig.color."))
8961 set_repo_config_option(name + 10, value, option_color_command);
8963 else if (!prefixcmp(name, "tig.bind."))
8964 set_repo_config_option(name + 9, value, option_bind_command);
8966 else if (!prefixcmp(name, "tig."))
8967 set_repo_config_option(name + 4, value, option_set_command);
8969 else if (!prefixcmp(name, "color."))
8970 set_git_color_option(name + STRING_SIZE("color."), value);
8972 else if (*opt_head && !prefixcmp(name, "branch.") &&
8973 !strncmp(name + 7, opt_head, strlen(opt_head)))
8974 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8976 return OK;
8979 static int
8980 load_git_config(void)
8982 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8984 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8987 #define REPO_INFO_GIT_DIR "--git-dir"
8988 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8989 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8990 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8991 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8992 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8994 struct repo_info_state {
8995 const char **argv;
8996 char head_id[SIZEOF_REV];
8999 static int
9000 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9002 struct repo_info_state *state = data;
9003 const char *arg = *state->argv ? *state->argv++ : "";
9005 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
9006 string_ncopy(opt_git_dir, name, namelen);
9008 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
9009 /* This can be 3 different values depending on the
9010 * version of git being used. If git-rev-parse does not
9011 * understand --is-inside-work-tree it will simply echo
9012 * the option else either "true" or "false" is printed.
9013 * Default to true for the unknown case. */
9014 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
9016 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
9017 string_ncopy(opt_cdup, name, namelen);
9019 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
9020 string_ncopy(opt_prefix, name, namelen);
9022 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
9023 string_ncopy(state->head_id, name, namelen);
9025 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
9026 if (!prefixcmp(name, "refs/heads/")) {
9027 char *offset = name + STRING_SIZE("refs/heads/");
9029 string_ncopy(opt_head, offset, strlen(offset) + 1);
9030 add_ref(state->head_id, name, opt_remote, opt_head);
9032 state->argv++;
9035 return OK;
9038 static int
9039 load_repo_info(void)
9041 const char *rev_parse_argv[] = {
9042 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
9043 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
9044 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
9045 NULL
9047 struct repo_info_state state = { rev_parse_argv + 2 };
9049 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
9054 * Main
9057 static const char usage[] =
9058 "tig " TIG_VERSION " (" __DATE__ ")\n"
9059 "\n"
9060 "Usage: tig [options] [revs] [--] [paths]\n"
9061 " or: tig log [options] [revs] [--] [paths]\n"
9062 " or: tig show [options] [revs] [--] [paths]\n"
9063 " or: tig blame [options] [rev] [--] path\n"
9064 " or: tig stash\n"
9065 " or: tig status\n"
9066 " or: tig < [git command output]\n"
9067 "\n"
9068 "Options:\n"
9069 " +<number> Select line <number> in the first view\n"
9070 " -v, --version Show version and exit\n"
9071 " -h, --help Show help message and exit";
9073 static void TIG_NORETURN
9074 quit(int sig)
9076 if (sig)
9077 signal(sig, SIG_DFL);
9079 /* XXX: Restore tty modes and let the OS cleanup the rest! */
9080 if (cursed)
9081 endwin();
9082 exit(0);
9085 static int
9086 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9088 const char ***filter_args = data;
9090 return argv_append(filter_args, name) ? OK : ERR;
9093 static void
9094 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
9096 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
9097 const char **all_argv = NULL;
9099 if (!argv_append_array(&all_argv, rev_parse_argv) ||
9100 !argv_append_array(&all_argv, argv) ||
9101 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
9102 die("Failed to split arguments");
9103 argv_free(all_argv);
9104 free(all_argv);
9107 static bool
9108 is_rev_flag(const char *flag)
9110 static const char *rev_flags[] = { GIT_REV_FLAGS };
9111 int i;
9113 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
9114 if (!strcmp(flag, rev_flags[i]))
9115 return TRUE;
9117 return FALSE;
9120 static void
9121 filter_options(const char *argv[], bool blame)
9123 const char **flags = NULL;
9124 int next, flags_pos;
9126 for (next = flags_pos = 0; argv[next]; next++) {
9127 const char *flag = argv[next];
9128 int enum_value = -1;
9130 if (map_enum(&enum_value, commit_order_arg_map, flag)) {
9131 opt_commit_order = enum_value;
9132 update_commit_order_arg();
9133 continue;
9136 if (map_enum(&enum_value, ignore_space_arg_map, flag)) {
9137 opt_ignore_space = enum_value;
9138 update_ignore_space_arg();
9139 continue;
9142 argv[flags_pos++] = flag;
9145 argv[flags_pos] = NULL;
9147 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
9148 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
9150 if (flags) {
9151 for (next = flags_pos = 0; flags && flags[next]; next++) {
9152 const char *flag = flags[next];
9154 if (is_rev_flag(flag))
9155 argv_append(&opt_rev_argv, flag);
9156 else
9157 flags[flags_pos++] = flag;
9160 flags[flags_pos] = NULL;
9162 if (blame)
9163 opt_blame_argv = flags;
9164 else
9165 opt_diff_argv = flags;
9168 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
9171 static enum request
9172 parse_options(int argc, const char *argv[], bool pager_mode)
9174 enum request request;
9175 const char *subcommand;
9176 bool seen_dashdash = FALSE;
9177 const char **filter_argv = NULL;
9178 int i;
9180 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
9182 if (argc <= 1)
9183 return request;
9185 subcommand = argv[1];
9186 if (!strcmp(subcommand, "status")) {
9187 request = REQ_VIEW_STATUS;
9189 } else if (!strcmp(subcommand, "blame")) {
9190 request = REQ_VIEW_BLAME;
9192 } else if (!strcmp(subcommand, "show")) {
9193 request = REQ_VIEW_DIFF;
9195 } else if (!strcmp(subcommand, "log")) {
9196 request = REQ_VIEW_LOG;
9198 } else if (!strcmp(subcommand, "stash")) {
9199 request = REQ_VIEW_STASH;
9201 } else {
9202 subcommand = NULL;
9205 for (i = 1 + !!subcommand; i < argc; i++) {
9206 const char *opt = argv[i];
9208 // stop parsing our options after -- and let rev-parse handle the rest
9209 if (!seen_dashdash) {
9210 if (!strcmp(opt, "--")) {
9211 seen_dashdash = TRUE;
9212 continue;
9214 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
9215 printf("tig version %s\n", TIG_VERSION);
9216 quit(0);
9218 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
9219 printf("%s\n", usage);
9220 quit(0);
9222 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
9223 opt_lineno = atoi(opt + 1);
9224 continue;
9229 if (!argv_append(&filter_argv, opt))
9230 die("command too long");
9233 if (filter_argv)
9234 filter_options(filter_argv, request == REQ_VIEW_BLAME);
9236 /* Finish validating and setting up blame options */
9237 if (request == REQ_VIEW_BLAME) {
9238 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
9239 die("invalid number of options to blame\n\n%s", usage);
9241 if (opt_rev_argv) {
9242 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
9245 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
9248 return request;
9251 static enum request
9252 open_pager_mode(enum request request)
9254 enum open_flags flags = OPEN_DEFAULT;
9256 if (request == REQ_VIEW_PAGER) {
9257 /* Detect if the user requested the main view. */
9258 if (argv_contains(opt_rev_argv, "--stdin")) {
9259 request = REQ_VIEW_MAIN;
9260 flags |= OPEN_FORWARD_STDIN;
9261 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
9262 request = REQ_VIEW_MAIN;
9263 flags |= OPEN_STDIN;
9264 } else {
9265 flags |= OPEN_STDIN;
9268 } else if (request == REQ_VIEW_DIFF) {
9269 if (argv_contains(opt_rev_argv, "--stdin"))
9270 flags |= OPEN_FORWARD_STDIN;
9273 /* Open the requested view even if the pager mode is enabled so
9274 * the warning message below is displayed correctly. */
9275 open_view(NULL, request, flags);
9277 if (!open_in_pager_mode(flags)) {
9278 close(STDIN_FILENO);
9279 report("Ignoring stdin.");
9282 return REQ_NONE;
9285 static enum request
9286 run_prompt_command(struct view *view, char *cmd) {
9287 enum request request;
9289 if (cmd && string_isnumber(cmd)) {
9290 int lineno = view->pos.lineno + 1;
9292 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9293 select_view_line(view, lineno - 1);
9294 report_clear();
9295 } else {
9296 report("Unable to parse '%s' as a line number", cmd);
9298 } else if (cmd && iscommit(cmd)) {
9299 string_ncopy(opt_search, cmd, strlen(cmd));
9301 request = view_request(view, REQ_JUMP_COMMIT);
9302 if (request == REQ_JUMP_COMMIT) {
9303 report("Jumping to commits is not supported by the '%s' view", view->name);
9306 } else if (cmd && strlen(cmd) == 1) {
9307 request = get_keybinding(&view->ops->keymap, cmd[0]);
9308 return request;
9310 } else if (cmd && cmd[0] == '!') {
9311 struct view *next = VIEW(REQ_VIEW_PAGER);
9312 const char *argv[SIZEOF_ARG];
9313 int argc = 0;
9315 cmd++;
9316 /* When running random commands, initially show the
9317 * command in the title. However, it maybe later be
9318 * overwritten if a commit line is selected. */
9319 string_ncopy(next->ref, cmd, strlen(cmd));
9321 if (!argv_from_string(argv, &argc, cmd)) {
9322 report("Too many arguments");
9323 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9324 report("Argument formatting failed");
9325 } else {
9326 next->dir = NULL;
9327 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9330 } else if (cmd) {
9331 request = get_request(cmd);
9332 if (request != REQ_UNKNOWN)
9333 return request;
9335 char *args = strchr(cmd, ' ');
9336 if (args) {
9337 *args++ = 0;
9338 if (set_option(cmd, args) == SUCCESS) {
9339 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9340 if (!strcmp(cmd, "color"))
9341 init_colors();
9344 return request;
9346 return REQ_NONE;
9349 #ifdef NCURSES_MOUSE_VERSION
9350 static struct view *
9351 find_clicked_view(MEVENT *event)
9353 struct view *view;
9354 int i;
9356 foreach_displayed_view (view, i) {
9357 int beg_y = 0, beg_x = 0;
9359 getbegyx(view->win, beg_y, beg_x);
9361 if (beg_y <= event->y && event->y < beg_y + view->height
9362 && beg_x <= event->x && event->x < beg_x + view->width) {
9363 if (i != current_view) {
9364 current_view = i;
9366 return view;
9370 return NULL;
9373 static enum request
9374 handle_mouse_event(void)
9376 MEVENT event;
9377 struct view *view;
9379 if (getmouse(&event) != OK)
9380 return REQ_NONE;
9382 view = find_clicked_view(&event);
9383 if (!view)
9384 return REQ_NONE;
9386 if (event.bstate & BUTTON2_PRESSED)
9387 return REQ_SCROLL_WHEEL_DOWN;
9389 if (event.bstate & BUTTON4_PRESSED)
9390 return REQ_SCROLL_WHEEL_UP;
9392 if (event.bstate & BUTTON1_PRESSED) {
9393 if (event.y == view->pos.lineno - view->pos.offset) {
9394 /* Click is on the same line, perform an "ENTER" */
9395 return REQ_ENTER;
9397 } else {
9398 int y = getbegy(view->win);
9399 unsigned long lineno = (event.y - y) + view->pos.offset;
9401 select_view_line(view, lineno);
9402 update_view_title(view);
9403 report_clear();
9407 return REQ_NONE;
9409 #endif
9412 main(int argc, const char *argv[])
9414 const char *codeset = ENCODING_UTF8;
9415 bool pager_mode = !isatty(STDIN_FILENO);
9416 enum request request = parse_options(argc, argv, pager_mode);
9417 struct view *view;
9418 int i;
9420 signal(SIGINT, quit);
9421 signal(SIGQUIT, quit);
9422 signal(SIGPIPE, SIG_IGN);
9424 if (setlocale(LC_ALL, "")) {
9425 codeset = nl_langinfo(CODESET);
9428 foreach_view(view, i) {
9429 add_keymap(&view->ops->keymap);
9432 if (load_repo_info() == ERR)
9433 die("Failed to load repo info.");
9435 if (load_options() == ERR)
9436 die("Failed to load user config.");
9438 if (load_git_config() == ERR)
9439 die("Failed to load repo config.");
9441 /* Require a git repository unless when running in pager mode. */
9442 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9443 die("Not a git repository");
9445 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9446 char translit[SIZEOF_STR];
9448 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9449 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9450 else
9451 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9452 if (opt_iconv_out == ICONV_NONE)
9453 die("Failed to initialize character set conversion");
9456 if (load_refs(FALSE) == ERR)
9457 die("Failed to load refs.");
9459 init_display();
9461 if (pager_mode)
9462 request = open_pager_mode(request);
9464 while (view_driver(display[current_view], request)) {
9465 int key = get_input(0);
9467 #ifdef NCURSES_MOUSE_VERSION
9468 if (key == KEY_MOUSE) {
9469 request = handle_mouse_event();
9470 continue;
9472 #endif
9474 if (key == KEY_ESC)
9475 key = get_input(0) + 0x80;
9477 view = display[current_view];
9478 request = get_keybinding(&view->ops->keymap, key);
9480 /* Some low-level request handling. This keeps access to
9481 * status_win restricted. */
9482 switch (request) {
9483 case REQ_NONE:
9484 report("Unknown key, press %s for help",
9485 get_view_key(view, REQ_VIEW_HELP));
9486 break;
9487 case REQ_PROMPT:
9489 char *cmd = read_prompt(":");
9490 request = run_prompt_command(view, cmd);
9491 break;
9493 case REQ_SEARCH:
9494 case REQ_SEARCH_BACK:
9496 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9497 char *search = read_prompt(prompt);
9499 if (search)
9500 string_ncopy(opt_search, search, strlen(search));
9501 else if (*opt_search)
9502 request = request == REQ_SEARCH ?
9503 REQ_FIND_NEXT :
9504 REQ_FIND_PREV;
9505 else
9506 request = REQ_NONE;
9507 break;
9509 default:
9510 break;
9514 quit(0);
9516 return 0;
9519 /* vim: set ts=8 sw=8 noexpandtab: */