Move test-graph tool to the test folder
[tig.git] / tig.c
blobae14956a03b83f0b7e09da720bc41dcf71daacc2
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_cmdline_argv = NULL;
512 static const char **opt_diff_argv = NULL;
513 static const char **opt_rev_argv = NULL;
514 static const char **opt_file_argv = NULL;
515 static const char **opt_blame_argv = NULL;
516 static int opt_lineno = 0;
517 static bool opt_show_id = FALSE;
518 static int opt_id_cols = ID_WIDTH;
519 static bool opt_file_filter = TRUE;
520 static bool opt_show_title_overflow = FALSE;
521 static int opt_title_overflow = 50;
522 static char opt_env_lines[64] = "";
523 static char opt_env_columns[64] = "";
524 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
525 static bool opt_mouse = FALSE;
526 static int opt_scroll_wheel_lines = 3;
528 #define is_initial_commit() (!get_ref_head())
529 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
531 static bool
532 vertical_split_is_enabled(void)
534 if (opt_vertical_split == VERTICAL_SPLIT_AUTO) {
535 int height, width;
537 getmaxyx(stdscr, height, width);
538 return width * opt_scale_vsplit_view > (height - 1) * 2;
541 return opt_vertical_split == VERTICAL_SPLIT_VERTICAL;
544 static inline int
545 load_refs(bool force)
547 static bool loaded = FALSE;
549 if (force)
550 opt_head[0] = 0;
551 else if (loaded)
552 return OK;
554 loaded = TRUE;
555 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
558 static inline void
559 update_diff_context_arg(int diff_context)
561 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
562 string_ncopy(opt_diff_context_arg, "-U3", 3);
565 #define ENUM_ARG(enum_name, arg_string) ENUM_MAP_ENTRY(arg_string, enum_name)
567 static const struct enum_map_entry ignore_space_arg_map[] = {
568 ENUM_ARG(IGNORE_SPACE_NO, ""),
569 ENUM_ARG(IGNORE_SPACE_ALL, "--ignore-all-space"),
570 ENUM_ARG(IGNORE_SPACE_SOME, "--ignore-space-change"),
571 ENUM_ARG(IGNORE_SPACE_AT_EOL, "--ignore-space-at-eol"),
574 static inline void
575 update_ignore_space_arg()
577 enum_copy_name(opt_ignore_space_arg, ignore_space_arg_map[opt_ignore_space]);
580 static const struct enum_map_entry commit_order_arg_map[] = {
581 ENUM_ARG(COMMIT_ORDER_DEFAULT, ""),
582 ENUM_ARG(COMMIT_ORDER_TOPO, "--topo-order"),
583 ENUM_ARG(COMMIT_ORDER_DATE, "--date-order"),
584 ENUM_ARG(COMMIT_ORDER_REVERSE, "--reverse"),
587 static inline void
588 update_commit_order_arg()
590 enum_copy_name(opt_commit_order_arg, commit_order_arg_map[opt_commit_order]);
593 static inline void
594 update_notes_arg()
596 if (opt_notes) {
597 string_copy(opt_notes_arg, "--show-notes");
598 } else {
599 /* Notes are disabled by default when passing --pretty args. */
600 string_copy(opt_notes_arg, "");
605 * Line-oriented content detection.
608 #define LINE_INFO \
609 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
610 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
611 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
612 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
613 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
614 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
615 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
616 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
617 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
618 LINE(DIFF_DELETED_FILE_MODE, \
619 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
620 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
621 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
622 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
623 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
624 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
625 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
626 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
627 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
628 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
629 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
630 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
631 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
632 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
633 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
634 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
635 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
636 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
637 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
638 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
639 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
640 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
641 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
642 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
644 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
645 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
646 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
647 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
648 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
649 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
650 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
651 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
652 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
653 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
654 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
655 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
656 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
657 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
658 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
659 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
660 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
661 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
662 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
663 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
664 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
665 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
666 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
667 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
668 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
669 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
670 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
671 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
672 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
673 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
674 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
675 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
676 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
677 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
678 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
679 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
680 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
681 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
682 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
683 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
684 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
685 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
686 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
687 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
689 enum line_type {
690 #define LINE(type, line, fg, bg, attr) \
691 LINE_##type
692 LINE_INFO,
693 LINE_NONE
694 #undef LINE
697 struct line_info {
698 const char *name; /* Option name. */
699 int namelen; /* Size of option name. */
700 const char *line; /* The start of line to match. */
701 int linelen; /* Size of string to match. */
702 int fg, bg, attr; /* Color and text attributes for the lines. */
703 int color_pair;
706 static struct line_info line_info[] = {
707 #define LINE(type, line, fg, bg, attr) \
708 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
709 LINE_INFO
710 #undef LINE
713 static struct line_info **color_pair;
714 static size_t color_pairs;
716 static struct line_info *custom_color;
717 static size_t custom_colors;
719 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
720 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
722 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
723 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
725 /* Color IDs must be 1 or higher. [GH #15] */
726 #define COLOR_ID(line_type) ((line_type) + 1)
728 static enum line_type
729 get_line_type(const char *line)
731 int linelen = strlen(line);
732 enum line_type type;
734 for (type = 0; type < custom_colors; type++)
735 /* Case insensitive search matches Signed-off-by lines better. */
736 if (linelen >= custom_color[type].linelen &&
737 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
738 return TO_CUSTOM_COLOR_TYPE(type);
740 for (type = 0; type < ARRAY_SIZE(line_info); type++)
741 /* Case insensitive search matches Signed-off-by lines better. */
742 if (linelen >= line_info[type].linelen &&
743 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
744 return type;
746 return LINE_DEFAULT;
749 static enum line_type
750 get_line_type_from_ref(const struct ref *ref)
752 if (ref->head)
753 return LINE_MAIN_HEAD;
754 else if (ref->ltag)
755 return LINE_MAIN_LOCAL_TAG;
756 else if (ref->tag)
757 return LINE_MAIN_TAG;
758 else if (ref->tracked)
759 return LINE_MAIN_TRACKED;
760 else if (ref->remote)
761 return LINE_MAIN_REMOTE;
762 else if (ref->replace)
763 return LINE_MAIN_REPLACE;
765 return LINE_MAIN_REF;
768 static inline struct line_info *
769 get_line(enum line_type type)
771 if (type > LINE_NONE) {
772 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
773 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
774 } else {
775 assert(type < ARRAY_SIZE(line_info));
776 return &line_info[type];
780 static inline int
781 get_line_color(enum line_type type)
783 return COLOR_ID(get_line(type)->color_pair);
786 static inline int
787 get_line_attr(enum line_type type)
789 struct line_info *info = get_line(type);
791 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
794 static struct line_info *
795 get_line_info(const char *name)
797 size_t namelen = strlen(name);
798 enum line_type type;
800 for (type = 0; type < ARRAY_SIZE(line_info); type++)
801 if (enum_equals(line_info[type], name, namelen))
802 return &line_info[type];
804 return NULL;
807 static struct line_info *
808 add_custom_color(const char *quoted_line)
810 struct line_info *info;
811 char *line;
812 size_t linelen;
814 if (!realloc_custom_color(&custom_color, custom_colors, 1))
815 die("Failed to alloc custom line info");
817 linelen = strlen(quoted_line) - 1;
818 line = malloc(linelen);
819 if (!line)
820 return NULL;
822 strncpy(line, quoted_line + 1, linelen);
823 line[linelen - 1] = 0;
825 info = &custom_color[custom_colors++];
826 info->name = info->line = line;
827 info->namelen = info->linelen = strlen(line);
829 return info;
832 static void
833 init_line_info_color_pair(struct line_info *info, enum line_type type,
834 int default_bg, int default_fg)
836 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
837 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
838 int i;
840 for (i = 0; i < color_pairs; i++) {
841 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
842 info->color_pair = i;
843 return;
847 if (!realloc_color_pair(&color_pair, color_pairs, 1))
848 die("Failed to alloc color pair");
850 color_pair[color_pairs] = info;
851 info->color_pair = color_pairs++;
852 init_pair(COLOR_ID(info->color_pair), fg, bg);
855 static void
856 init_colors(void)
858 int default_bg = line_info[LINE_DEFAULT].bg;
859 int default_fg = line_info[LINE_DEFAULT].fg;
860 enum line_type type;
862 start_color();
864 if (assume_default_colors(default_fg, default_bg) == ERR) {
865 default_bg = COLOR_BLACK;
866 default_fg = COLOR_WHITE;
869 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
870 struct line_info *info = &line_info[type];
872 init_line_info_color_pair(info, type, default_bg, default_fg);
875 for (type = 0; type < custom_colors; type++) {
876 struct line_info *info = &custom_color[type];
878 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
879 default_bg, default_fg);
883 struct line {
884 enum line_type type;
885 unsigned int lineno:24;
887 /* State flags */
888 unsigned int selected:1;
889 unsigned int dirty:1;
890 unsigned int cleareol:1;
891 unsigned int wrapped:1;
893 unsigned int user_flags:6;
894 void *data; /* User data */
899 * Keys
902 struct keybinding {
903 int alias;
904 enum request request;
907 static struct keybinding default_keybindings[] = {
908 /* View switching */
909 { 'm', REQ_VIEW_MAIN },
910 { 'd', REQ_VIEW_DIFF },
911 { 'l', REQ_VIEW_LOG },
912 { 't', REQ_VIEW_TREE },
913 { 'f', REQ_VIEW_BLOB },
914 { 'B', REQ_VIEW_BLAME },
915 { 'H', REQ_VIEW_BRANCH },
916 { 'p', REQ_VIEW_PAGER },
917 { 'h', REQ_VIEW_HELP },
918 { 'S', REQ_VIEW_STATUS },
919 { 'c', REQ_VIEW_STAGE },
920 { 'y', REQ_VIEW_STASH },
922 /* View manipulation */
923 { 'q', REQ_VIEW_CLOSE },
924 { KEY_TAB, REQ_VIEW_NEXT },
925 { KEY_RETURN, REQ_ENTER },
926 { KEY_UP, REQ_PREVIOUS },
927 { KEY_CTL('P'), REQ_PREVIOUS },
928 { KEY_DOWN, REQ_NEXT },
929 { KEY_CTL('N'), REQ_NEXT },
930 { 'R', REQ_REFRESH },
931 { KEY_F(5), REQ_REFRESH },
932 { 'O', REQ_MAXIMIZE },
933 { ',', REQ_PARENT },
934 { '<', REQ_BACK },
936 /* View specific */
937 { 'u', REQ_STATUS_UPDATE },
938 { '!', REQ_STATUS_REVERT },
939 { 'M', REQ_STATUS_MERGE },
940 { '1', REQ_STAGE_UPDATE_LINE },
941 { '@', REQ_STAGE_NEXT },
942 { '\\', REQ_STAGE_SPLIT_CHUNK },
943 { '[', REQ_DIFF_CONTEXT_DOWN },
944 { ']', REQ_DIFF_CONTEXT_UP },
946 /* Cursor navigation */
947 { 'k', REQ_MOVE_UP },
948 { 'j', REQ_MOVE_DOWN },
949 { KEY_HOME, REQ_MOVE_FIRST_LINE },
950 { KEY_END, REQ_MOVE_LAST_LINE },
951 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
952 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
953 { ' ', REQ_MOVE_PAGE_DOWN },
954 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
955 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
956 { 'b', REQ_MOVE_PAGE_UP },
957 { '-', REQ_MOVE_PAGE_UP },
959 /* Scrolling */
960 { '|', REQ_SCROLL_FIRST_COL },
961 { KEY_LEFT, REQ_SCROLL_LEFT },
962 { KEY_RIGHT, REQ_SCROLL_RIGHT },
963 { KEY_IC, REQ_SCROLL_LINE_UP },
964 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
965 { KEY_DC, REQ_SCROLL_LINE_DOWN },
966 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
967 { 'w', REQ_SCROLL_PAGE_UP },
968 { 's', REQ_SCROLL_PAGE_DOWN },
970 /* Searching */
971 { '/', REQ_SEARCH },
972 { '?', REQ_SEARCH_BACK },
973 { 'n', REQ_FIND_NEXT },
974 { 'N', REQ_FIND_PREV },
976 /* Misc */
977 { 'Q', REQ_QUIT },
978 { 'z', REQ_STOP_LOADING },
979 { 'v', REQ_SHOW_VERSION },
980 { 'r', REQ_SCREEN_REDRAW },
981 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
982 { 'o', REQ_OPTIONS },
983 { '.', REQ_TOGGLE_LINENO },
984 { 'D', REQ_TOGGLE_DATE },
985 { 'A', REQ_TOGGLE_AUTHOR },
986 { 'g', REQ_TOGGLE_REV_GRAPH },
987 { '~', REQ_TOGGLE_GRAPHIC },
988 { '#', REQ_TOGGLE_FILENAME },
989 { 'F', REQ_TOGGLE_REFS },
990 { 'I', REQ_TOGGLE_SORT_ORDER },
991 { 'i', REQ_TOGGLE_SORT_FIELD },
992 { 'W', REQ_TOGGLE_IGNORE_SPACE },
993 { 'X', REQ_TOGGLE_ID },
994 { '%', REQ_TOGGLE_FILES },
995 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
996 { ':', REQ_PROMPT },
997 { 'e', REQ_EDIT },
1000 struct keymap {
1001 const char *name;
1002 struct keymap *next;
1003 struct keybinding *data;
1004 size_t size;
1005 bool hidden;
1008 static struct keymap generic_keymap = { "generic" };
1009 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
1011 static struct keymap *keymaps = &generic_keymap;
1013 static void
1014 add_keymap(struct keymap *keymap)
1016 keymap->next = keymaps;
1017 keymaps = keymap;
1020 static struct keymap *
1021 get_keymap(const char *name)
1023 struct keymap *keymap = keymaps;
1025 while (keymap) {
1026 if (!strcasecmp(keymap->name, name))
1027 return keymap;
1028 keymap = keymap->next;
1031 return NULL;
1035 static void
1036 add_keybinding(struct keymap *table, enum request request, int key)
1038 size_t i;
1040 for (i = 0; i < table->size; i++) {
1041 if (table->data[i].alias == key) {
1042 table->data[i].request = request;
1043 return;
1047 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1048 if (!table->data)
1049 die("Failed to allocate keybinding");
1050 table->data[table->size].alias = key;
1051 table->data[table->size++].request = request;
1053 if (request == REQ_NONE && is_generic_keymap(table)) {
1054 int i;
1056 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1057 if (default_keybindings[i].alias == key)
1058 default_keybindings[i].request = REQ_NONE;
1062 /* Looks for a key binding first in the given map, then in the generic map, and
1063 * lastly in the default keybindings. */
1064 static enum request
1065 get_keybinding(struct keymap *keymap, int key)
1067 size_t i;
1069 for (i = 0; i < keymap->size; i++)
1070 if (keymap->data[i].alias == key)
1071 return keymap->data[i].request;
1073 for (i = 0; i < generic_keymap.size; i++)
1074 if (generic_keymap.data[i].alias == key)
1075 return generic_keymap.data[i].request;
1077 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1078 if (default_keybindings[i].alias == key)
1079 return default_keybindings[i].request;
1081 return (enum request) key;
1085 struct key {
1086 const char *name;
1087 int value;
1090 static const struct key key_table[] = {
1091 { "Enter", KEY_RETURN },
1092 { "Space", ' ' },
1093 { "Backspace", KEY_BACKSPACE },
1094 { "Tab", KEY_TAB },
1095 { "Escape", KEY_ESC },
1096 { "Left", KEY_LEFT },
1097 { "Right", KEY_RIGHT },
1098 { "Up", KEY_UP },
1099 { "Down", KEY_DOWN },
1100 { "Insert", KEY_IC },
1101 { "Delete", KEY_DC },
1102 { "Hash", '#' },
1103 { "Home", KEY_HOME },
1104 { "End", KEY_END },
1105 { "PageUp", KEY_PPAGE },
1106 { "PageDown", KEY_NPAGE },
1107 { "F1", KEY_F(1) },
1108 { "F2", KEY_F(2) },
1109 { "F3", KEY_F(3) },
1110 { "F4", KEY_F(4) },
1111 { "F5", KEY_F(5) },
1112 { "F6", KEY_F(6) },
1113 { "F7", KEY_F(7) },
1114 { "F8", KEY_F(8) },
1115 { "F9", KEY_F(9) },
1116 { "F10", KEY_F(10) },
1117 { "F11", KEY_F(11) },
1118 { "F12", KEY_F(12) },
1121 static int
1122 get_key_value(const char *name)
1124 int i;
1126 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1127 if (!strcasecmp(key_table[i].name, name))
1128 return key_table[i].value;
1130 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1131 return (int)name[2] + 0x80;
1132 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1133 return (int)name[1] & 0x1f;
1134 if (strlen(name) == 1 && isprint(*name))
1135 return (int) *name;
1136 return ERR;
1139 static const char *
1140 get_key_name(int key_value)
1142 static char key_char[] = "'X'\0";
1143 const char *seq = NULL;
1144 int key;
1146 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1147 if (key_table[key].value == key_value)
1148 seq = key_table[key].name;
1150 if (seq == NULL && key_value < 0x7f) {
1151 char *s = key_char + 1;
1153 if (key_value >= 0x20) {
1154 *s++ = key_value;
1155 } else {
1156 *s++ = '^';
1157 *s++ = 0x40 | (key_value & 0x1f);
1159 *s++ = '\'';
1160 *s++ = '\0';
1161 seq = key_char;
1164 return seq ? seq : "(no key)";
1167 static bool
1168 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1170 const char *sep = *pos > 0 ? ", " : "";
1171 const char *keyname = get_key_name(keybinding->alias);
1173 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1176 static bool
1177 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1178 struct keymap *keymap, bool all)
1180 int i;
1182 for (i = 0; i < keymap->size; i++) {
1183 if (keymap->data[i].request == request) {
1184 if (!append_key(buf, pos, &keymap->data[i]))
1185 return FALSE;
1186 if (!all)
1187 break;
1191 return TRUE;
1194 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1196 static const char *
1197 get_keys(struct keymap *keymap, enum request request, bool all)
1199 static char buf[BUFSIZ];
1200 size_t pos = 0;
1201 int i;
1203 buf[pos] = 0;
1205 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1206 return "Too many keybindings!";
1207 if (pos > 0 && !all)
1208 return buf;
1210 if (!is_generic_keymap(keymap)) {
1211 /* Only the generic keymap includes the default keybindings when
1212 * listing all keys. */
1213 if (all)
1214 return buf;
1216 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1217 return "Too many keybindings!";
1218 if (pos)
1219 return buf;
1222 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1223 if (default_keybindings[i].request == request) {
1224 if (!append_key(buf, &pos, &default_keybindings[i]))
1225 return "Too many keybindings!";
1226 if (!all)
1227 return buf;
1231 return buf;
1234 enum run_request_flag {
1235 RUN_REQUEST_DEFAULT = 0,
1236 RUN_REQUEST_FORCE = 1,
1237 RUN_REQUEST_SILENT = 2,
1238 RUN_REQUEST_CONFIRM = 4,
1239 RUN_REQUEST_EXIT = 8,
1240 RUN_REQUEST_INTERNAL = 16,
1243 struct run_request {
1244 struct keymap *keymap;
1245 int key;
1246 const char **argv;
1247 bool silent;
1248 bool confirm;
1249 bool exit;
1250 bool internal;
1253 static struct run_request *run_request;
1254 static size_t run_requests;
1256 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1258 static bool
1259 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1261 bool force = flags & RUN_REQUEST_FORCE;
1262 struct run_request *req;
1264 if (!force && get_keybinding(keymap, key) != key)
1265 return TRUE;
1267 if (!realloc_run_requests(&run_request, run_requests, 1))
1268 return FALSE;
1270 if (!argv_copy(&run_request[run_requests].argv, argv))
1271 return FALSE;
1273 req = &run_request[run_requests++];
1274 req->silent = flags & RUN_REQUEST_SILENT;
1275 req->confirm = flags & RUN_REQUEST_CONFIRM;
1276 req->exit = flags & RUN_REQUEST_EXIT;
1277 req->internal = flags & RUN_REQUEST_INTERNAL;
1278 req->keymap = keymap;
1279 req->key = key;
1281 add_keybinding(keymap, REQ_RUN_REQUESTS + run_requests, key);
1282 return TRUE;
1285 static struct run_request *
1286 get_run_request(enum request request)
1288 if (request <= REQ_RUN_REQUESTS || request > REQ_RUN_REQUESTS + run_requests)
1289 return NULL;
1290 return &run_request[request - REQ_RUN_REQUESTS - 1];
1293 static void
1294 add_builtin_run_requests(void)
1296 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1297 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1298 const char *commit[] = { "git", "commit", NULL };
1299 const char *gc[] = { "git", "gc", NULL };
1300 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1302 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1303 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1304 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1305 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1306 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1310 * User config file handling.
1313 static const struct enum_map_entry color_map[] = {
1314 #define COLOR_MAP(name) ENUM_MAP_ENTRY(#name, COLOR_##name)
1315 COLOR_MAP(DEFAULT),
1316 COLOR_MAP(BLACK),
1317 COLOR_MAP(BLUE),
1318 COLOR_MAP(CYAN),
1319 COLOR_MAP(GREEN),
1320 COLOR_MAP(MAGENTA),
1321 COLOR_MAP(RED),
1322 COLOR_MAP(WHITE),
1323 COLOR_MAP(YELLOW),
1326 static const struct enum_map_entry attr_map[] = {
1327 #define ATTR_MAP(name) ENUM_MAP_ENTRY(#name, A_##name)
1328 ATTR_MAP(NORMAL),
1329 ATTR_MAP(BLINK),
1330 ATTR_MAP(BOLD),
1331 ATTR_MAP(DIM),
1332 ATTR_MAP(REVERSE),
1333 ATTR_MAP(STANDOUT),
1334 ATTR_MAP(UNDERLINE),
1337 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1339 static enum status_code
1340 parse_step(double *opt, const char *arg)
1342 *opt = atoi(arg);
1343 if (!strchr(arg, '%'))
1344 return SUCCESS;
1346 /* "Shift down" so 100% and 1 does not conflict. */
1347 *opt = (*opt - 1) / 100;
1348 if (*opt >= 1.0) {
1349 *opt = 0.99;
1350 return ERROR_INVALID_STEP_VALUE;
1352 if (*opt < 0.0) {
1353 *opt = 1;
1354 return ERROR_INVALID_STEP_VALUE;
1356 return SUCCESS;
1359 static enum status_code
1360 parse_int(int *opt, const char *arg, int min, int max)
1362 int value = atoi(arg);
1364 if (min <= value && value <= max) {
1365 *opt = value;
1366 return SUCCESS;
1369 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1372 #define parse_id(opt, arg) \
1373 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1375 static bool
1376 set_color(int *color, const char *name)
1378 if (map_enum(color, color_map, name))
1379 return TRUE;
1380 if (!prefixcmp(name, "color"))
1381 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1382 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1383 return parse_int(color, name, 0, 255) == SUCCESS;
1386 /* Wants: object fgcolor bgcolor [attribute] */
1387 static enum status_code
1388 option_color_command(int argc, const char *argv[])
1390 struct line_info *info;
1392 if (argc < 3)
1393 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1395 if (*argv[0] == '"' || *argv[0] == '\'') {
1396 info = add_custom_color(argv[0]);
1397 } else {
1398 info = get_line_info(argv[0]);
1400 if (!info) {
1401 static const struct enum_map_entry obsolete[] = {
1402 ENUM_MAP_ENTRY("main-delim", LINE_DELIMITER),
1403 ENUM_MAP_ENTRY("main-date", LINE_DATE),
1404 ENUM_MAP_ENTRY("main-author", LINE_AUTHOR),
1405 ENUM_MAP_ENTRY("blame-id", LINE_ID),
1407 int index;
1409 if (!map_enum(&index, obsolete, argv[0]))
1410 return ERROR_UNKNOWN_COLOR_NAME;
1411 info = &line_info[index];
1414 if (!set_color(&info->fg, argv[1]) ||
1415 !set_color(&info->bg, argv[2]))
1416 return ERROR_UNKNOWN_COLOR;
1418 info->attr = 0;
1419 while (argc-- > 3) {
1420 int attr;
1422 if (!set_attribute(&attr, argv[argc]))
1423 return ERROR_UNKNOWN_ATTRIBUTE;
1424 info->attr |= attr;
1427 return SUCCESS;
1430 static enum status_code
1431 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1433 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1434 ? TRUE : FALSE;
1435 if (matched)
1436 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1437 return SUCCESS;
1440 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1442 static enum status_code
1443 parse_enum(unsigned int *opt, const char *arg, const struct enum_map *map)
1445 bool is_true;
1447 assert(map->size > 1);
1449 if (map_enum_do(map->entries, map->size, (int *) opt, arg))
1450 return SUCCESS;
1452 parse_bool(&is_true, arg);
1453 *opt = is_true ? map->entries[1].value : map->entries[0].value;
1454 return SUCCESS;
1457 static enum status_code
1458 parse_string(char *opt, const char *arg, size_t optsize)
1460 int arglen = strlen(arg);
1462 switch (arg[0]) {
1463 case '\"':
1464 case '\'':
1465 if (arglen == 1 || arg[arglen - 1] != arg[0])
1466 return ERROR_UNMATCHED_QUOTATION;
1467 arg += 1; arglen -= 2;
1468 default:
1469 string_ncopy_do(opt, optsize, arg, arglen);
1470 return SUCCESS;
1474 static enum status_code
1475 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1477 char buf[SIZEOF_STR];
1478 enum status_code code = parse_string(buf, arg, sizeof(buf));
1480 if (code == SUCCESS) {
1481 struct encoding *encoding = *encoding_ref;
1483 if (encoding && !priority)
1484 return code;
1485 encoding = encoding_open(buf);
1486 if (encoding)
1487 *encoding_ref = encoding;
1490 return code;
1493 static enum status_code
1494 parse_args(const char ***args, const char *argv[])
1496 if (!argv_copy(args, argv))
1497 return ERROR_OUT_OF_MEMORY;
1498 return SUCCESS;
1501 /* Wants: name = value */
1502 static enum status_code
1503 option_set_command(int argc, const char *argv[])
1505 if (argc < 3)
1506 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1508 if (strcmp(argv[1], "="))
1509 return ERROR_NO_VALUE_ASSIGNED;
1511 if (!strcmp(argv[0], "blame-options"))
1512 return parse_args(&opt_blame_argv, argv + 2);
1514 if (!strcmp(argv[0], "diff-options"))
1515 return parse_args(&opt_diff_argv, argv + 2);
1517 if (argc != 3)
1518 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1520 if (!strcmp(argv[0], "show-author"))
1521 return parse_enum(&opt_author, argv[2], author_map);
1523 if (!strcmp(argv[0], "show-date"))
1524 return parse_enum(&opt_date, argv[2], date_map);
1526 if (!strcmp(argv[0], "show-rev-graph"))
1527 return parse_bool(&opt_rev_graph, argv[2]);
1529 if (!strcmp(argv[0], "show-refs"))
1530 return parse_bool(&opt_show_refs, argv[2]);
1532 if (!strcmp(argv[0], "show-changes"))
1533 return parse_bool(&opt_show_changes, argv[2]);
1535 if (!strcmp(argv[0], "show-notes")) {
1536 bool matched = FALSE;
1537 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1539 if (res == SUCCESS && matched) {
1540 update_notes_arg();
1541 return res;
1544 opt_notes = TRUE;
1545 strcpy(opt_notes_arg, "--show-notes=");
1546 res = parse_string(opt_notes_arg + 8, argv[2],
1547 sizeof(opt_notes_arg) - 8);
1548 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1549 opt_notes_arg[7] = '\0';
1550 return res;
1553 if (!strcmp(argv[0], "show-line-numbers"))
1554 return parse_bool(&opt_line_number, argv[2]);
1556 if (!strcmp(argv[0], "line-graphics"))
1557 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1559 if (!strcmp(argv[0], "line-number-interval"))
1560 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1562 if (!strcmp(argv[0], "author-width"))
1563 return parse_int(&opt_author_width, argv[2], 0, 1024);
1565 if (!strcmp(argv[0], "filename-width"))
1566 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1568 if (!strcmp(argv[0], "show-filename"))
1569 return parse_enum(&opt_filename, argv[2], filename_map);
1571 if (!strcmp(argv[0], "show-file-size"))
1572 return parse_enum(&opt_file_size, argv[2], file_size_map);
1574 if (!strcmp(argv[0], "horizontal-scroll"))
1575 return parse_step(&opt_hscroll, argv[2]);
1577 if (!strcmp(argv[0], "split-view-height"))
1578 return parse_step(&opt_scale_split_view, argv[2]);
1580 if (!strcmp(argv[0], "vertical-split"))
1581 return parse_enum(&opt_vertical_split, argv[2], vertical_split_map);
1583 if (!strcmp(argv[0], "tab-size"))
1584 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1586 if (!strcmp(argv[0], "diff-context") && !*opt_diff_context_arg) {
1587 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1589 if (code == SUCCESS)
1590 update_diff_context_arg(opt_diff_context);
1591 return code;
1594 if (!strcmp(argv[0], "ignore-space") && !*opt_ignore_space_arg) {
1595 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1597 if (code == SUCCESS)
1598 update_ignore_space_arg();
1599 return code;
1602 if (!strcmp(argv[0], "commit-order") && !*opt_commit_order_arg) {
1603 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1605 if (code == SUCCESS)
1606 update_commit_order_arg();
1607 return code;
1610 if (!strcmp(argv[0], "status-untracked-dirs"))
1611 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1613 if (!strcmp(argv[0], "read-git-colors"))
1614 return parse_bool(&opt_read_git_colors, argv[2]);
1616 if (!strcmp(argv[0], "ignore-case"))
1617 return parse_bool(&opt_ignore_case, argv[2]);
1619 if (!strcmp(argv[0], "focus-child"))
1620 return parse_bool(&opt_focus_child, argv[2]);
1622 if (!strcmp(argv[0], "wrap-lines"))
1623 return parse_bool(&opt_wrap_lines, argv[2]);
1625 if (!strcmp(argv[0], "show-id"))
1626 return parse_bool(&opt_show_id, argv[2]);
1628 if (!strcmp(argv[0], "id-width"))
1629 return parse_id(&opt_id_cols, argv[2]);
1631 if (!strcmp(argv[0], "title-overflow")) {
1632 bool matched;
1633 enum status_code code;
1636 * "title-overflow" is considered a boolint.
1637 * We try to parse it as a boolean (and set the value to 50 if true),
1638 * otherwise we parse it as an integer and use the given value.
1640 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1641 if (code == SUCCESS && matched) {
1642 if (opt_show_title_overflow)
1643 opt_title_overflow = 50;
1644 } else {
1645 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1646 if (code == SUCCESS)
1647 opt_show_title_overflow = TRUE;
1650 return code;
1653 if (!strcmp(argv[0], "editor-line-number"))
1654 return parse_bool(&opt_editor_lineno, argv[2]);
1656 if (!strcmp(argv[0], "mouse"))
1657 return parse_bool(&opt_mouse, argv[2]);
1659 if (!strcmp(argv[0], "mouse-scroll"))
1660 return parse_int(&opt_scroll_wheel_lines, argv[2], 0, 1024);
1662 return ERROR_UNKNOWN_VARIABLE_NAME;
1665 /* Wants: mode request key */
1666 static enum status_code
1667 option_bind_command(int argc, const char *argv[])
1669 enum request request;
1670 struct keymap *keymap;
1671 int key;
1673 if (argc < 3)
1674 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1676 if (!(keymap = get_keymap(argv[0])))
1677 return ERROR_UNKNOWN_KEY_MAP;
1679 key = get_key_value(argv[1]);
1680 if (key == ERR)
1681 return ERROR_UNKNOWN_KEY;
1683 request = get_request(argv[2]);
1684 if (request == REQ_UNKNOWN) {
1685 static const struct enum_map_entry obsolete[] = {
1686 ENUM_MAP_ENTRY("cherry-pick", REQ_NONE),
1687 ENUM_MAP_ENTRY("screen-resize", REQ_NONE),
1688 ENUM_MAP_ENTRY("tree-parent", REQ_PARENT),
1690 int alias;
1692 if (map_enum(&alias, obsolete, argv[2])) {
1693 if (alias != REQ_NONE)
1694 add_keybinding(keymap, alias, key);
1695 return ERROR_OBSOLETE_REQUEST_NAME;
1699 if (request == REQ_UNKNOWN) {
1700 enum run_request_flag flags = RUN_REQUEST_FORCE;
1702 if (strchr("!?@<", *argv[2])) {
1703 while (*argv[2]) {
1704 if (*argv[2] == '@') {
1705 flags |= RUN_REQUEST_SILENT;
1706 } else if (*argv[2] == '?') {
1707 flags |= RUN_REQUEST_CONFIRM;
1708 } else if (*argv[2] == '<') {
1709 flags |= RUN_REQUEST_EXIT;
1710 } else if (*argv[2] != '!') {
1711 break;
1713 argv[2]++;
1716 } else if (*argv[2] == ':') {
1717 argv[2]++;
1718 flags |= RUN_REQUEST_INTERNAL;
1720 } else {
1721 return ERROR_UNKNOWN_REQUEST_NAME;
1724 return add_run_request(keymap, key, argv + 2, flags)
1725 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1728 add_keybinding(keymap, request, key);
1730 return SUCCESS;
1734 static enum status_code load_option_file(const char *path);
1736 static enum status_code
1737 option_source_command(int argc, const char *argv[])
1739 if (argc < 1)
1740 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1742 return load_option_file(argv[0]);
1745 static enum status_code
1746 set_option(const char *opt, char *value)
1748 const char *argv[SIZEOF_ARG];
1749 int argc = 0;
1751 if (!argv_from_string(argv, &argc, value))
1752 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1754 if (!strcmp(opt, "color"))
1755 return option_color_command(argc, argv);
1757 if (!strcmp(opt, "set"))
1758 return option_set_command(argc, argv);
1760 if (!strcmp(opt, "bind"))
1761 return option_bind_command(argc, argv);
1763 if (!strcmp(opt, "source"))
1764 return option_source_command(argc, argv);
1766 return ERROR_UNKNOWN_OPTION_COMMAND;
1769 struct config_state {
1770 const char *path;
1771 int lineno;
1772 bool errors;
1775 static int
1776 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1778 struct config_state *config = data;
1779 enum status_code status = ERROR_NO_OPTION_VALUE;
1781 config->lineno++;
1783 /* Check for comment markers, since read_properties() will
1784 * only ensure opt and value are split at first " \t". */
1785 optlen = strcspn(opt, "#");
1786 if (optlen == 0)
1787 return OK;
1789 if (opt[optlen] == 0) {
1790 /* Look for comment endings in the value. */
1791 size_t len = strcspn(value, "#");
1793 if (len < valuelen) {
1794 valuelen = len;
1795 value[valuelen] = 0;
1798 status = set_option(opt, value);
1801 if (status != SUCCESS) {
1802 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1803 get_status_message(status), (int) optlen, opt);
1804 config->errors = TRUE;
1807 /* Always keep going if errors are encountered. */
1808 return OK;
1811 static enum status_code
1812 load_option_file(const char *path)
1814 struct config_state config = { path, 0, FALSE };
1815 struct io io;
1816 char buf[SIZEOF_STR];
1818 /* Do not read configuration from stdin if set to "" */
1819 if (!path || !strlen(path))
1820 return SUCCESS;
1822 if (!prefixcmp(path, "~/")) {
1823 const char *home = getenv("HOME");
1825 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1826 return ERROR_HOME_UNRESOLVABLE;
1827 path = buf;
1830 /* It's OK that the file doesn't exist. */
1831 if (!io_open(&io, "%s", path))
1832 return ERROR_FILE_DOES_NOT_EXIST;
1834 if (io_load(&io, " \t", read_option, &config) == ERR ||
1835 config.errors == TRUE)
1836 warn("Errors while loading %s.", path);
1837 return SUCCESS;
1840 static int
1841 load_options(void)
1843 const char *tigrc_user = getenv("TIGRC_USER");
1844 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1845 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1846 const bool diff_opts_from_args = !!opt_diff_argv;
1848 if (!tigrc_system)
1849 tigrc_system = SYSCONFDIR "/tigrc";
1850 load_option_file(tigrc_system);
1852 if (!tigrc_user)
1853 tigrc_user = "~/.tigrc";
1854 load_option_file(tigrc_user);
1856 /* Add _after_ loading config files to avoid adding run requests
1857 * that conflict with keybindings. */
1858 add_builtin_run_requests();
1860 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1861 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1862 char buf[SIZEOF_STR];
1863 int argc = 0;
1865 if (!string_format(buf, "%s", tig_diff_opts) ||
1866 !argv_from_string(diff_opts, &argc, buf))
1867 die("TIG_DIFF_OPTS contains too many arguments");
1868 else if (!argv_copy(&opt_diff_argv, diff_opts))
1869 die("Failed to format TIG_DIFF_OPTS arguments");
1872 return OK;
1877 * The viewer
1880 struct view;
1881 struct view_ops;
1883 /* The display array of active views and the index of the current view. */
1884 static struct view *display[2];
1885 static WINDOW *display_win[2];
1886 static WINDOW *display_title[2];
1887 static WINDOW *display_sep;
1889 static unsigned int current_view;
1891 #define foreach_displayed_view(view, i) \
1892 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1894 #define displayed_views() (display[1] != NULL ? 2 : 1)
1896 /* Current head and commit ID */
1897 static char ref_blob[SIZEOF_REF] = "";
1898 static char ref_commit[SIZEOF_REF] = "HEAD";
1899 static char ref_head[SIZEOF_REF] = "HEAD";
1900 static char ref_branch[SIZEOF_REF] = "";
1901 static char ref_status[SIZEOF_STR] = "";
1902 static char ref_stash[SIZEOF_REF] = "";
1904 enum view_flag {
1905 VIEW_NO_FLAGS = 0,
1906 VIEW_ALWAYS_LINENO = 1 << 0,
1907 VIEW_CUSTOM_STATUS = 1 << 1,
1908 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1909 VIEW_ADD_PAGER_REFS = 1 << 3,
1910 VIEW_OPEN_DIFF = 1 << 4,
1911 VIEW_NO_REF = 1 << 5,
1912 VIEW_NO_GIT_DIR = 1 << 6,
1913 VIEW_DIFF_LIKE = 1 << 7,
1914 VIEW_SEND_CHILD_ENTER = 1 << 9,
1915 VIEW_FILE_FILTER = 1 << 10,
1916 VIEW_LOG_LIKE = 1 << 11,
1917 VIEW_STATUS_LIKE = 1 << 12,
1918 VIEW_REFRESH = 1 << 13,
1921 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1923 struct position {
1924 unsigned long offset; /* Offset of the window top */
1925 unsigned long col; /* Offset from the window side. */
1926 unsigned long lineno; /* Current line number */
1929 struct view {
1930 const char *name; /* View name */
1931 const char *id; /* Points to either of ref_{head,commit,blob} */
1933 struct view_ops *ops; /* View operations */
1935 char ref[SIZEOF_REF]; /* Hovered commit reference */
1936 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1938 int height, width; /* The width and height of the main window */
1939 WINDOW *win; /* The main window */
1941 /* Navigation */
1942 struct position pos; /* Current position. */
1943 struct position prev_pos; /* Previous position. */
1945 /* Searching */
1946 char grep[SIZEOF_STR]; /* Search string */
1947 regex_t *regex; /* Pre-compiled regexp */
1949 /* If non-NULL, points to the view that opened this view. If this view
1950 * is closed tig will switch back to the parent view. */
1951 struct view *parent;
1952 struct view *prev;
1954 /* Buffering */
1955 size_t lines; /* Total number of lines */
1956 struct line *line; /* Line index */
1957 unsigned int digits; /* Number of digits in the lines member. */
1959 /* Number of lines with custom status, not to be counted in the
1960 * view title. */
1961 unsigned int custom_lines;
1963 /* Drawing */
1964 struct line *curline; /* Line currently being drawn. */
1965 enum line_type curtype; /* Attribute currently used for drawing. */
1966 unsigned long col; /* Column when drawing. */
1967 bool has_scrolled; /* View was scrolled. */
1968 bool force_redraw; /* Whether to force a redraw after reading. */
1970 /* Loading */
1971 const char **argv; /* Shell command arguments. */
1972 const char *dir; /* Directory from which to execute. */
1973 struct io io;
1974 struct io *pipe;
1975 time_t start_time;
1976 time_t update_secs;
1977 struct encoding *encoding;
1978 bool unrefreshable;
1980 /* Private data */
1981 void *private;
1984 enum open_flags {
1985 OPEN_DEFAULT = 0, /* Use default view switching. */
1986 OPEN_STDIN = 1, /* Open in pager mode. */
1987 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1988 OPEN_SPLIT = 4, /* Split current view. */
1989 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1990 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1991 OPEN_PREPARED = 32, /* Open already prepared command. */
1992 OPEN_EXTRA = 64, /* Open extra data from command. */
1994 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1997 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1998 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
2000 struct view_ops {
2001 /* What type of content being displayed. Used in the title bar. */
2002 const char *type;
2003 /* What keymap does this view have */
2004 struct keymap keymap;
2005 /* Flags to control the view behavior. */
2006 enum view_flag flags;
2007 /* Size of private data. */
2008 size_t private_size;
2009 /* Open and reads in all view content. */
2010 bool (*open)(struct view *view, enum open_flags flags);
2011 /* Read one line; updates view->line. */
2012 bool (*read)(struct view *view, char *data);
2013 /* Draw one line; @lineno must be < view->height. */
2014 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
2015 /* Depending on view handle a special requests. */
2016 enum request (*request)(struct view *view, enum request request, struct line *line);
2017 /* Search for regexp in a line. */
2018 bool (*grep)(struct view *view, struct line *line);
2019 /* Select line */
2020 void (*select)(struct view *view, struct line *line);
2021 /* Release resources when reloading the view */
2022 void (*done)(struct view *view);
2025 #define VIEW_OPS(id, name, ref) name##_ops
2026 static struct view_ops VIEW_INFO(VIEW_OPS);
2028 static struct view views[] = {
2029 #define VIEW_DATA(id, name, ref) \
2030 { #name, ref, &name##_ops }
2031 VIEW_INFO(VIEW_DATA)
2034 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2036 #define foreach_view(view, i) \
2037 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2039 #define view_is_displayed(view) \
2040 (view == display[0] || view == display[1])
2042 #define view_has_line(view, line_) \
2043 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2045 static bool
2046 forward_request_to_child(struct view *child, enum request request)
2048 return displayed_views() == 2 && view_is_displayed(child) &&
2049 !strcmp(child->vid, child->id);
2052 static enum request
2053 view_request(struct view *view, enum request request)
2055 if (!view || !view->lines)
2056 return request;
2058 if (request == REQ_ENTER && !opt_focus_child &&
2059 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2060 struct view *child = display[1];
2062 if (forward_request_to_child(child, request)) {
2063 view_request(child, request);
2064 return REQ_NONE;
2068 if (request == REQ_REFRESH && view->unrefreshable) {
2069 report("This view can not be refreshed");
2070 return REQ_NONE;
2073 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2077 * View drawing.
2080 static inline void
2081 set_view_attr(struct view *view, enum line_type type)
2083 if (!view->curline->selected && view->curtype != type) {
2084 (void) wattrset(view->win, get_line_attr(type));
2085 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2086 view->curtype = type;
2090 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2092 static bool
2093 draw_chars(struct view *view, enum line_type type, const char *string,
2094 int max_len, bool use_tilde)
2096 int len = 0;
2097 int col = 0;
2098 int trimmed = FALSE;
2099 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2101 if (max_len <= 0)
2102 return VIEW_MAX_LEN(view) <= 0;
2104 if (opt_iconv_out != ICONV_NONE) {
2105 string = encoding_iconv(opt_iconv_out, string);
2106 if (!string)
2107 return VIEW_MAX_LEN(view) <= 0;
2110 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2112 set_view_attr(view, type);
2113 if (len > 0) {
2114 waddnstr(view->win, string, len);
2116 if (trimmed && use_tilde) {
2117 set_view_attr(view, LINE_DELIMITER);
2118 waddch(view->win, '~');
2119 col++;
2123 view->col += col;
2124 return VIEW_MAX_LEN(view) <= 0;
2127 static bool
2128 draw_space(struct view *view, enum line_type type, int max, int spaces)
2130 static char space[] = " ";
2132 spaces = MIN(max, spaces);
2134 while (spaces > 0) {
2135 int len = MIN(spaces, sizeof(space) - 1);
2137 if (draw_chars(view, type, space, len, FALSE))
2138 return TRUE;
2139 spaces -= len;
2142 return VIEW_MAX_LEN(view) <= 0;
2145 static bool
2146 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2148 static char text[SIZEOF_STR];
2150 do {
2151 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2153 if (draw_chars(view, type, text, max_len, use_tilde))
2154 return TRUE;
2155 string += pos;
2156 } while (*string);
2158 return VIEW_MAX_LEN(view) <= 0;
2161 static bool
2162 draw_text(struct view *view, enum line_type type, const char *string)
2164 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2167 static bool
2168 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2170 if (on) {
2171 int max = MIN(VIEW_MAX_LEN(view), overflow);
2172 int len = strlen(text);
2174 if (draw_text_expanded(view, type, text, max, max < overflow))
2175 return TRUE;
2177 text = len > overflow ? text + overflow : "";
2178 type = LINE_OVERFLOW;
2181 if (*text && draw_text(view, type, text))
2182 return TRUE;
2184 return VIEW_MAX_LEN(view) <= 0;
2187 #define draw_commit_title(view, text, offset) \
2188 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2190 static bool PRINTF_LIKE(3, 4)
2191 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2193 char text[SIZEOF_STR];
2194 int retval;
2196 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2197 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2200 static bool
2201 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2203 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2204 int max = VIEW_MAX_LEN(view);
2205 int i;
2207 if (max < size)
2208 size = max;
2210 set_view_attr(view, type);
2211 /* Using waddch() instead of waddnstr() ensures that
2212 * they'll be rendered correctly for the cursor line. */
2213 for (i = skip; i < size; i++)
2214 waddch(view->win, graphic[i]);
2216 view->col += size;
2217 if (separator) {
2218 if (size < max && skip <= size)
2219 waddch(view->win, ' ');
2220 view->col++;
2223 return VIEW_MAX_LEN(view) <= 0;
2226 enum align {
2227 ALIGN_LEFT,
2228 ALIGN_RIGHT
2231 static bool
2232 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2234 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2235 int col = view->col;
2237 if (!text)
2238 return draw_space(view, type, max, max);
2240 if (align == ALIGN_RIGHT) {
2241 int textlen = strlen(text);
2242 int leftpad = max - textlen - 1;
2244 if (leftpad > 0) {
2245 if (draw_space(view, type, leftpad, leftpad))
2246 return TRUE;
2247 max -= leftpad;
2248 col += leftpad;;
2252 return draw_chars(view, type, text, max - 1, trim)
2253 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2256 static bool
2257 draw_date(struct view *view, struct time *time)
2259 const char *date = mkdate(time, opt_date);
2260 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2262 if (opt_date == DATE_NO)
2263 return FALSE;
2265 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2268 static bool
2269 draw_author(struct view *view, const struct ident *author)
2271 bool trim = author_trim(opt_author_width);
2272 const char *text = mkauthor(author, opt_author_width, opt_author);
2274 if (opt_author == AUTHOR_NO)
2275 return FALSE;
2277 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2280 static bool
2281 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2283 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2286 static bool
2287 draw_id(struct view *view, const char *id)
2289 if (!opt_show_id)
2290 return FALSE;
2292 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2295 static bool
2296 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2298 bool trim = filename && strlen(filename) >= opt_filename_width;
2300 if (opt_filename == FILENAME_NO)
2301 return FALSE;
2303 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2304 return FALSE;
2306 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2309 static bool
2310 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2312 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2314 if (!width || opt_file_size == FILE_SIZE_NO)
2315 return FALSE;
2317 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2320 static bool
2321 draw_mode(struct view *view, mode_t mode)
2323 const char *str = mkmode(mode);
2325 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2328 static bool
2329 draw_lineno(struct view *view, unsigned int lineno)
2331 char number[10];
2332 int digits3 = view->digits < 3 ? 3 : view->digits;
2333 int max = MIN(VIEW_MAX_LEN(view), digits3);
2334 char *text = NULL;
2335 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2337 if (!opt_line_number)
2338 return FALSE;
2340 lineno += view->pos.offset + 1;
2341 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2342 static char fmt[] = "%1ld";
2344 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2345 if (string_format(number, fmt, lineno))
2346 text = number;
2348 if (text)
2349 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2350 else
2351 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2352 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2355 static bool
2356 draw_refs(struct view *view, struct ref_list *refs)
2358 size_t i;
2360 if (!opt_show_refs || !refs)
2361 return FALSE;
2363 for (i = 0; i < refs->size; i++) {
2364 struct ref *ref = refs->refs[i];
2365 enum line_type type = get_line_type_from_ref(ref);
2367 if (draw_formatted(view, type, "[%s]", ref->name))
2368 return TRUE;
2370 if (draw_text(view, LINE_DEFAULT, " "))
2371 return TRUE;
2374 return FALSE;
2377 static bool
2378 draw_view_line(struct view *view, unsigned int lineno)
2380 struct line *line;
2381 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2383 assert(view_is_displayed(view));
2385 if (view->pos.offset + lineno >= view->lines)
2386 return FALSE;
2388 line = &view->line[view->pos.offset + lineno];
2390 wmove(view->win, lineno, 0);
2391 if (line->cleareol)
2392 wclrtoeol(view->win);
2393 view->col = 0;
2394 view->curline = line;
2395 view->curtype = LINE_NONE;
2396 line->selected = FALSE;
2397 line->dirty = line->cleareol = 0;
2399 if (selected) {
2400 set_view_attr(view, LINE_CURSOR);
2401 line->selected = TRUE;
2402 view->ops->select(view, line);
2405 return view->ops->draw(view, line, lineno);
2408 static void
2409 redraw_view_dirty(struct view *view)
2411 bool dirty = FALSE;
2412 int lineno;
2414 for (lineno = 0; lineno < view->height; lineno++) {
2415 if (view->pos.offset + lineno >= view->lines)
2416 break;
2417 if (!view->line[view->pos.offset + lineno].dirty)
2418 continue;
2419 dirty = TRUE;
2420 if (!draw_view_line(view, lineno))
2421 break;
2424 if (!dirty)
2425 return;
2426 wnoutrefresh(view->win);
2429 static void
2430 redraw_view_from(struct view *view, int lineno)
2432 assert(0 <= lineno && lineno < view->height);
2434 for (; lineno < view->height; lineno++) {
2435 if (!draw_view_line(view, lineno))
2436 break;
2439 wnoutrefresh(view->win);
2442 static void
2443 redraw_view(struct view *view)
2445 werase(view->win);
2446 redraw_view_from(view, 0);
2450 static void
2451 update_view_title(struct view *view)
2453 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2454 struct line *line = &view->line[view->pos.lineno];
2455 unsigned int view_lines, lines;
2457 assert(view_is_displayed(view));
2459 if (view == display[current_view])
2460 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2461 else
2462 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2464 werase(window);
2465 mvwprintw(window, 0, 0, "[%s]", view->name);
2467 if (*view->ref) {
2468 wprintw(window, " %s", view->ref);
2471 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2472 line->lineno) {
2473 wprintw(window, " - %s %d of %zd",
2474 view->ops->type,
2475 line->lineno,
2476 view->lines - view->custom_lines);
2479 if (view->pipe) {
2480 time_t secs = time(NULL) - view->start_time;
2482 /* Three git seconds are a long time ... */
2483 if (secs > 2)
2484 wprintw(window, " loading %lds", secs);
2487 view_lines = view->pos.offset + view->height;
2488 lines = view->lines ? MIN(view_lines, view->lines) * 100 / view->lines : 0;
2489 mvwprintw(window, 0, view->width - count_digits(lines) - 1, "%d%%", lines);
2491 wnoutrefresh(window);
2494 static int
2495 apply_step(double step, int value)
2497 if (step >= 1)
2498 return (int) step;
2499 value *= step + 0.01;
2500 return value ? value : 1;
2503 static void
2504 apply_horizontal_split(struct view *base, struct view *view)
2506 view->width = base->width;
2507 view->height = apply_step(opt_scale_split_view, base->height);
2508 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2509 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2510 base->height -= view->height;
2513 static void
2514 apply_vertical_split(struct view *base, struct view *view)
2516 view->height = base->height;
2517 view->width = apply_step(opt_scale_vsplit_view, base->width);
2518 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2519 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2520 base->width -= view->width;
2523 static void
2524 redraw_display_separator(bool clear)
2526 if (displayed_views() > 1 && vertical_split_is_enabled()) {
2527 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2529 if (clear)
2530 wclear(display_sep);
2531 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2532 wnoutrefresh(display_sep);
2536 static void
2537 resize_display(void)
2539 int x, y, i;
2540 struct view *base = display[0];
2541 struct view *view = display[1] ? display[1] : display[0];
2542 bool vsplit;
2544 /* Setup window dimensions */
2546 getmaxyx(stdscr, base->height, base->width);
2547 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2548 string_format(opt_env_lines, "LINES=%d", base->height);
2550 /* Make room for the status window. */
2551 base->height -= 1;
2553 vsplit = vertical_split_is_enabled();
2555 if (view != base) {
2556 if (vsplit) {
2557 apply_vertical_split(base, view);
2559 /* Make room for the separator bar. */
2560 view->width -= 1;
2561 } else {
2562 apply_horizontal_split(base, view);
2565 /* Make room for the title bar. */
2566 view->height -= 1;
2569 /* Make room for the title bar. */
2570 base->height -= 1;
2572 x = y = 0;
2574 foreach_displayed_view (view, i) {
2575 if (!display_win[i]) {
2576 display_win[i] = newwin(view->height, view->width, y, x);
2577 if (!display_win[i])
2578 die("Failed to create %s view", view->name);
2580 scrollok(display_win[i], FALSE);
2582 display_title[i] = newwin(1, view->width, y + view->height, x);
2583 if (!display_title[i])
2584 die("Failed to create title window");
2586 } else {
2587 wresize(display_win[i], view->height, view->width);
2588 mvwin(display_win[i], y, x);
2589 wresize(display_title[i], 1, view->width);
2590 mvwin(display_title[i], y + view->height, x);
2593 if (i > 0 && vsplit) {
2594 if (!display_sep) {
2595 display_sep = newwin(view->height, 1, 0, x - 1);
2596 if (!display_sep)
2597 die("Failed to create separator window");
2599 } else {
2600 wresize(display_sep, view->height, 1);
2601 mvwin(display_sep, 0, x - 1);
2605 view->win = display_win[i];
2607 if (vsplit)
2608 x += view->width + 1;
2609 else
2610 y += view->height + 1;
2613 redraw_display_separator(FALSE);
2616 static void
2617 redraw_display(bool clear)
2619 struct view *view;
2620 int i;
2622 foreach_displayed_view (view, i) {
2623 if (clear)
2624 wclear(view->win);
2625 redraw_view(view);
2626 update_view_title(view);
2629 redraw_display_separator(clear);
2633 * Option management
2636 #define VIEW_FLAG_RESET_DISPLAY ((enum view_flag) -1)
2638 #define TOGGLE_MENU_INFO(_) \
2639 _(LINENO, '.', "line numbers", &opt_line_number, NULL, VIEW_NO_FLAGS), \
2640 _(DATE, 'D', "dates", &opt_date, date_map, VIEW_NO_FLAGS), \
2641 _(AUTHOR, 'A', "author", &opt_author, author_map, VIEW_NO_FLAGS), \
2642 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, VIEW_NO_FLAGS), \
2643 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, VIEW_LOG_LIKE), \
2644 _(FILENAME, '#', "file names", &opt_filename, filename_map, VIEW_NO_FLAGS), \
2645 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, VIEW_NO_FLAGS), \
2646 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, VIEW_DIFF_LIKE), \
2647 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, VIEW_LOG_LIKE), \
2648 _(REFS, 'F', "reference display", &opt_show_refs, NULL, VIEW_NO_FLAGS), \
2649 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, VIEW_NO_FLAGS), \
2650 _(ID, 'X', "commit ID display", &opt_show_id, NULL, VIEW_NO_FLAGS), \
2651 _(FILES, '%', "file filtering", &opt_file_filter, NULL, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2652 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, VIEW_NO_FLAGS), \
2653 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, VIEW_STATUS_LIKE), \
2654 _(VERTICAL_SPLIT, '|', "view split", &opt_vertical_split, vertical_split_map, VIEW_FLAG_RESET_DISPLAY), \
2656 static enum view_flag
2657 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2659 const struct {
2660 enum request request;
2661 const struct enum_map *map;
2662 enum view_flag reload_flags;
2663 } data[] = {
2664 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, vflags) { REQ_TOGGLE_ ## id, map, vflags }
2665 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2667 const struct menu_item menu[] = {
2668 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, vflags) { key, help, value }
2669 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2670 { 0 }
2672 int i = 0;
2674 if (request == REQ_OPTIONS) {
2675 if (!prompt_menu("Toggle option", menu, &i))
2676 return VIEW_NO_FLAGS;
2677 } else {
2678 while (i < ARRAY_SIZE(data) && data[i].request != request)
2679 i++;
2680 if (i >= ARRAY_SIZE(data))
2681 die("Invalid request (%d)", request);
2684 if (data[i].map != NULL) {
2685 unsigned int *opt = menu[i].data;
2687 *opt = (*opt + 1) % data[i].map->size;
2688 if (data[i].map == ignore_space_map) {
2689 update_ignore_space_arg();
2690 string_format_size(msg, SIZEOF_STR,
2691 "Ignoring %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2693 } else if (data[i].map == commit_order_map) {
2694 update_commit_order_arg();
2695 string_format_size(msg, SIZEOF_STR,
2696 "Using %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2698 } else {
2699 string_format_size(msg, SIZEOF_STR,
2700 "Displaying %s %s", enum_name(data[i].map->entries[*opt]), menu[i].text);
2703 } else {
2704 bool *option = menu[i].data;
2706 *option = !*option;
2707 string_format_size(msg, SIZEOF_STR,
2708 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2711 return data[i].reload_flags;
2716 * Navigation
2719 static bool
2720 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2722 if (lineno >= view->lines)
2723 lineno = view->lines > 0 ? view->lines - 1 : 0;
2725 if (offset > lineno || offset + view->height <= lineno) {
2726 unsigned long half = view->height / 2;
2728 if (lineno > half)
2729 offset = lineno - half;
2730 else
2731 offset = 0;
2734 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2735 view->pos.offset = offset;
2736 view->pos.lineno = lineno;
2737 return TRUE;
2740 return FALSE;
2743 /* Scrolling backend */
2744 static void
2745 do_scroll_view(struct view *view, int lines)
2747 bool redraw_current_line = FALSE;
2749 /* The rendering expects the new offset. */
2750 view->pos.offset += lines;
2752 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2753 assert(lines);
2755 /* Move current line into the view. */
2756 if (view->pos.lineno < view->pos.offset) {
2757 view->pos.lineno = view->pos.offset;
2758 redraw_current_line = TRUE;
2759 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2760 view->pos.lineno = view->pos.offset + view->height - 1;
2761 redraw_current_line = TRUE;
2764 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2766 /* Redraw the whole screen if scrolling is pointless. */
2767 if (view->height < ABS(lines)) {
2768 redraw_view(view);
2770 } else {
2771 int line = lines > 0 ? view->height - lines : 0;
2772 int end = line + ABS(lines);
2774 scrollok(view->win, TRUE);
2775 wscrl(view->win, lines);
2776 scrollok(view->win, FALSE);
2778 while (line < end && draw_view_line(view, line))
2779 line++;
2781 if (redraw_current_line)
2782 draw_view_line(view, view->pos.lineno - view->pos.offset);
2783 wnoutrefresh(view->win);
2786 view->has_scrolled = TRUE;
2787 report_clear();
2790 /* Scroll frontend */
2791 static void
2792 scroll_view(struct view *view, enum request request)
2794 int lines = 1;
2796 assert(view_is_displayed(view));
2798 if (request == REQ_SCROLL_WHEEL_DOWN || request == REQ_SCROLL_WHEEL_UP)
2799 lines = opt_scroll_wheel_lines;
2801 switch (request) {
2802 case REQ_SCROLL_FIRST_COL:
2803 view->pos.col = 0;
2804 redraw_view_from(view, 0);
2805 report_clear();
2806 return;
2807 case REQ_SCROLL_LEFT:
2808 if (view->pos.col == 0) {
2809 report("Cannot scroll beyond the first column");
2810 return;
2812 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2813 view->pos.col = 0;
2814 else
2815 view->pos.col -= apply_step(opt_hscroll, view->width);
2816 redraw_view_from(view, 0);
2817 report_clear();
2818 return;
2819 case REQ_SCROLL_RIGHT:
2820 view->pos.col += apply_step(opt_hscroll, view->width);
2821 redraw_view(view);
2822 report_clear();
2823 return;
2824 case REQ_SCROLL_PAGE_DOWN:
2825 lines = view->height;
2826 case REQ_SCROLL_WHEEL_DOWN:
2827 case REQ_SCROLL_LINE_DOWN:
2828 if (view->pos.offset + lines > view->lines)
2829 lines = view->lines - view->pos.offset;
2831 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2832 report("Cannot scroll beyond the last line");
2833 return;
2835 break;
2837 case REQ_SCROLL_PAGE_UP:
2838 lines = view->height;
2839 case REQ_SCROLL_LINE_UP:
2840 case REQ_SCROLL_WHEEL_UP:
2841 if (lines > view->pos.offset)
2842 lines = view->pos.offset;
2844 if (lines == 0) {
2845 report("Cannot scroll beyond the first line");
2846 return;
2849 lines = -lines;
2850 break;
2852 default:
2853 die("request %d not handled in switch", request);
2856 do_scroll_view(view, lines);
2859 /* Cursor moving */
2860 static void
2861 move_view(struct view *view, enum request request)
2863 int scroll_steps = 0;
2864 int steps;
2866 switch (request) {
2867 case REQ_MOVE_FIRST_LINE:
2868 steps = -view->pos.lineno;
2869 break;
2871 case REQ_MOVE_LAST_LINE:
2872 steps = view->lines - view->pos.lineno - 1;
2873 break;
2875 case REQ_MOVE_PAGE_UP:
2876 steps = view->height > view->pos.lineno
2877 ? -view->pos.lineno : -view->height;
2878 break;
2880 case REQ_MOVE_PAGE_DOWN:
2881 steps = view->pos.lineno + view->height >= view->lines
2882 ? view->lines - view->pos.lineno - 1 : view->height;
2883 break;
2885 case REQ_MOVE_UP:
2886 case REQ_PREVIOUS:
2887 steps = -1;
2888 break;
2890 case REQ_MOVE_DOWN:
2891 case REQ_NEXT:
2892 steps = 1;
2893 break;
2895 default:
2896 die("request %d not handled in switch", request);
2899 if (steps <= 0 && view->pos.lineno == 0) {
2900 report("Cannot move beyond the first line");
2901 return;
2903 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2904 report("Cannot move beyond the last line");
2905 return;
2908 /* Move the current line */
2909 view->pos.lineno += steps;
2910 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2912 /* Check whether the view needs to be scrolled */
2913 if (view->pos.lineno < view->pos.offset ||
2914 view->pos.lineno >= view->pos.offset + view->height) {
2915 scroll_steps = steps;
2916 if (steps < 0 && -steps > view->pos.offset) {
2917 scroll_steps = -view->pos.offset;
2919 } else if (steps > 0) {
2920 if (view->pos.lineno == view->lines - 1 &&
2921 view->lines > view->height) {
2922 scroll_steps = view->lines - view->pos.offset - 1;
2923 if (scroll_steps >= view->height)
2924 scroll_steps -= view->height - 1;
2929 if (!view_is_displayed(view)) {
2930 view->pos.offset += scroll_steps;
2931 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2932 view->ops->select(view, &view->line[view->pos.lineno]);
2933 return;
2936 /* Repaint the old "current" line if we be scrolling */
2937 if (ABS(steps) < view->height)
2938 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2940 if (scroll_steps) {
2941 do_scroll_view(view, scroll_steps);
2942 return;
2945 /* Draw the current line */
2946 draw_view_line(view, view->pos.lineno - view->pos.offset);
2948 wnoutrefresh(view->win);
2949 report_clear();
2954 * Searching
2957 static void search_view(struct view *view, enum request request);
2959 static bool
2960 grep_text(struct view *view, const char *text[])
2962 regmatch_t pmatch;
2963 size_t i;
2965 for (i = 0; text[i]; i++)
2966 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2967 return TRUE;
2968 return FALSE;
2971 static void
2972 select_view_line(struct view *view, unsigned long lineno)
2974 struct position old = view->pos;
2976 if (goto_view_line(view, view->pos.offset, lineno)) {
2977 if (view_is_displayed(view)) {
2978 if (old.offset != view->pos.offset) {
2979 redraw_view(view);
2980 } else {
2981 draw_view_line(view, old.lineno - view->pos.offset);
2982 draw_view_line(view, view->pos.lineno - view->pos.offset);
2983 wnoutrefresh(view->win);
2985 } else {
2986 view->ops->select(view, &view->line[view->pos.lineno]);
2991 static void
2992 find_next(struct view *view, enum request request)
2994 unsigned long lineno = view->pos.lineno;
2995 int direction;
2997 if (!*view->grep) {
2998 if (!*opt_search)
2999 report("No previous search");
3000 else
3001 search_view(view, request);
3002 return;
3005 switch (request) {
3006 case REQ_SEARCH:
3007 case REQ_FIND_NEXT:
3008 direction = 1;
3009 break;
3011 case REQ_SEARCH_BACK:
3012 case REQ_FIND_PREV:
3013 direction = -1;
3014 break;
3016 default:
3017 return;
3020 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
3021 lineno += direction;
3023 /* Note, lineno is unsigned long so will wrap around in which case it
3024 * will become bigger than view->lines. */
3025 for (; lineno < view->lines; lineno += direction) {
3026 if (view->ops->grep(view, &view->line[lineno])) {
3027 select_view_line(view, lineno);
3028 report("Line %ld matches '%s'", lineno + 1, view->grep);
3029 return;
3033 report("No match found for '%s'", view->grep);
3036 static void
3037 search_view(struct view *view, enum request request)
3039 int regex_err;
3040 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3042 if (view->regex) {
3043 regfree(view->regex);
3044 *view->grep = 0;
3045 } else {
3046 view->regex = calloc(1, sizeof(*view->regex));
3047 if (!view->regex)
3048 return;
3051 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3052 if (regex_err != 0) {
3053 char buf[SIZEOF_STR] = "unknown error";
3055 regerror(regex_err, view->regex, buf, sizeof(buf));
3056 report("Search failed: %s", buf);
3057 return;
3060 string_copy(view->grep, opt_search);
3062 find_next(view, request);
3066 * Incremental updating
3069 static inline bool
3070 check_position(struct position *pos)
3072 return pos->lineno || pos->col || pos->offset;
3075 static inline void
3076 clear_position(struct position *pos)
3078 memset(pos, 0, sizeof(*pos));
3081 static void
3082 reset_view(struct view *view)
3084 int i;
3086 if (view->ops->done)
3087 view->ops->done(view);
3089 for (i = 0; i < view->lines; i++)
3090 free(view->line[i].data);
3091 free(view->line);
3093 view->prev_pos = view->pos;
3094 clear_position(&view->pos);
3096 view->line = NULL;
3097 view->lines = 0;
3098 view->vid[0] = 0;
3099 view->custom_lines = 0;
3100 view->update_secs = 0;
3103 struct format_context {
3104 struct view *view;
3105 char buf[SIZEOF_STR];
3106 size_t bufpos;
3107 bool file_filter;
3110 static bool
3111 format_expand_arg(struct format_context *format, const char *name, const char *end)
3113 static struct {
3114 const char *name;
3115 size_t namelen;
3116 const char *value;
3117 const char *value_if_empty;
3118 } vars[] = {
3119 #define FORMAT_VAR(name, value, value_if_empty) \
3120 { name, STRING_SIZE(name), value, value_if_empty }
3121 FORMAT_VAR("%(directory)", opt_path, "."),
3122 FORMAT_VAR("%(file)", opt_file, ""),
3123 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3124 FORMAT_VAR("%(head)", ref_head, ""),
3125 FORMAT_VAR("%(commit)", ref_commit, ""),
3126 FORMAT_VAR("%(blob)", ref_blob, ""),
3127 FORMAT_VAR("%(branch)", ref_branch, ""),
3128 FORMAT_VAR("%(stash)", ref_stash, ""),
3130 int i;
3132 if (!prefixcmp(name, "%(prompt")) {
3133 const char *prompt = "Command argument: ";
3134 char msgbuf[SIZEOF_STR];
3135 const char *value;
3136 const char *msgstart = name + STRING_SIZE("%(prompt");
3137 int msglen = end - msgstart - 1;
3139 if (end && msglen > 0 && string_format(msgbuf, "%.*s", msglen, msgstart)) {
3140 const char *msg = msgbuf;
3142 while (isspace(*msg))
3143 msg++;
3144 if (*msg)
3145 prompt = msg;
3148 value = read_prompt(prompt);
3149 if (value == NULL)
3150 return FALSE;
3151 return string_format_from(format->buf, &format->bufpos, "%s", value);
3154 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3155 const char *value;
3157 if (strncmp(name, vars[i].name, vars[i].namelen))
3158 continue;
3160 if (vars[i].value == opt_file && !format->file_filter)
3161 return TRUE;
3163 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3164 if (!*value)
3165 return TRUE;
3167 return string_format_from(format->buf, &format->bufpos, "%s", value);
3170 report("Unknown replacement: `%s`", name);
3171 return FALSE;
3174 static bool
3175 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3177 memset(format->buf, 0, sizeof(format->buf));
3178 format->bufpos = 0;
3180 while (arg) {
3181 char *var = strstr(arg, "%(");
3182 int len = var ? var - arg : strlen(arg);
3183 char *next = var ? strchr(var, ')') + 1 : NULL;
3185 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3186 return FALSE;
3188 if (var && !format_expand_arg(format, var, next))
3189 return FALSE;
3191 arg = next;
3194 return argv_append(dst_argv, format->buf);
3197 static bool
3198 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3200 int argc;
3202 if (!src_argv)
3203 return TRUE;
3205 for (argc = 0; src_argv[argc]; argc++)
3206 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3207 return FALSE;
3209 return src_argv[argc] == NULL;
3212 static bool
3213 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3215 struct format_context format = { view, "", 0, file_filter };
3216 int argc;
3218 argv_free(*dst_argv);
3220 for (argc = 0; src_argv[argc]; argc++) {
3221 const char *arg = src_argv[argc];
3223 if (!strcmp(arg, "%(fileargs)")) {
3224 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3225 break;
3227 } else if (!strcmp(arg, "%(diffargs)")) {
3228 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3229 break;
3231 } else if (!strcmp(arg, "%(blameargs)")) {
3232 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3233 break;
3235 } else if (!strcmp(arg, "%(cmdlineargs)")) {
3236 if (!format_append_argv(&format, dst_argv, opt_cmdline_argv))
3237 break;
3239 } else if (!strcmp(arg, "%(revargs)") ||
3240 (first && !strcmp(arg, "%(commit)"))) {
3241 if (!argv_append_array(dst_argv, opt_rev_argv))
3242 break;
3244 } else if (!format_append_arg(&format, dst_argv, arg)) {
3245 break;
3249 return src_argv[argc] == NULL;
3252 static bool
3253 restore_view_position(struct view *view)
3255 /* A view without a previous view is the first view */
3256 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3257 select_view_line(view, opt_lineno - 1);
3258 opt_lineno = 0;
3261 /* Ensure that the view position is in a valid state. */
3262 if (!check_position(&view->prev_pos) ||
3263 (view->pipe && view->lines <= view->prev_pos.lineno))
3264 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3266 /* Changing the view position cancels the restoring. */
3267 /* FIXME: Changing back to the first line is not detected. */
3268 if (check_position(&view->pos)) {
3269 clear_position(&view->prev_pos);
3270 return FALSE;
3273 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3274 view_is_displayed(view))
3275 werase(view->win);
3277 view->pos.col = view->prev_pos.col;
3278 clear_position(&view->prev_pos);
3280 return TRUE;
3283 static void
3284 end_update(struct view *view, bool force)
3286 if (!view->pipe)
3287 return;
3288 while (!view->ops->read(view, NULL))
3289 if (!force)
3290 return;
3291 if (force)
3292 io_kill(view->pipe);
3293 io_done(view->pipe);
3294 view->pipe = NULL;
3297 static void
3298 setup_update(struct view *view, const char *vid)
3300 reset_view(view);
3301 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3302 string_ncopy(view->vid, vid, strlen(vid));
3303 view->pipe = &view->io;
3304 view->start_time = time(NULL);
3307 static bool
3308 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3310 bool extra = !!(flags & (OPEN_EXTRA));
3311 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3312 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3313 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3314 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3316 if ((!reload && !strcmp(view->vid, view->id)) ||
3317 ((flags & OPEN_REFRESH) && view->unrefreshable))
3318 return TRUE;
3320 if (view->pipe) {
3321 if (extra)
3322 io_done(view->pipe);
3323 else
3324 end_update(view, TRUE);
3327 view->unrefreshable = open_in_pager_mode(flags);
3329 if (!refresh && argv) {
3330 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3332 view->dir = dir;
3333 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3334 report("Failed to format %s arguments", view->name);
3335 return FALSE;
3338 /* Put the current ref_* value to the view title ref
3339 * member. This is needed by the blob view. Most other
3340 * views sets it automatically after loading because the
3341 * first line is a commit line. */
3342 string_copy_rev(view->ref, view->id);
3345 if (view->argv && view->argv[0] &&
3346 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3347 report("Failed to open %s view", view->name);
3348 return FALSE;
3351 if (open_from_stdin(flags)) {
3352 if (!io_open(&view->io, "%s", ""))
3353 die("Failed to open stdin");
3356 if (!extra)
3357 setup_update(view, view->id);
3359 return TRUE;
3362 static bool
3363 update_view(struct view *view)
3365 char *line;
3366 /* Clear the view and redraw everything since the tree sorting
3367 * might have rearranged things. */
3368 bool redraw = view->lines == 0;
3369 bool can_read = TRUE;
3370 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3372 if (!view->pipe)
3373 return TRUE;
3375 if (!io_can_read(view->pipe, FALSE)) {
3376 if (view->lines == 0 && view_is_displayed(view)) {
3377 time_t secs = time(NULL) - view->start_time;
3379 if (secs > 1 && secs > view->update_secs) {
3380 if (view->update_secs == 0)
3381 redraw_view(view);
3382 update_view_title(view);
3383 view->update_secs = secs;
3386 return TRUE;
3389 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3390 if (encoding) {
3391 line = encoding_convert(encoding, line);
3394 if (!view->ops->read(view, line)) {
3395 report("Allocation failure");
3396 end_update(view, TRUE);
3397 return FALSE;
3402 int digits = count_digits(view->lines);
3404 /* Keep the displayed view in sync with line number scaling. */
3405 if (digits != view->digits) {
3406 view->digits = digits;
3407 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3408 redraw = TRUE;
3412 if (io_error(view->pipe)) {
3413 report("Failed to read: %s", io_strerror(view->pipe));
3414 end_update(view, TRUE);
3416 } else if (io_eof(view->pipe)) {
3417 end_update(view, FALSE);
3420 if (restore_view_position(view))
3421 redraw = TRUE;
3423 if (!view_is_displayed(view))
3424 return TRUE;
3426 if (redraw || view->force_redraw)
3427 redraw_view_from(view, 0);
3428 else
3429 redraw_view_dirty(view);
3430 view->force_redraw = FALSE;
3432 /* Update the title _after_ the redraw so that if the redraw picks up a
3433 * commit reference in view->ref it'll be available here. */
3434 update_view_title(view);
3435 return TRUE;
3438 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3440 static struct line *
3441 add_line_at(struct view *view, unsigned long pos, const void *data, enum line_type type, size_t data_size, bool custom)
3443 struct line *line;
3444 unsigned long lineno;
3446 if (!realloc_lines(&view->line, view->lines, 1))
3447 return NULL;
3449 if (data_size) {
3450 void *alloc_data = calloc(1, data_size);
3452 if (!alloc_data)
3453 return NULL;
3455 if (data)
3456 memcpy(alloc_data, data, data_size);
3457 data = alloc_data;
3460 if (pos < view->lines) {
3461 view->lines++;
3462 line = view->line + pos;
3463 lineno = line->lineno;
3465 memmove(line + 1, line, (view->lines - pos) * sizeof(*view->line));
3466 while (pos < view->lines) {
3467 view->line[pos].lineno++;
3468 view->line[pos++].dirty = 1;
3470 } else {
3471 line = &view->line[view->lines++];
3472 lineno = view->lines - view->custom_lines;
3475 memset(line, 0, sizeof(*line));
3476 line->type = type;
3477 line->data = (void *) data;
3478 line->dirty = 1;
3480 if (custom)
3481 view->custom_lines++;
3482 else
3483 line->lineno = lineno;
3485 return line;
3488 static struct line *
3489 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3491 return add_line_at(view, view->lines, data, type, data_size, custom);
3494 static struct line *
3495 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3497 struct line *line = add_line(view, NULL, type, data_size, custom);
3499 if (line)
3500 *ptr = line->data;
3501 return line;
3504 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3505 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3507 static struct line *
3508 add_line_nodata(struct view *view, enum line_type type)
3510 return add_line(view, NULL, type, 0, FALSE);
3513 static struct line *
3514 add_line_text(struct view *view, const char *text, enum line_type type)
3516 return add_line(view, text, type, strlen(text) + 1, FALSE);
3519 static struct line * PRINTF_LIKE(3, 4)
3520 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3522 char buf[SIZEOF_STR];
3523 int retval;
3525 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3526 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3530 * View opening
3533 static void
3534 split_view(struct view *prev, struct view *view)
3536 display[1] = view;
3537 current_view = opt_focus_child ? 1 : 0;
3538 view->parent = prev;
3539 resize_display();
3541 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3542 /* Take the title line into account. */
3543 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3545 /* Scroll the view that was split if the current line is
3546 * outside the new limited view. */
3547 do_scroll_view(prev, lines);
3550 if (view != prev && view_is_displayed(prev)) {
3551 /* "Blur" the previous view. */
3552 update_view_title(prev);
3556 static void
3557 maximize_view(struct view *view, bool redraw)
3559 memset(display, 0, sizeof(display));
3560 current_view = 0;
3561 display[current_view] = view;
3562 resize_display();
3563 if (redraw) {
3564 redraw_display(FALSE);
3565 report_clear();
3569 static void
3570 load_view(struct view *view, struct view *prev, enum open_flags flags)
3572 if (view->pipe)
3573 end_update(view, TRUE);
3574 if (view->ops->private_size) {
3575 if (!view->private)
3576 view->private = calloc(1, view->ops->private_size);
3577 else
3578 memset(view->private, 0, view->ops->private_size);
3581 /* When prev == view it means this is the first loaded view. */
3582 if (prev && view != prev) {
3583 view->prev = prev;
3586 if (!view->ops->open(view, flags))
3587 return;
3589 if (prev) {
3590 bool split = !!(flags & OPEN_SPLIT);
3592 if (split) {
3593 split_view(prev, view);
3594 } else {
3595 maximize_view(view, FALSE);
3599 restore_view_position(view);
3601 if (view->pipe && view->lines == 0) {
3602 /* Clear the old view and let the incremental updating refill
3603 * the screen. */
3604 werase(view->win);
3605 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3606 clear_position(&view->prev_pos);
3607 report_clear();
3608 } else if (view_is_displayed(view)) {
3609 redraw_view(view);
3610 report_clear();
3614 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3615 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3617 static void
3618 open_view(struct view *prev, enum request request, enum open_flags flags)
3620 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3621 struct view *view = VIEW(request);
3622 int nviews = displayed_views();
3624 assert(flags ^ OPEN_REFRESH);
3626 if (view == prev && nviews == 1 && !reload) {
3627 report("Already in %s view", view->name);
3628 return;
3631 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3632 report("The %s view is disabled in pager view", view->name);
3633 return;
3636 load_view(view, prev ? prev : view, flags);
3639 static void
3640 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3642 enum request request = view - views + REQ_OFFSET + 1;
3644 if (view->pipe)
3645 end_update(view, TRUE);
3646 view->dir = dir;
3648 if (!argv_copy(&view->argv, argv)) {
3649 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3650 } else {
3651 open_view(prev, request, flags | OPEN_PREPARED);
3655 static bool
3656 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3658 bool ok;
3660 def_prog_mode(); /* save current tty modes */
3661 endwin(); /* restore original tty modes */
3662 ok = io_run_fg(argv, dir);
3663 if (confirm) {
3664 if (!ok && *notice)
3665 fprintf(stderr, "%s", notice);
3666 fprintf(stderr, "Press Enter to continue");
3667 getc(opt_tty);
3669 reset_prog_mode();
3670 redraw_display(TRUE);
3671 return ok;
3674 static void
3675 open_mergetool(const char *file)
3677 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3679 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3682 #define EDITOR_LINENO_MSG \
3683 "*** Your editor reported an error while opening the file.\n" \
3684 "*** This is probably because it doesn't support the line\n" \
3685 "*** number argument added automatically. The line number\n" \
3686 "*** has been disabled for now. You can permanently disable\n" \
3687 "*** it by adding the following line to ~/.tigrc\n" \
3688 "*** set editor-line-number = no\n"
3690 static void
3691 open_editor(const char *file, unsigned int lineno)
3693 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3694 char editor_cmd[SIZEOF_STR];
3695 char lineno_cmd[SIZEOF_STR];
3696 const char *editor;
3697 int argc = 0;
3699 editor = getenv("GIT_EDITOR");
3700 if (!editor && *opt_editor)
3701 editor = opt_editor;
3702 if (!editor)
3703 editor = getenv("VISUAL");
3704 if (!editor)
3705 editor = getenv("EDITOR");
3706 if (!editor)
3707 editor = "vi";
3709 string_ncopy(editor_cmd, editor, strlen(editor));
3710 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3711 report("Failed to read editor command");
3712 return;
3715 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3716 editor_argv[argc++] = lineno_cmd;
3717 editor_argv[argc] = file;
3718 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3719 opt_editor_lineno = FALSE;
3722 static enum request run_prompt_command(struct view *view, char *cmd);
3724 static enum request
3725 open_run_request(struct view *view, enum request request)
3727 struct run_request *req = get_run_request(request);
3728 const char **argv = NULL;
3729 bool confirmed = FALSE;
3731 request = REQ_NONE;
3733 if (!req) {
3734 report("Unknown run request");
3735 return request;
3738 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3739 if (req->internal) {
3740 char cmd[SIZEOF_STR];
3742 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3743 request = run_prompt_command(view, cmd);
3746 else {
3747 confirmed = !req->confirm;
3749 if (req->confirm) {
3750 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3751 const char *and_exit = req->exit ? " and exit" : "";
3753 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3754 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3755 prompt_yesno(prompt)) {
3756 confirmed = TRUE;
3760 if (confirmed && argv_remove_quotes(argv)) {
3761 if (req->silent)
3762 io_run_bg(argv);
3763 else
3764 open_external_viewer(argv, NULL, !req->exit, "");
3769 if (argv)
3770 argv_free(argv);
3771 free(argv);
3773 if (request == REQ_NONE) {
3774 if (req->confirm && !confirmed)
3775 request = REQ_NONE;
3777 else if (req->exit)
3778 request = REQ_QUIT;
3780 else if (view_has_flags(view, VIEW_REFRESH) && !view->unrefreshable)
3781 request = REQ_REFRESH;
3783 return request;
3787 * User request switch noodle
3790 static int
3791 view_driver(struct view *view, enum request request)
3793 int i;
3795 if (request == REQ_NONE)
3796 return TRUE;
3798 if (request >= REQ_RUN_REQUESTS) {
3799 request = open_run_request(view, request);
3801 // exit quickly rather than going through view_request and back
3802 if (request == REQ_QUIT)
3803 return FALSE;
3806 request = view_request(view, request);
3807 if (request == REQ_NONE)
3808 return TRUE;
3810 switch (request) {
3811 case REQ_MOVE_UP:
3812 case REQ_MOVE_DOWN:
3813 case REQ_MOVE_PAGE_UP:
3814 case REQ_MOVE_PAGE_DOWN:
3815 case REQ_MOVE_FIRST_LINE:
3816 case REQ_MOVE_LAST_LINE:
3817 move_view(view, request);
3818 break;
3820 case REQ_SCROLL_FIRST_COL:
3821 case REQ_SCROLL_LEFT:
3822 case REQ_SCROLL_RIGHT:
3823 case REQ_SCROLL_LINE_DOWN:
3824 case REQ_SCROLL_LINE_UP:
3825 case REQ_SCROLL_PAGE_DOWN:
3826 case REQ_SCROLL_PAGE_UP:
3827 case REQ_SCROLL_WHEEL_DOWN:
3828 case REQ_SCROLL_WHEEL_UP:
3829 scroll_view(view, request);
3830 break;
3832 case REQ_VIEW_MAIN:
3833 case REQ_VIEW_DIFF:
3834 case REQ_VIEW_LOG:
3835 case REQ_VIEW_TREE:
3836 case REQ_VIEW_HELP:
3837 case REQ_VIEW_BRANCH:
3838 case REQ_VIEW_BLAME:
3839 case REQ_VIEW_BLOB:
3840 case REQ_VIEW_STATUS:
3841 case REQ_VIEW_STAGE:
3842 case REQ_VIEW_PAGER:
3843 case REQ_VIEW_STASH:
3844 open_view(view, request, OPEN_DEFAULT);
3845 break;
3847 case REQ_NEXT:
3848 case REQ_PREVIOUS:
3849 if (view->parent) {
3850 int line;
3852 view = view->parent;
3853 line = view->pos.lineno;
3854 view_request(view, request);
3855 move_view(view, request);
3856 if (view_is_displayed(view))
3857 update_view_title(view);
3858 if (line != view->pos.lineno)
3859 view_request(view, REQ_ENTER);
3860 } else {
3861 move_view(view, request);
3863 break;
3865 case REQ_VIEW_NEXT:
3867 int nviews = displayed_views();
3868 int next_view = (current_view + 1) % nviews;
3870 if (next_view == current_view) {
3871 report("Only one view is displayed");
3872 break;
3875 current_view = next_view;
3876 /* Blur out the title of the previous view. */
3877 update_view_title(view);
3878 report_clear();
3879 break;
3881 case REQ_REFRESH:
3882 report("Refreshing is not supported by the %s view", view->name);
3883 break;
3885 case REQ_PARENT:
3886 report("Moving to parent is not supported by the the %s view", view->name);
3887 break;
3889 case REQ_BACK:
3890 report("Going back is not supported for by %s view", view->name);
3891 break;
3893 case REQ_MAXIMIZE:
3894 if (displayed_views() == 2)
3895 maximize_view(view, TRUE);
3896 break;
3898 case REQ_OPTIONS:
3899 case REQ_TOGGLE_LINENO:
3900 case REQ_TOGGLE_DATE:
3901 case REQ_TOGGLE_AUTHOR:
3902 case REQ_TOGGLE_FILENAME:
3903 case REQ_TOGGLE_GRAPHIC:
3904 case REQ_TOGGLE_REV_GRAPH:
3905 case REQ_TOGGLE_REFS:
3906 case REQ_TOGGLE_CHANGES:
3907 case REQ_TOGGLE_IGNORE_SPACE:
3908 case REQ_TOGGLE_ID:
3909 case REQ_TOGGLE_FILES:
3910 case REQ_TOGGLE_TITLE_OVERFLOW:
3911 case REQ_TOGGLE_FILE_SIZE:
3912 case REQ_TOGGLE_UNTRACKED_DIRS:
3913 case REQ_TOGGLE_VERTICAL_SPLIT:
3915 char action[SIZEOF_STR] = "";
3916 enum view_flag flags = toggle_option(view, request, action);
3918 if (flags == VIEW_FLAG_RESET_DISPLAY) {
3919 resize_display();
3920 redraw_display(TRUE);
3921 } else {
3922 foreach_displayed_view(view, i) {
3923 if (view_has_flags(view, flags) && !view->unrefreshable)
3924 reload_view(view);
3925 else
3926 redraw_view(view);
3930 if (*action)
3931 report("%s", action);
3933 break;
3935 case REQ_TOGGLE_SORT_FIELD:
3936 case REQ_TOGGLE_SORT_ORDER:
3937 report("Sorting is not yet supported for the %s view", view->name);
3938 break;
3940 case REQ_DIFF_CONTEXT_UP:
3941 case REQ_DIFF_CONTEXT_DOWN:
3942 report("Changing the diff context is not yet supported for the %s view", view->name);
3943 break;
3945 case REQ_SEARCH:
3946 case REQ_SEARCH_BACK:
3947 search_view(view, request);
3948 break;
3950 case REQ_FIND_NEXT:
3951 case REQ_FIND_PREV:
3952 find_next(view, request);
3953 break;
3955 case REQ_STOP_LOADING:
3956 foreach_view(view, i) {
3957 if (view->pipe)
3958 report("Stopped loading the %s view", view->name),
3959 end_update(view, TRUE);
3961 break;
3963 case REQ_SHOW_VERSION:
3964 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3965 return TRUE;
3967 case REQ_SCREEN_REDRAW:
3968 redraw_display(TRUE);
3969 break;
3971 case REQ_EDIT:
3972 report("Nothing to edit");
3973 break;
3975 case REQ_ENTER:
3976 report("Nothing to enter");
3977 break;
3979 case REQ_VIEW_CLOSE:
3980 /* XXX: Mark closed views by letting view->prev point to the
3981 * view itself. Parents to closed view should never be
3982 * followed. */
3983 if (view->prev && view->prev != view) {
3984 maximize_view(view->prev, TRUE);
3985 view->prev = view;
3986 break;
3988 /* Fall-through */
3989 case REQ_QUIT:
3990 return FALSE;
3992 default:
3993 report("Unknown key, press %s for help",
3994 get_view_key(view, REQ_VIEW_HELP));
3995 return TRUE;
3998 return TRUE;
4003 * View backend utilities
4006 enum sort_field {
4007 ORDERBY_NAME,
4008 ORDERBY_DATE,
4009 ORDERBY_AUTHOR,
4012 struct sort_state {
4013 const enum sort_field *fields;
4014 size_t size, current;
4015 bool reverse;
4018 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
4019 #define get_sort_field(state) ((state).fields[(state).current])
4020 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
4022 static void
4023 sort_view(struct view *view, enum request request, struct sort_state *state,
4024 int (*compare)(const void *, const void *))
4026 switch (request) {
4027 case REQ_TOGGLE_SORT_FIELD:
4028 state->current = (state->current + 1) % state->size;
4029 break;
4031 case REQ_TOGGLE_SORT_ORDER:
4032 state->reverse = !state->reverse;
4033 break;
4034 default:
4035 die("Not a sort request");
4038 qsort(view->line, view->lines, sizeof(*view->line), compare);
4039 redraw_view(view);
4042 static bool
4043 update_diff_context(enum request request)
4045 int diff_context = opt_diff_context;
4047 switch (request) {
4048 case REQ_DIFF_CONTEXT_UP:
4049 opt_diff_context += 1;
4050 update_diff_context_arg(opt_diff_context);
4051 break;
4053 case REQ_DIFF_CONTEXT_DOWN:
4054 if (opt_diff_context == 0) {
4055 report("Diff context cannot be less than zero");
4056 break;
4058 opt_diff_context -= 1;
4059 update_diff_context_arg(opt_diff_context);
4060 break;
4062 default:
4063 die("Not a diff context request");
4066 return diff_context != opt_diff_context;
4069 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
4071 /* Small cache to reduce memory consumption. It uses binary search to
4072 * lookup or find place to position new entries. No entries are ever
4073 * freed. */
4074 static const char *
4075 get_path(const char *path)
4077 static const char **paths;
4078 static size_t paths_size;
4079 int from = 0, to = paths_size - 1;
4080 char *entry;
4082 while (from <= to) {
4083 size_t pos = (to + from) / 2;
4084 int cmp = strcmp(path, paths[pos]);
4086 if (!cmp)
4087 return paths[pos];
4089 if (cmp < 0)
4090 to = pos - 1;
4091 else
4092 from = pos + 1;
4095 if (!realloc_paths(&paths, paths_size, 1))
4096 return NULL;
4097 entry = strdup(path);
4098 if (!entry)
4099 return NULL;
4101 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4102 paths[from] = entry;
4103 paths_size++;
4105 return entry;
4108 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4110 /* Small author cache to reduce memory consumption. It uses binary
4111 * search to lookup or find place to position new entries. No entries
4112 * are ever freed. */
4113 static struct ident *
4114 get_author(const char *name, const char *email)
4116 static struct ident **authors;
4117 static size_t authors_size;
4118 int from = 0, to = authors_size - 1;
4119 struct ident *ident;
4121 while (from <= to) {
4122 size_t pos = (to + from) / 2;
4123 int cmp = strcmp(name, authors[pos]->name);
4125 if (!cmp)
4126 return authors[pos];
4128 if (cmp < 0)
4129 to = pos - 1;
4130 else
4131 from = pos + 1;
4134 if (!realloc_authors(&authors, authors_size, 1))
4135 return NULL;
4136 ident = calloc(1, sizeof(*ident));
4137 if (!ident)
4138 return NULL;
4139 ident->name = strdup(name);
4140 ident->email = strdup(email);
4141 if (!ident->name || !ident->email) {
4142 free((void *) ident->name);
4143 free(ident);
4144 return NULL;
4147 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4148 authors[from] = ident;
4149 authors_size++;
4151 return ident;
4154 static void
4155 parse_timesec(struct time *time, const char *sec)
4157 time->sec = (time_t) atol(sec);
4160 static void
4161 parse_timezone(struct time *time, const char *zone)
4163 long tz;
4165 tz = ('0' - zone[1]) * 60 * 60 * 10;
4166 tz += ('0' - zone[2]) * 60 * 60;
4167 tz += ('0' - zone[3]) * 60 * 10;
4168 tz += ('0' - zone[4]) * 60;
4170 if (zone[0] == '-')
4171 tz = -tz;
4173 time->tz = tz;
4174 time->sec -= tz;
4177 /* Parse author lines where the name may be empty:
4178 * author <email@address.tld> 1138474660 +0100
4180 static void
4181 parse_author_line(char *ident, const struct ident **author, struct time *time)
4183 char *nameend = strchr(ident, '<');
4184 char *emailend = strchr(ident, '>');
4185 const char *name, *email = "";
4187 if (nameend && emailend)
4188 *nameend = *emailend = 0;
4189 name = chomp_string(ident);
4190 if (nameend)
4191 email = chomp_string(nameend + 1);
4192 if (!*name)
4193 name = *email ? email : unknown_ident.name;
4194 if (!*email)
4195 email = *name ? name : unknown_ident.email;
4197 *author = get_author(name, email);
4199 /* Parse epoch and timezone */
4200 if (time && emailend && emailend[1] == ' ') {
4201 char *secs = emailend + 2;
4202 char *zone = strchr(secs, ' ');
4204 parse_timesec(time, secs);
4206 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4207 parse_timezone(time, zone + 1);
4211 static struct line *
4212 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4214 for (; view_has_line(view, line); line += direction)
4215 if (line->type == type)
4216 return line;
4218 return NULL;
4221 #define find_prev_line_by_type(view, line, type) \
4222 find_line_by_type(view, line, type, -1)
4224 #define find_next_line_by_type(view, line, type) \
4225 find_line_by_type(view, line, type, 1)
4228 * View history
4231 struct view_state {
4232 struct view_state *prev; /* Entry below this in the stack */
4233 struct position position; /* View position to restore */
4234 void *data; /* View specific state */
4237 struct view_history {
4238 size_t state_alloc;
4239 struct view_state *stack;
4240 struct position position;
4243 static bool
4244 view_history_is_empty(struct view_history *history)
4246 return !history->stack;
4249 static struct view_state *
4250 push_view_history_state(struct view_history *history, struct position *position, void *data)
4252 struct view_state *state = history->stack;
4254 if (state && data && history->state_alloc &&
4255 !memcmp(state->data, data, history->state_alloc))
4256 return NULL;
4258 state = calloc(1, sizeof(*state) + history->state_alloc);
4259 if (!state)
4260 return NULL;
4262 state->prev = history->stack;
4263 history->stack = state;
4264 clear_position(&history->position);
4265 state->position = *position;
4266 state->data = &state[1];
4267 if (data && history->state_alloc)
4268 memcpy(state->data, data, history->state_alloc);
4269 return state;
4272 static bool
4273 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4275 struct view_state *state = history->stack;
4277 if (view_history_is_empty(history))
4278 return FALSE;
4280 history->position = state->position;
4281 history->stack = state->prev;
4283 if (data && history->state_alloc)
4284 memcpy(data, state->data, history->state_alloc);
4285 if (position)
4286 *position = state->position;
4288 free(state);
4289 return TRUE;
4292 static void
4293 reset_view_history(struct view_history *history)
4295 while (pop_view_history_state(history, NULL, NULL))
4300 * Blame
4303 struct blame_commit {
4304 char id[SIZEOF_REV]; /* SHA1 ID. */
4305 char title[128]; /* First line of the commit message. */
4306 const struct ident *author; /* Author of the commit. */
4307 struct time time; /* Date from the author ident. */
4308 const char *filename; /* Name of file. */
4309 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4310 const char *parent_filename; /* Parent/previous name of file. */
4313 struct blame_header {
4314 char id[SIZEOF_REV]; /* SHA1 ID. */
4315 size_t orig_lineno;
4316 size_t lineno;
4317 size_t group;
4320 static bool
4321 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4323 const char *pos = *posref;
4325 *posref = NULL;
4326 pos = strchr(pos + 1, ' ');
4327 if (!pos || !isdigit(pos[1]))
4328 return FALSE;
4329 *number = atoi(pos + 1);
4330 if (*number < min || *number > max)
4331 return FALSE;
4333 *posref = pos;
4334 return TRUE;
4337 static bool
4338 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4340 const char *pos = text + SIZEOF_REV - 2;
4342 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4343 return FALSE;
4345 string_ncopy(header->id, text, SIZEOF_REV);
4347 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4348 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4349 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4350 return FALSE;
4352 return TRUE;
4355 static bool
4356 match_blame_header(const char *name, char **line)
4358 size_t namelen = strlen(name);
4359 bool matched = !strncmp(name, *line, namelen);
4361 if (matched)
4362 *line += namelen;
4364 return matched;
4367 static bool
4368 parse_blame_info(struct blame_commit *commit, char *line)
4370 if (match_blame_header("author ", &line)) {
4371 parse_author_line(line, &commit->author, NULL);
4373 } else if (match_blame_header("author-time ", &line)) {
4374 parse_timesec(&commit->time, line);
4376 } else if (match_blame_header("author-tz ", &line)) {
4377 parse_timezone(&commit->time, line);
4379 } else if (match_blame_header("summary ", &line)) {
4380 string_ncopy(commit->title, line, strlen(line));
4382 } else if (match_blame_header("previous ", &line)) {
4383 if (strlen(line) <= SIZEOF_REV)
4384 return FALSE;
4385 string_copy_rev(commit->parent_id, line);
4386 line += SIZEOF_REV;
4387 commit->parent_filename = get_path(line);
4388 if (!commit->parent_filename)
4389 return TRUE;
4391 } else if (match_blame_header("filename ", &line)) {
4392 commit->filename = get_path(line);
4393 return TRUE;
4396 return FALSE;
4400 * Pager backend
4403 static bool
4404 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4406 if (draw_lineno(view, lineno))
4407 return TRUE;
4409 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4410 return TRUE;
4412 draw_text(view, line->type, line->data);
4413 return TRUE;
4416 static bool
4417 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4419 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4420 char ref[SIZEOF_STR];
4422 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4423 return TRUE;
4425 /* This is the only fatal call, since it can "corrupt" the buffer. */
4426 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4427 return FALSE;
4429 return TRUE;
4432 static void
4433 add_pager_refs(struct view *view, const char *commit_id)
4435 char buf[SIZEOF_STR];
4436 struct ref_list *list;
4437 size_t bufpos = 0, i;
4438 const char *sep = "Refs: ";
4439 bool is_tag = FALSE;
4441 list = get_ref_list(commit_id);
4442 if (!list) {
4443 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4444 goto try_add_describe_ref;
4445 return;
4448 for (i = 0; i < list->size; i++) {
4449 struct ref *ref = list->refs[i];
4450 const char *fmt = ref->tag ? "%s[%s]" :
4451 ref->remote ? "%s<%s>" : "%s%s";
4453 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4454 return;
4455 sep = ", ";
4456 if (ref->tag)
4457 is_tag = TRUE;
4460 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4461 try_add_describe_ref:
4462 /* Add <tag>-g<commit_id> "fake" reference. */
4463 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4464 return;
4467 if (bufpos == 0)
4468 return;
4470 add_line_text(view, buf, LINE_PP_REFS);
4473 static struct line *
4474 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4476 size_t first_line = 0;
4477 bool has_first_line = FALSE;
4478 size_t datalen = strlen(data);
4479 size_t lineno = 0;
4481 while (datalen > 0 || !has_first_line) {
4482 bool wrapped = !!first_line;
4483 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4484 struct line *line;
4485 char *text;
4487 line = add_line(view, NULL, type, linelen + 1, wrapped);
4488 if (!line)
4489 break;
4490 if (!has_first_line) {
4491 first_line = view->lines - 1;
4492 has_first_line = TRUE;
4495 if (!wrapped)
4496 lineno = line->lineno;
4498 line->wrapped = wrapped;
4499 line->lineno = lineno;
4500 text = line->data;
4501 if (linelen)
4502 strncpy(text, data, linelen);
4503 text[linelen] = 0;
4505 datalen -= linelen;
4506 data += linelen;
4509 return has_first_line ? &view->line[first_line] : NULL;
4512 static bool
4513 pager_common_read(struct view *view, const char *data, enum line_type type)
4515 struct line *line;
4517 if (!data)
4518 return TRUE;
4520 if (opt_wrap_lines) {
4521 line = pager_wrap_line(view, data, type);
4522 } else {
4523 line = add_line_text(view, data, type);
4526 if (!line)
4527 return FALSE;
4529 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4530 add_pager_refs(view, data + STRING_SIZE("commit "));
4532 return TRUE;
4535 static bool
4536 pager_read(struct view *view, char *data)
4538 if (!data)
4539 return TRUE;
4541 return pager_common_read(view, data, get_line_type(data));
4544 static enum request
4545 pager_request(struct view *view, enum request request, struct line *line)
4547 int split = 0;
4549 if (request != REQ_ENTER)
4550 return request;
4552 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4553 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4554 split = 1;
4557 /* Always scroll the view even if it was split. That way
4558 * you can use Enter to scroll through the log view and
4559 * split open each commit diff. */
4560 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4562 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4563 * but if we are scrolling a non-current view this won't properly
4564 * update the view title. */
4565 if (split)
4566 update_view_title(view);
4568 return REQ_NONE;
4571 static bool
4572 pager_grep(struct view *view, struct line *line)
4574 const char *text[] = { line->data, NULL };
4576 return grep_text(view, text);
4579 static void
4580 pager_select(struct view *view, struct line *line)
4582 if (line->type == LINE_COMMIT) {
4583 string_copy_rev_from_commit_line(ref_commit, line->data);
4584 if (!view_has_flags(view, VIEW_NO_REF))
4585 string_copy_rev(view->ref, ref_commit);
4589 struct log_state {
4590 /* Used for tracking when we need to recalculate the previous
4591 * commit, for example when the user scrolls up or uses the page
4592 * up/down in the log view. */
4593 int last_lineno;
4594 enum line_type last_type;
4597 static void
4598 log_select(struct view *view, struct line *line)
4600 struct log_state *state = view->private;
4601 int last_lineno = state->last_lineno;
4603 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4604 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4605 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4607 if (commit_line)
4608 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4611 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4612 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4614 string_copy_rev(ref_commit, view->ref);
4615 state->last_lineno = line->lineno;
4616 state->last_type = line->type;
4619 static bool
4620 pager_open(struct view *view, enum open_flags flags)
4622 if (!open_from_stdin(flags) && !view->lines) {
4623 report("No pager content, press %s to run command from prompt",
4624 get_view_key(view, REQ_PROMPT));
4625 return FALSE;
4628 return begin_update(view, NULL, NULL, flags);
4631 static struct view_ops pager_ops = {
4632 "line",
4633 { "pager" },
4634 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4636 pager_open,
4637 pager_read,
4638 pager_draw,
4639 pager_request,
4640 pager_grep,
4641 pager_select,
4644 static bool
4645 log_open(struct view *view, enum open_flags flags)
4647 static const char *log_argv[] = {
4648 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", "--", NULL
4651 return begin_update(view, NULL, log_argv, flags);
4654 static enum request
4655 log_request(struct view *view, enum request request, struct line *line)
4657 switch (request) {
4658 case REQ_REFRESH:
4659 load_refs(TRUE);
4660 refresh_view(view);
4661 return REQ_NONE;
4663 case REQ_ENTER:
4664 if (!display[1] || strcmp(display[1]->vid, view->ref))
4665 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4666 return REQ_NONE;
4668 default:
4669 return request;
4673 static struct view_ops log_ops = {
4674 "line",
4675 { "log" },
4676 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE | VIEW_REFRESH,
4677 sizeof(struct log_state),
4678 log_open,
4679 pager_read,
4680 pager_draw,
4681 log_request,
4682 pager_grep,
4683 log_select,
4686 struct diff_state {
4687 bool after_commit_title;
4688 bool after_diff;
4689 bool reading_diff_stat;
4690 bool combined_diff;
4693 #define DIFF_LINE_COMMIT_TITLE 1
4695 static bool
4696 diff_open(struct view *view, enum open_flags flags)
4698 static const char *diff_argv[] = {
4699 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4700 "--patch-with-stat",
4701 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4702 "%(diffargs)", "%(cmdlineargs)", "--no-color", "%(commit)",
4703 "--", "%(fileargs)", NULL
4706 return begin_update(view, NULL, diff_argv, flags);
4709 static bool
4710 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4712 enum line_type type = get_line_type(data);
4714 if (!view->lines && type != LINE_COMMIT)
4715 state->reading_diff_stat = TRUE;
4717 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4718 state->reading_diff_stat = TRUE;
4720 if (state->reading_diff_stat) {
4721 size_t len = strlen(data);
4722 char *pipe = strchr(data, '|');
4723 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4724 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4725 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4726 bool has_no_change = pipe && strstr(pipe, " 0");
4728 if (pipe && (has_histogram || has_bin_diff || has_rename || has_no_change)) {
4729 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4730 } else {
4731 state->reading_diff_stat = FALSE;
4734 } else if (!strcmp(data, "---")) {
4735 state->reading_diff_stat = TRUE;
4738 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4739 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4741 if (line)
4742 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4743 state->after_commit_title = TRUE;
4744 return line != NULL;
4747 if (type == LINE_DIFF_HEADER) {
4748 const int len = line_info[LINE_DIFF_HEADER].linelen;
4750 state->after_diff = TRUE;
4751 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4752 !strncmp(data + len, "cc ", strlen("cc ")))
4753 state->combined_diff = TRUE;
4755 } else if (type == LINE_PP_MERGE) {
4756 state->combined_diff = TRUE;
4759 /* ADD2 and DEL2 are only valid in combined diff hunks */
4760 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4761 type = LINE_DEFAULT;
4763 return pager_common_read(view, data, type);
4766 static bool
4767 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4769 struct line *marker = find_next_line_by_type(view, line, type);
4771 return marker &&
4772 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4775 static enum request
4776 diff_common_enter(struct view *view, enum request request, struct line *line)
4778 if (line->type == LINE_DIFF_STAT) {
4779 int file_number = 0;
4781 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4782 file_number++;
4783 line--;
4786 for (line = view->line; view_has_line(view, line); line++) {
4787 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4788 if (!line)
4789 break;
4791 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4792 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4793 if (file_number == 1) {
4794 break;
4796 file_number--;
4800 if (!line) {
4801 report("Failed to find file diff");
4802 return REQ_NONE;
4805 select_view_line(view, line - view->line);
4806 report_clear();
4807 return REQ_NONE;
4809 } else {
4810 return pager_request(view, request, line);
4814 static bool
4815 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4817 char *sep = strchr(*text, c);
4819 if (sep != NULL) {
4820 *sep = 0;
4821 draw_text(view, *type, *text);
4822 *sep = c;
4823 *text = sep;
4824 *type = next_type;
4827 return sep != NULL;
4830 static bool
4831 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4833 char *text = line->data;
4834 enum line_type type = line->type;
4836 if (draw_lineno(view, lineno))
4837 return TRUE;
4839 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4840 return TRUE;
4842 if (type == LINE_DIFF_STAT) {
4843 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4844 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4845 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4846 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4847 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4848 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4849 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4851 } else {
4852 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4853 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4857 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4858 draw_commit_title(view, text, 4);
4859 else
4860 draw_text(view, type, text);
4861 return TRUE;
4864 static bool
4865 diff_read(struct view *view, char *data)
4867 struct diff_state *state = view->private;
4869 if (!data) {
4870 /* Fall back to retry if no diff will be shown. */
4871 if (view->lines == 0 && opt_file_argv) {
4872 int pos = argv_size(view->argv)
4873 - argv_size(opt_file_argv) - 1;
4875 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4876 for (; view->argv[pos]; pos++) {
4877 free((void *) view->argv[pos]);
4878 view->argv[pos] = NULL;
4881 if (view->pipe)
4882 io_done(view->pipe);
4883 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4884 return FALSE;
4887 return TRUE;
4890 return diff_common_read(view, data, state);
4893 static bool
4894 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4895 struct blame_header *header, struct blame_commit *commit)
4897 char line_arg[SIZEOF_STR];
4898 const char *blame_argv[] = {
4899 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4901 struct io io;
4902 bool ok = FALSE;
4903 char *buf;
4905 if (!string_format(line_arg, "-L%ld,+1", lineno))
4906 return FALSE;
4908 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4909 return FALSE;
4911 while ((buf = io_get(&io, '\n', TRUE))) {
4912 if (header) {
4913 if (!parse_blame_header(header, buf, 9999999))
4914 break;
4915 header = NULL;
4917 } else if (parse_blame_info(commit, buf)) {
4918 ok = commit->filename != NULL;
4919 break;
4923 if (io_error(&io))
4924 ok = FALSE;
4926 io_done(&io);
4927 return ok;
4930 struct chunk_header_position {
4931 unsigned long position;
4932 unsigned long lines;
4935 struct chunk_header {
4936 struct chunk_header_position old;
4937 struct chunk_header_position new;
4940 static bool
4941 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
4943 const char *start = *pos_ptr;
4944 char *end;
4946 if (!isdigit(*start))
4947 return 0;
4949 *value = strtoul(start, &end, 10);
4950 if (end == start)
4951 return FALSE;
4953 start = end;
4954 while (skip && *start && strchr(skip, *start))
4955 start++;
4956 *pos_ptr = start;
4957 return TRUE;
4960 static bool
4961 parse_chunk_header(struct chunk_header *header, const char *line)
4963 memset(header, 0, sizeof(*header));
4965 if (prefixcmp(line, "@@ -"))
4966 return FALSE;
4968 line += STRING_SIZE("@@ -");
4970 return parse_ulong(&line, &header->old.position, ",") &&
4971 parse_ulong(&line, &header->old.lines, " +") &&
4972 parse_ulong(&line, &header->new.position, ",") &&
4973 parse_ulong(&line, &header->new.lines, NULL);
4976 static unsigned int
4977 diff_get_lineno(struct view *view, struct line *line)
4979 const struct line *header, *chunk;
4980 unsigned int lineno;
4981 struct chunk_header chunk_header;
4983 /* Verify that we are after a diff header and one of its chunks */
4984 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4985 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4986 if (!header || !chunk || chunk < header)
4987 return 0;
4990 * In a chunk header, the number after the '+' sign is the number of its
4991 * following line, in the new version of the file. We increment this
4992 * number for each non-deletion line, until the given line position.
4994 if (!parse_chunk_header(&chunk_header, chunk->data))
4995 return 0;
4997 lineno = chunk_header.new.position;
4998 chunk++;
4999 while (chunk++ < line)
5000 if (chunk->type != LINE_DIFF_DEL)
5001 lineno++;
5003 return lineno;
5006 static bool
5007 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
5009 struct chunk_header chunk_header;
5011 *lineno = 0;
5013 if (!parse_chunk_header(&chunk_header, chunk))
5014 return FALSE;
5016 *lineno = marker == '-' ? chunk_header.old.position : chunk_header.new.position;
5017 return TRUE;
5020 static enum request
5021 diff_trace_origin(struct view *view, struct line *line)
5023 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5024 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
5025 const char *chunk_data;
5026 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
5027 unsigned long lineno = 0;
5028 const char *file = NULL;
5029 char ref[SIZEOF_REF];
5030 struct blame_header header;
5031 struct blame_commit commit;
5033 if (!diff || !chunk || chunk == line) {
5034 report("The line to trace must be inside a diff chunk");
5035 return REQ_NONE;
5038 for (; diff < line && !file; diff++) {
5039 const char *data = diff->data;
5041 if (!prefixcmp(data, "--- a/")) {
5042 file = data + STRING_SIZE("--- a/");
5043 break;
5047 if (diff == line || !file) {
5048 report("Failed to read the file name");
5049 return REQ_NONE;
5052 chunk_data = chunk->data;
5054 if (!parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
5055 report("Failed to read the line number");
5056 return REQ_NONE;
5059 if (lineno == 0) {
5060 report("This is the origin of the line");
5061 return REQ_NONE;
5064 for (chunk += 1; chunk < line; chunk++) {
5065 if (chunk->type == LINE_DIFF_ADD) {
5066 lineno += chunk_marker == '+';
5067 } else if (chunk->type == LINE_DIFF_DEL) {
5068 lineno += chunk_marker == '-';
5069 } else {
5070 lineno++;
5074 if (chunk_marker == '+')
5075 string_copy(ref, view->vid);
5076 else
5077 string_format(ref, "%s^", view->vid);
5079 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
5080 report("Failed to read blame data");
5081 return REQ_NONE;
5084 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
5085 string_copy(opt_ref, header.id);
5086 opt_goto_line = header.orig_lineno - 1;
5088 return REQ_VIEW_BLAME;
5091 static const char *
5092 diff_get_pathname(struct view *view, struct line *line)
5094 const struct line *header;
5095 const char *dst = NULL;
5096 const char *prefixes[] = { " b/", "cc ", "combined " };
5097 int i;
5099 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5100 if (!header)
5101 return NULL;
5103 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
5104 dst = strstr(header->data, prefixes[i]);
5106 return dst ? dst + strlen(prefixes[--i]) : NULL;
5109 static enum request
5110 diff_common_edit(struct view *view, enum request request, struct line *line)
5112 const char *file = diff_get_pathname(view, line);
5113 char path[SIZEOF_STR];
5114 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
5116 if (has_path && access(path, R_OK)) {
5117 report("Failed to open file: %s", file);
5118 return REQ_NONE;
5121 open_editor(file, diff_get_lineno(view, line));
5122 return REQ_NONE;
5125 static enum request
5126 diff_request(struct view *view, enum request request, struct line *line)
5128 switch (request) {
5129 case REQ_VIEW_BLAME:
5130 return diff_trace_origin(view, line);
5132 case REQ_DIFF_CONTEXT_UP:
5133 case REQ_DIFF_CONTEXT_DOWN:
5134 if (!update_diff_context(request))
5135 return REQ_NONE;
5136 reload_view(view);
5137 return REQ_NONE;
5140 case REQ_EDIT:
5141 return diff_common_edit(view, request, line);
5143 case REQ_ENTER:
5144 return diff_common_enter(view, request, line);
5146 case REQ_REFRESH:
5147 if (string_rev_is_null(view->vid))
5148 refresh_view(view);
5149 else
5150 reload_view(view);
5151 return REQ_NONE;
5153 default:
5154 return pager_request(view, request, line);
5158 static void
5159 diff_select(struct view *view, struct line *line)
5161 if (line->type == LINE_DIFF_STAT) {
5162 string_format(view->ref, "Press '%s' to jump to file diff",
5163 get_view_key(view, REQ_ENTER));
5164 } else {
5165 const char *file = diff_get_pathname(view, line);
5167 if (file) {
5168 string_format(view->ref, "Changes to '%s'", file);
5169 string_format(opt_file, "%s", file);
5170 ref_blob[0] = 0;
5171 } else {
5172 string_ncopy(view->ref, view->id, strlen(view->id));
5173 pager_select(view, line);
5178 static struct view_ops diff_ops = {
5179 "line",
5180 { "diff" },
5181 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER | VIEW_REFRESH,
5182 sizeof(struct diff_state),
5183 diff_open,
5184 diff_read,
5185 diff_common_draw,
5186 diff_request,
5187 pager_grep,
5188 diff_select,
5192 * Help backend
5195 static bool
5196 help_draw(struct view *view, struct line *line, unsigned int lineno)
5198 if (line->type == LINE_HELP_KEYMAP) {
5199 struct keymap *keymap = line->data;
5201 draw_formatted(view, line->type, "[%c] %s bindings",
5202 keymap->hidden ? '+' : '-', keymap->name);
5203 return TRUE;
5204 } else {
5205 return pager_draw(view, line, lineno);
5209 static bool
5210 help_open_keymap_title(struct view *view, struct keymap *keymap)
5212 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5213 return keymap->hidden;
5216 static void
5217 help_open_keymap(struct view *view, struct keymap *keymap)
5219 const char *group = NULL;
5220 char buf[SIZEOF_STR];
5221 bool add_title = TRUE;
5222 int i;
5224 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5225 const char *key = NULL;
5227 if (req_info[i].request == REQ_NONE)
5228 continue;
5230 if (!req_info[i].request) {
5231 group = req_info[i].help;
5232 continue;
5235 key = get_keys(keymap, req_info[i].request, TRUE);
5236 if (!key || !*key)
5237 continue;
5239 if (add_title && help_open_keymap_title(view, keymap))
5240 return;
5241 add_title = FALSE;
5243 if (group) {
5244 add_line_text(view, group, LINE_HELP_GROUP);
5245 group = NULL;
5248 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5249 enum_name(req_info[i]), req_info[i].help);
5252 group = "External commands:";
5254 for (i = 0; i < run_requests; i++) {
5255 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5256 const char *key;
5258 if (!req || req->keymap != keymap)
5259 continue;
5261 key = get_key_name(req->key);
5262 if (!*key)
5263 key = "(no key defined)";
5265 if (add_title && help_open_keymap_title(view, keymap))
5266 return;
5267 add_title = FALSE;
5269 if (group) {
5270 add_line_text(view, group, LINE_HELP_GROUP);
5271 group = NULL;
5274 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5275 return;
5277 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5281 static bool
5282 help_open(struct view *view, enum open_flags flags)
5284 struct keymap *keymap;
5286 reset_view(view);
5287 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5288 add_line_text(view, "", LINE_DEFAULT);
5290 for (keymap = keymaps; keymap; keymap = keymap->next)
5291 help_open_keymap(view, keymap);
5293 return TRUE;
5296 static enum request
5297 help_request(struct view *view, enum request request, struct line *line)
5299 switch (request) {
5300 case REQ_ENTER:
5301 if (line->type == LINE_HELP_KEYMAP) {
5302 struct keymap *keymap = line->data;
5304 keymap->hidden = !keymap->hidden;
5305 refresh_view(view);
5308 return REQ_NONE;
5309 default:
5310 return pager_request(view, request, line);
5314 static void
5315 help_done(struct view *view)
5317 int i;
5319 for (i = 0; i < view->lines; i++)
5320 if (view->line[i].type == LINE_HELP_KEYMAP)
5321 view->line[i].data = NULL;
5324 static struct view_ops help_ops = {
5325 "line",
5326 { "help" },
5327 VIEW_NO_GIT_DIR,
5329 help_open,
5330 NULL,
5331 help_draw,
5332 help_request,
5333 pager_grep,
5334 pager_select,
5335 help_done,
5340 * Tree backend
5343 /* The top of the path stack. */
5344 static struct view_history tree_view_history = { sizeof(char *) };
5346 static void
5347 pop_tree_stack_entry(struct position *position)
5349 char *path_position = NULL;
5351 pop_view_history_state(&tree_view_history, position, &path_position);
5352 path_position[0] = 0;
5355 static void
5356 push_tree_stack_entry(const char *name, struct position *position)
5358 size_t pathlen = strlen(opt_path);
5359 char *path_position = opt_path + pathlen;
5360 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5362 if (!state)
5363 return;
5365 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5366 pop_tree_stack_entry(NULL);
5367 return;
5370 clear_position(position);
5373 /* Parse output from git-ls-tree(1):
5375 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5378 #define SIZEOF_TREE_ATTR \
5379 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5381 #define SIZEOF_TREE_MODE \
5382 STRING_SIZE("100644 ")
5384 #define TREE_ID_OFFSET \
5385 STRING_SIZE("100644 blob ")
5387 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5389 struct tree_entry {
5390 char id[SIZEOF_REV];
5391 char commit[SIZEOF_REV];
5392 mode_t mode;
5393 struct time time; /* Date from the author ident. */
5394 const struct ident *author; /* Author of the commit. */
5395 unsigned long size;
5396 char name[1];
5399 struct tree_state {
5400 char commit[SIZEOF_REV];
5401 const struct ident *author;
5402 struct time author_time;
5403 int size_width;
5404 bool read_date;
5407 static const char *
5408 tree_path(const struct line *line)
5410 return ((struct tree_entry *) line->data)->name;
5413 static int
5414 tree_compare_entry(const struct line *line1, const struct line *line2)
5416 if (line1->type != line2->type)
5417 return line1->type == LINE_TREE_DIR ? -1 : 1;
5418 return strcmp(tree_path(line1), tree_path(line2));
5421 static const enum sort_field tree_sort_fields[] = {
5422 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5424 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5426 static int
5427 tree_compare(const void *l1, const void *l2)
5429 const struct line *line1 = (const struct line *) l1;
5430 const struct line *line2 = (const struct line *) l2;
5431 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5432 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5434 if (line1->type == LINE_TREE_HEAD)
5435 return -1;
5436 if (line2->type == LINE_TREE_HEAD)
5437 return 1;
5439 switch (get_sort_field(tree_sort_state)) {
5440 case ORDERBY_DATE:
5441 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5443 case ORDERBY_AUTHOR:
5444 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5446 case ORDERBY_NAME:
5447 default:
5448 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5453 static struct line *
5454 tree_entry(struct view *view, enum line_type type, const char *path,
5455 const char *mode, const char *id, unsigned long size)
5457 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5458 struct tree_entry *entry;
5459 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5461 if (!line)
5462 return NULL;
5464 strncpy(entry->name, path, strlen(path));
5465 if (mode)
5466 entry->mode = strtoul(mode, NULL, 8);
5467 if (id)
5468 string_copy_rev(entry->id, id);
5469 entry->size = size;
5471 return line;
5474 static bool
5475 tree_read_date(struct view *view, char *text, struct tree_state *state)
5477 if (!text && state->read_date) {
5478 state->read_date = FALSE;
5479 return TRUE;
5481 } else if (!text) {
5482 /* Find next entry to process */
5483 const char *log_file[] = {
5484 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5485 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5488 if (!view->lines) {
5489 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5490 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5491 report("Tree is empty");
5492 return TRUE;
5495 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5496 report("Failed to load tree data");
5497 return TRUE;
5500 state->read_date = TRUE;
5501 return FALSE;
5503 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5504 string_copy_rev_from_commit_line(state->commit, text);
5506 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5507 parse_author_line(text + STRING_SIZE("author "),
5508 &state->author, &state->author_time);
5510 } else if (*text == ':') {
5511 char *pos;
5512 size_t annotated = 1;
5513 size_t i;
5515 pos = strchr(text, '\t');
5516 if (!pos)
5517 return TRUE;
5518 text = pos + 1;
5519 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5520 text += strlen(opt_path);
5521 pos = strchr(text, '/');
5522 if (pos)
5523 *pos = 0;
5525 for (i = 1; i < view->lines; i++) {
5526 struct line *line = &view->line[i];
5527 struct tree_entry *entry = line->data;
5529 annotated += !!entry->author;
5530 if (entry->author || strcmp(entry->name, text))
5531 continue;
5533 string_copy_rev(entry->commit, state->commit);
5534 entry->author = state->author;
5535 entry->time = state->author_time;
5536 line->dirty = 1;
5537 break;
5540 if (annotated == view->lines)
5541 io_kill(view->pipe);
5543 return TRUE;
5546 static inline size_t
5547 parse_size(const char *text, int *max_digits)
5549 size_t size = 0;
5550 int digits = 0;
5552 while (*text == ' ')
5553 text++;
5555 while (isdigit(*text)) {
5556 size = (size * 10) + (*text++ - '0');
5557 digits++;
5560 if (digits > *max_digits)
5561 *max_digits = digits;
5563 return size;
5566 static bool
5567 tree_read(struct view *view, char *text)
5569 struct tree_state *state = view->private;
5570 struct tree_entry *data;
5571 struct line *entry, *line;
5572 enum line_type type;
5573 size_t textlen = text ? strlen(text) : 0;
5574 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5575 char *path;
5576 size_t size;
5578 if (state->read_date || !text)
5579 return tree_read_date(view, text, state);
5581 if (textlen <= SIZEOF_TREE_ATTR)
5582 return FALSE;
5583 if (view->lines == 0 &&
5584 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5585 return FALSE;
5587 size = parse_size(attr_offset, &state->size_width);
5588 path = strchr(attr_offset, '\t');
5589 if (!path)
5590 return FALSE;
5591 path++;
5593 /* Strip the path part ... */
5594 if (*opt_path) {
5595 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5596 size_t striplen = strlen(opt_path);
5598 if (pathlen > striplen)
5599 memmove(path, path + striplen,
5600 pathlen - striplen + 1);
5602 /* Insert "link" to parent directory. */
5603 if (view->lines == 1 &&
5604 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5605 return FALSE;
5608 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5609 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5610 if (!entry)
5611 return FALSE;
5612 data = entry->data;
5614 /* Skip "Directory ..." and ".." line. */
5615 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5616 if (tree_compare_entry(line, entry) <= 0)
5617 continue;
5619 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5621 line->data = data;
5622 line->type = type;
5623 for (; line <= entry; line++)
5624 line->dirty = line->cleareol = 1;
5625 return TRUE;
5628 /* Move the current line to the first tree entry. */
5629 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5630 goto_view_line(view, 0, 1);
5632 return TRUE;
5635 static bool
5636 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5638 struct tree_state *state = view->private;
5639 struct tree_entry *entry = line->data;
5641 if (line->type == LINE_TREE_HEAD) {
5642 if (draw_text(view, line->type, "Directory path /"))
5643 return TRUE;
5644 } else {
5645 if (draw_mode(view, entry->mode))
5646 return TRUE;
5648 if (draw_author(view, entry->author))
5649 return TRUE;
5651 if (draw_file_size(view, entry->size, state->size_width,
5652 line->type != LINE_TREE_FILE))
5653 return TRUE;
5655 if (draw_date(view, &entry->time))
5656 return TRUE;
5658 if (draw_id(view, entry->commit))
5659 return TRUE;
5662 draw_text(view, line->type, entry->name);
5663 return TRUE;
5666 static void
5667 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5669 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5670 char file[SIZEOF_STR];
5671 int fd;
5673 if (!name)
5674 name = "unknown";
5676 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5677 report("Temporary file name is too long");
5678 return;
5681 fd = mkstemps(file, strlen(name) + 1);
5683 if (fd == -1)
5684 report("Failed to create temporary file");
5685 else if (!io_run_append(blob_argv, fd))
5686 report("Failed to save blob data to file");
5687 else
5688 open_editor(file, lineno);
5689 if (fd != -1)
5690 unlink(file);
5693 static enum request
5694 tree_request(struct view *view, enum request request, struct line *line)
5696 enum open_flags flags;
5697 struct tree_entry *entry = line->data;
5699 switch (request) {
5700 case REQ_VIEW_BLAME:
5701 if (line->type != LINE_TREE_FILE) {
5702 report("Blame only supported for files");
5703 return REQ_NONE;
5706 string_copy(opt_ref, view->vid);
5707 return request;
5709 case REQ_EDIT:
5710 if (line->type != LINE_TREE_FILE) {
5711 report("Edit only supported for files");
5712 } else if (!is_head_commit(view->vid)) {
5713 open_blob_editor(entry->id, entry->name, 0);
5714 } else {
5715 open_editor(opt_file, 0);
5717 return REQ_NONE;
5719 case REQ_TOGGLE_SORT_FIELD:
5720 case REQ_TOGGLE_SORT_ORDER:
5721 sort_view(view, request, &tree_sort_state, tree_compare);
5722 return REQ_NONE;
5724 case REQ_PARENT:
5725 case REQ_BACK:
5726 if (!*opt_path) {
5727 /* quit view if at top of tree */
5728 return REQ_VIEW_CLOSE;
5730 /* fake 'cd ..' */
5731 line = &view->line[1];
5732 break;
5734 case REQ_ENTER:
5735 break;
5737 default:
5738 return request;
5741 /* Cleanup the stack if the tree view is at a different tree. */
5742 if (!*opt_path)
5743 reset_view_history(&tree_view_history);
5745 switch (line->type) {
5746 case LINE_TREE_DIR:
5747 /* Depending on whether it is a subdirectory or parent link
5748 * mangle the path buffer. */
5749 if (line == &view->line[1] && *opt_path) {
5750 pop_tree_stack_entry(&view->pos);
5752 } else {
5753 const char *basename = tree_path(line);
5755 push_tree_stack_entry(basename, &view->pos);
5758 /* Trees and subtrees share the same ID, so they are not not
5759 * unique like blobs. */
5760 flags = OPEN_RELOAD;
5761 request = REQ_VIEW_TREE;
5762 break;
5764 case LINE_TREE_FILE:
5765 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5766 request = REQ_VIEW_BLOB;
5767 break;
5769 default:
5770 return REQ_NONE;
5773 open_view(view, request, flags);
5775 return REQ_NONE;
5778 static bool
5779 tree_grep(struct view *view, struct line *line)
5781 struct tree_entry *entry = line->data;
5782 const char *text[] = {
5783 entry->name,
5784 mkauthor(entry->author, opt_author_width, opt_author),
5785 mkdate(&entry->time, opt_date),
5786 NULL
5789 return grep_text(view, text);
5792 static void
5793 tree_select(struct view *view, struct line *line)
5795 struct tree_entry *entry = line->data;
5797 if (line->type == LINE_TREE_HEAD) {
5798 string_format(view->ref, "Files in /%s", opt_path);
5799 return;
5802 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5803 string_copy(view->ref, "Open parent directory");
5804 ref_blob[0] = 0;
5805 return;
5808 if (line->type == LINE_TREE_FILE) {
5809 string_copy_rev(ref_blob, entry->id);
5810 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5813 string_copy_rev(view->ref, entry->id);
5816 static bool
5817 tree_open(struct view *view, enum open_flags flags)
5819 static const char *tree_argv[] = {
5820 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5823 if (string_rev_is_null(ref_commit)) {
5824 report("No tree exists for this commit");
5825 return FALSE;
5828 if (view->lines == 0 && opt_prefix[0]) {
5829 char *pos = opt_prefix;
5831 while (pos && *pos) {
5832 char *end = strchr(pos, '/');
5834 if (end)
5835 *end = 0;
5836 push_tree_stack_entry(pos, &view->pos);
5837 pos = end;
5838 if (end) {
5839 *end = '/';
5840 pos++;
5844 } else if (strcmp(view->vid, view->id)) {
5845 opt_path[0] = 0;
5848 return begin_update(view, opt_cdup, tree_argv, flags);
5851 static struct view_ops tree_ops = {
5852 "file",
5853 { "tree" },
5854 VIEW_SEND_CHILD_ENTER,
5855 sizeof(struct tree_state),
5856 tree_open,
5857 tree_read,
5858 tree_draw,
5859 tree_request,
5860 tree_grep,
5861 tree_select,
5864 static bool
5865 blob_open(struct view *view, enum open_flags flags)
5867 static const char *blob_argv[] = {
5868 "git", "cat-file", "blob", "%(blob)", NULL
5871 if (!ref_blob[0] && opt_file[0]) {
5872 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5873 char blob_spec[SIZEOF_STR];
5874 const char *rev_parse_argv[] = {
5875 "git", "rev-parse", blob_spec, NULL
5878 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5879 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5880 report("Failed to resolve blob from file name");
5881 return FALSE;
5885 if (!ref_blob[0]) {
5886 report("No file chosen, press %s to open tree view",
5887 get_view_key(view, REQ_VIEW_TREE));
5888 return FALSE;
5891 view->encoding = get_path_encoding(opt_file, default_encoding);
5893 return begin_update(view, NULL, blob_argv, flags);
5896 static bool
5897 blob_read(struct view *view, char *line)
5899 if (!line)
5900 return TRUE;
5901 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5904 static enum request
5905 blob_request(struct view *view, enum request request, struct line *line)
5907 switch (request) {
5908 case REQ_VIEW_BLAME:
5909 if (view->parent)
5910 string_copy(opt_ref, view->parent->vid);
5911 return request;
5913 case REQ_EDIT:
5914 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5915 return REQ_NONE;
5916 default:
5917 return pager_request(view, request, line);
5921 static struct view_ops blob_ops = {
5922 "line",
5923 { "blob" },
5924 VIEW_NO_FLAGS,
5926 blob_open,
5927 blob_read,
5928 pager_draw,
5929 blob_request,
5930 pager_grep,
5931 pager_select,
5935 * Blame backend
5937 * Loading the blame view is a two phase job:
5939 * 1. File content is read either using opt_file from the
5940 * filesystem or using git-cat-file.
5941 * 2. Then blame information is incrementally added by
5942 * reading output from git-blame.
5945 struct blame_history_state {
5946 char id[SIZEOF_REV]; /* SHA1 ID. */
5947 const char *filename; /* Name of file. */
5950 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5952 struct blame {
5953 struct blame_commit *commit;
5954 unsigned long lineno;
5955 char text[1];
5958 struct blame_state {
5959 struct blame_commit *commit;
5960 int blamed;
5961 bool done_reading;
5962 bool auto_filename_display;
5963 /* The history state for the current view is cached in the view
5964 * state so it always matches what was used to load the current blame
5965 * view. */
5966 struct blame_history_state history_state;
5969 static bool
5970 blame_detect_filename_display(struct view *view)
5972 bool show_filenames = FALSE;
5973 const char *filename = NULL;
5974 int i;
5976 if (opt_blame_argv) {
5977 for (i = 0; opt_blame_argv[i]; i++) {
5978 if (prefixcmp(opt_blame_argv[i], "-C"))
5979 continue;
5981 show_filenames = TRUE;
5985 for (i = 0; i < view->lines; i++) {
5986 struct blame *blame = view->line[i].data;
5988 if (blame->commit && blame->commit->id[0]) {
5989 if (!filename)
5990 filename = blame->commit->filename;
5991 else if (strcmp(filename, blame->commit->filename))
5992 show_filenames = TRUE;
5996 return show_filenames;
5999 static bool
6000 blame_open(struct view *view, enum open_flags flags)
6002 struct blame_state *state = view->private;
6003 const char *file_argv[] = { opt_cdup, opt_file , NULL };
6004 char path[SIZEOF_STR];
6005 size_t i;
6007 if (!opt_file[0]) {
6008 report("No file chosen, press %s to open tree view",
6009 get_view_key(view, REQ_VIEW_TREE));
6010 return FALSE;
6013 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
6014 string_copy(path, opt_file);
6015 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
6016 report("Failed to setup the blame view");
6017 return FALSE;
6021 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
6022 const char *blame_cat_file_argv[] = {
6023 "git", "cat-file", "blob", "%(ref):%(file)", NULL
6026 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
6027 return FALSE;
6030 /* First pass: remove multiple references to the same commit. */
6031 for (i = 0; i < view->lines; i++) {
6032 struct blame *blame = view->line[i].data;
6034 if (blame->commit && blame->commit->id[0])
6035 blame->commit->id[0] = 0;
6036 else
6037 blame->commit = NULL;
6040 /* Second pass: free existing references. */
6041 for (i = 0; i < view->lines; i++) {
6042 struct blame *blame = view->line[i].data;
6044 if (blame->commit)
6045 free(blame->commit);
6048 if (!(flags & OPEN_RELOAD))
6049 reset_view_history(&blame_view_history);
6050 string_copy_rev(state->history_state.id, opt_ref);
6051 state->history_state.filename = get_path(opt_file);
6052 if (!state->history_state.filename)
6053 return FALSE;
6054 string_format(view->vid, "%s", opt_file);
6055 string_format(view->ref, "%s ...", opt_file);
6057 return TRUE;
6060 static struct blame_commit *
6061 get_blame_commit(struct view *view, const char *id)
6063 size_t i;
6065 for (i = 0; i < view->lines; i++) {
6066 struct blame *blame = view->line[i].data;
6068 if (!blame->commit)
6069 continue;
6071 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
6072 return blame->commit;
6076 struct blame_commit *commit = calloc(1, sizeof(*commit));
6078 if (commit)
6079 string_ncopy(commit->id, id, SIZEOF_REV);
6080 return commit;
6084 static struct blame_commit *
6085 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
6087 struct blame_header header;
6088 struct blame_commit *commit;
6089 struct blame *blame;
6091 if (!parse_blame_header(&header, text, view->lines))
6092 return NULL;
6094 commit = get_blame_commit(view, text);
6095 if (!commit)
6096 return NULL;
6098 state->blamed += header.group;
6099 while (header.group--) {
6100 struct line *line = &view->line[header.lineno + header.group - 1];
6102 blame = line->data;
6103 blame->commit = commit;
6104 blame->lineno = header.orig_lineno + header.group - 1;
6105 line->dirty = 1;
6108 return commit;
6111 static bool
6112 blame_read_file(struct view *view, const char *text, struct blame_state *state)
6114 if (!text) {
6115 const char *blame_argv[] = {
6116 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
6117 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
6120 if (view->lines == 0 && !view->prev)
6121 die("No blame exist for %s", view->vid);
6123 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
6124 report("Failed to load blame data");
6125 return TRUE;
6128 if (opt_goto_line > 0) {
6129 select_view_line(view, opt_goto_line);
6130 opt_goto_line = 0;
6133 state->done_reading = TRUE;
6134 return FALSE;
6136 } else {
6137 size_t textlen = strlen(text);
6138 struct blame *blame;
6140 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
6141 return FALSE;
6143 blame->commit = NULL;
6144 strncpy(blame->text, text, textlen);
6145 blame->text[textlen] = 0;
6146 return TRUE;
6150 static bool
6151 blame_read(struct view *view, char *line)
6153 struct blame_state *state = view->private;
6155 if (!state->done_reading)
6156 return blame_read_file(view, line, state);
6158 if (!line) {
6159 state->auto_filename_display = blame_detect_filename_display(view);
6160 string_format(view->ref, "%s", view->vid);
6161 if (view_is_displayed(view)) {
6162 update_view_title(view);
6163 redraw_view_from(view, 0);
6165 return TRUE;
6168 if (!state->commit) {
6169 state->commit = read_blame_commit(view, line, state);
6170 string_format(view->ref, "%s %2zd%%", view->vid,
6171 view->lines ? state->blamed * 100 / view->lines : 0);
6173 } else if (parse_blame_info(state->commit, line)) {
6174 if (!state->commit->filename)
6175 return FALSE;
6176 state->commit = NULL;
6179 return TRUE;
6182 static bool
6183 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6185 struct blame_state *state = view->private;
6186 struct blame *blame = line->data;
6187 struct time *time = NULL;
6188 const char *id = NULL, *filename = NULL;
6189 const struct ident *author = NULL;
6190 enum line_type id_type = LINE_ID;
6191 static const enum line_type blame_colors[] = {
6192 LINE_PALETTE_0,
6193 LINE_PALETTE_1,
6194 LINE_PALETTE_2,
6195 LINE_PALETTE_3,
6196 LINE_PALETTE_4,
6197 LINE_PALETTE_5,
6198 LINE_PALETTE_6,
6201 #define BLAME_COLOR(i) \
6202 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6204 if (blame->commit && blame->commit->filename) {
6205 id = blame->commit->id;
6206 author = blame->commit->author;
6207 filename = blame->commit->filename;
6208 time = &blame->commit->time;
6209 id_type = BLAME_COLOR((long) blame->commit);
6212 if (draw_date(view, time))
6213 return TRUE;
6215 if (draw_author(view, author))
6216 return TRUE;
6218 if (draw_filename(view, filename, state->auto_filename_display))
6219 return TRUE;
6221 if (draw_id_custom(view, id_type, id, opt_id_cols))
6222 return TRUE;
6224 if (draw_lineno(view, lineno))
6225 return TRUE;
6227 draw_text(view, LINE_DEFAULT, blame->text);
6228 return TRUE;
6231 static bool
6232 check_blame_commit(struct blame *blame, bool check_null_id)
6234 if (!blame->commit)
6235 report("Commit data not loaded yet");
6236 else if (check_null_id && string_rev_is_null(blame->commit->id))
6237 report("No commit exist for the selected line");
6238 else
6239 return TRUE;
6240 return FALSE;
6243 static void
6244 setup_blame_parent_line(struct view *view, struct blame *blame)
6246 char from[SIZEOF_REF + SIZEOF_STR];
6247 char to[SIZEOF_REF + SIZEOF_STR];
6248 const char *diff_tree_argv[] = {
6249 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6250 "--no-color", "-U0", from, to, "--", NULL
6252 struct io io;
6253 int parent_lineno = -1;
6254 int blamed_lineno = -1;
6255 char *line;
6257 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6258 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6259 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6260 return;
6262 while ((line = io_get(&io, '\n', TRUE))) {
6263 if (*line == '@') {
6264 char *pos = strchr(line, '+');
6266 parent_lineno = atoi(line + 4);
6267 if (pos)
6268 blamed_lineno = atoi(pos + 1);
6270 } else if (*line == '+' && parent_lineno != -1) {
6271 if (blame->lineno == blamed_lineno - 1 &&
6272 !strcmp(blame->text, line + 1)) {
6273 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6274 break;
6276 blamed_lineno++;
6280 io_done(&io);
6283 static void
6284 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6286 struct blame_state *state = view->private;
6287 struct blame_history_state *history_state = &state->history_state;
6288 struct blame_commit *commit = blame->commit;
6289 const char *id = parent ? commit->parent_id : commit->id;
6290 const char *filename = parent ? commit->parent_filename : commit->filename;
6292 if (!*id && parent) {
6293 report("The selected commit has no parents");
6294 return;
6297 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6298 report("The selected commit is already displayed");
6299 return;
6302 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6303 report("Failed to save current view state");
6304 return;
6307 string_ncopy(opt_ref, id, sizeof(commit->id));
6308 string_ncopy(opt_file, filename, strlen(filename));
6309 if (parent)
6310 setup_blame_parent_line(view, blame);
6311 opt_goto_line = blame->lineno;
6312 reload_view(view);
6315 static void
6316 blame_go_back(struct view *view)
6318 struct blame_history_state history_state;
6320 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6321 report("Already at start of history");
6322 return;
6325 string_copy(opt_ref, history_state.id);
6326 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6327 opt_goto_line = view->pos.lineno;
6328 reload_view(view);
6331 static enum request
6332 blame_request(struct view *view, enum request request, struct line *line)
6334 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6335 struct blame *blame = line->data;
6337 switch (request) {
6338 case REQ_VIEW_BLAME:
6339 case REQ_PARENT:
6340 if (!check_blame_commit(blame, TRUE))
6341 break;
6342 blame_go_forward(view, blame, request == REQ_PARENT);
6343 break;
6345 case REQ_BACK:
6346 blame_go_back(view);
6347 break;
6349 case REQ_ENTER:
6350 if (!check_blame_commit(blame, FALSE))
6351 break;
6353 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6354 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6355 break;
6357 if (string_rev_is_null(blame->commit->id)) {
6358 struct view *diff = VIEW(REQ_VIEW_DIFF);
6359 const char *diff_parent_argv[] = {
6360 GIT_DIFF_BLAME(encoding_arg,
6361 opt_diff_context_arg,
6362 opt_ignore_space_arg, view->vid)
6364 const char *diff_no_parent_argv[] = {
6365 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6366 opt_diff_context_arg,
6367 opt_ignore_space_arg, view->vid)
6369 const char **diff_index_argv = *blame->commit->parent_id
6370 ? diff_parent_argv : diff_no_parent_argv;
6372 open_argv(view, diff, diff_index_argv, NULL, flags);
6373 if (diff->pipe)
6374 string_copy_rev(diff->ref, NULL_ID);
6375 } else {
6376 open_view(view, REQ_VIEW_DIFF, flags);
6378 break;
6380 default:
6381 return request;
6384 return REQ_NONE;
6387 static bool
6388 blame_grep(struct view *view, struct line *line)
6390 struct blame *blame = line->data;
6391 struct blame_commit *commit = blame->commit;
6392 const char *text[] = {
6393 blame->text,
6394 commit ? commit->title : "",
6395 commit ? commit->id : "",
6396 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6397 commit ? mkdate(&commit->time, opt_date) : "",
6398 NULL
6401 return grep_text(view, text);
6404 static void
6405 blame_select(struct view *view, struct line *line)
6407 struct blame *blame = line->data;
6408 struct blame_commit *commit = blame->commit;
6410 if (!commit)
6411 return;
6413 if (string_rev_is_null(commit->id))
6414 string_ncopy(ref_commit, "HEAD", 4);
6415 else
6416 string_copy_rev(ref_commit, commit->id);
6419 static struct view_ops blame_ops = {
6420 "line",
6421 { "blame" },
6422 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6423 sizeof(struct blame_state),
6424 blame_open,
6425 blame_read,
6426 blame_draw,
6427 blame_request,
6428 blame_grep,
6429 blame_select,
6433 * Branch backend
6436 struct branch {
6437 const struct ident *author; /* Author of the last commit. */
6438 struct time time; /* Date of the last activity. */
6439 char title[128]; /* First line of the commit message. */
6440 const struct ref *ref; /* Name and commit ID information. */
6443 static const struct ref branch_all;
6444 #define BRANCH_ALL_NAME "All branches"
6445 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6447 static const enum sort_field branch_sort_fields[] = {
6448 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6450 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6452 struct branch_state {
6453 char id[SIZEOF_REV];
6454 size_t max_ref_length;
6457 static int
6458 branch_compare(const void *l1, const void *l2)
6460 const struct branch *branch1 = ((const struct line *) l1)->data;
6461 const struct branch *branch2 = ((const struct line *) l2)->data;
6463 if (branch_is_all(branch1))
6464 return -1;
6465 else if (branch_is_all(branch2))
6466 return 1;
6468 switch (get_sort_field(branch_sort_state)) {
6469 case ORDERBY_DATE:
6470 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6472 case ORDERBY_AUTHOR:
6473 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6475 case ORDERBY_NAME:
6476 default:
6477 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6481 static bool
6482 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6484 struct branch_state *state = view->private;
6485 struct branch *branch = line->data;
6486 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6487 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6489 if (draw_lineno(view, lineno))
6490 return TRUE;
6492 if (draw_date(view, &branch->time))
6493 return TRUE;
6495 if (draw_author(view, branch->author))
6496 return TRUE;
6498 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6499 return TRUE;
6501 if (draw_id(view, branch->ref->id))
6502 return TRUE;
6504 draw_text(view, LINE_DEFAULT, branch->title);
6505 return TRUE;
6508 static enum request
6509 branch_request(struct view *view, enum request request, struct line *line)
6511 struct branch *branch = line->data;
6513 switch (request) {
6514 case REQ_REFRESH:
6515 load_refs(TRUE);
6516 refresh_view(view);
6517 return REQ_NONE;
6519 case REQ_TOGGLE_SORT_FIELD:
6520 case REQ_TOGGLE_SORT_ORDER:
6521 sort_view(view, request, &branch_sort_state, branch_compare);
6522 return REQ_NONE;
6524 case REQ_ENTER:
6526 const struct ref *ref = branch->ref;
6527 const char *all_branches_argv[] = {
6528 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6530 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6532 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6533 return REQ_NONE;
6535 case REQ_JUMP_COMMIT:
6537 int lineno;
6539 for (lineno = 0; lineno < view->lines; lineno++) {
6540 struct branch *branch = view->line[lineno].data;
6542 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6543 select_view_line(view, lineno);
6544 report_clear();
6545 return REQ_NONE;
6549 default:
6550 return request;
6554 static bool
6555 branch_read(struct view *view, char *line)
6557 struct branch_state *state = view->private;
6558 const char *title = NULL;
6559 const struct ident *author = NULL;
6560 struct time time = {};
6561 size_t i;
6563 if (!line)
6564 return TRUE;
6566 switch (get_line_type(line)) {
6567 case LINE_COMMIT:
6568 string_copy_rev_from_commit_line(state->id, line);
6569 return TRUE;
6571 case LINE_AUTHOR:
6572 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6573 break;
6575 default:
6576 title = line + STRING_SIZE("title ");
6579 for (i = 0; i < view->lines; i++) {
6580 struct branch *branch = view->line[i].data;
6582 if (strcmp(branch->ref->id, state->id))
6583 continue;
6585 if (author) {
6586 branch->author = author;
6587 branch->time = time;
6590 if (title)
6591 string_expand(branch->title, sizeof(branch->title), title, 1);
6593 view->line[i].dirty = TRUE;
6596 return TRUE;
6599 static bool
6600 branch_open_visitor(void *data, const struct ref *ref)
6602 struct view *view = data;
6603 struct branch_state *state = view->private;
6604 struct branch *branch;
6605 bool is_all = ref == &branch_all;
6606 size_t ref_length;
6608 if (ref->tag || ref->ltag)
6609 return TRUE;
6611 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6612 return FALSE;
6614 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6615 if (ref_length > state->max_ref_length)
6616 state->max_ref_length = ref_length;
6618 branch->ref = ref;
6619 return TRUE;
6622 static bool
6623 branch_open(struct view *view, enum open_flags flags)
6625 const char *branch_log[] = {
6626 "git", "log", encoding_arg, "--no-color", "--date=raw",
6627 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6628 "--all", "--simplify-by-decoration", NULL
6631 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6632 report("Failed to load branch data");
6633 return FALSE;
6636 branch_open_visitor(view, &branch_all);
6637 foreach_ref(branch_open_visitor, view);
6639 return TRUE;
6642 static bool
6643 branch_grep(struct view *view, struct line *line)
6645 struct branch *branch = line->data;
6646 const char *text[] = {
6647 branch->ref->name,
6648 mkauthor(branch->author, opt_author_width, opt_author),
6649 NULL
6652 return grep_text(view, text);
6655 static void
6656 branch_select(struct view *view, struct line *line)
6658 struct branch *branch = line->data;
6660 if (branch_is_all(branch)) {
6661 string_copy(view->ref, BRANCH_ALL_NAME);
6662 return;
6664 string_copy_rev(view->ref, branch->ref->id);
6665 string_copy_rev(ref_commit, branch->ref->id);
6666 string_copy_rev(ref_head, branch->ref->id);
6667 string_copy_rev(ref_branch, branch->ref->name);
6670 static struct view_ops branch_ops = {
6671 "branch",
6672 { "branch" },
6673 VIEW_REFRESH,
6674 sizeof(struct branch_state),
6675 branch_open,
6676 branch_read,
6677 branch_draw,
6678 branch_request,
6679 branch_grep,
6680 branch_select,
6684 * Status backend
6687 struct status {
6688 char status;
6689 struct {
6690 mode_t mode;
6691 char rev[SIZEOF_REV];
6692 char name[SIZEOF_STR];
6693 } old;
6694 struct {
6695 mode_t mode;
6696 char rev[SIZEOF_REV];
6697 char name[SIZEOF_STR];
6698 } new;
6701 static char status_onbranch[SIZEOF_STR];
6702 static struct status stage_status;
6703 static enum line_type stage_line_type;
6705 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6707 /* This should work even for the "On branch" line. */
6708 static inline bool
6709 status_has_none(struct view *view, struct line *line)
6711 return view_has_line(view, line) && !line[1].data;
6714 /* Get fields from the diff line:
6715 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6717 static inline bool
6718 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6720 const char *old_mode = buf + 1;
6721 const char *new_mode = buf + 8;
6722 const char *old_rev = buf + 15;
6723 const char *new_rev = buf + 56;
6724 const char *status = buf + 97;
6726 if (bufsize < 98 ||
6727 old_mode[-1] != ':' ||
6728 new_mode[-1] != ' ' ||
6729 old_rev[-1] != ' ' ||
6730 new_rev[-1] != ' ' ||
6731 status[-1] != ' ')
6732 return FALSE;
6734 file->status = *status;
6736 string_copy_rev(file->old.rev, old_rev);
6737 string_copy_rev(file->new.rev, new_rev);
6739 file->old.mode = strtoul(old_mode, NULL, 8);
6740 file->new.mode = strtoul(new_mode, NULL, 8);
6742 file->old.name[0] = file->new.name[0] = 0;
6744 return TRUE;
6747 static bool
6748 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6750 struct status *unmerged = NULL;
6751 char *buf;
6752 struct io io;
6754 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6755 return FALSE;
6757 add_line_nodata(view, type);
6759 while ((buf = io_get(&io, 0, TRUE))) {
6760 struct status *file = unmerged;
6762 if (!file) {
6763 if (!add_line_alloc(view, &file, type, 0, FALSE))
6764 goto error_out;
6767 /* Parse diff info part. */
6768 if (status) {
6769 file->status = status;
6770 if (status == 'A')
6771 string_copy(file->old.rev, NULL_ID);
6773 } else if (!file->status || file == unmerged) {
6774 if (!status_get_diff(file, buf, strlen(buf)))
6775 goto error_out;
6777 buf = io_get(&io, 0, TRUE);
6778 if (!buf)
6779 break;
6781 /* Collapse all modified entries that follow an
6782 * associated unmerged entry. */
6783 if (unmerged == file) {
6784 unmerged->status = 'U';
6785 unmerged = NULL;
6786 } else if (file->status == 'U') {
6787 unmerged = file;
6791 /* Grab the old name for rename/copy. */
6792 if (!*file->old.name &&
6793 (file->status == 'R' || file->status == 'C')) {
6794 string_ncopy(file->old.name, buf, strlen(buf));
6796 buf = io_get(&io, 0, TRUE);
6797 if (!buf)
6798 break;
6801 /* git-ls-files just delivers a NUL separated list of
6802 * file names similar to the second half of the
6803 * git-diff-* output. */
6804 string_ncopy(file->new.name, buf, strlen(buf));
6805 if (!*file->old.name)
6806 string_copy(file->old.name, file->new.name);
6807 file = NULL;
6810 if (io_error(&io)) {
6811 error_out:
6812 io_done(&io);
6813 return FALSE;
6816 if (!view->line[view->lines - 1].data)
6817 add_line_nodata(view, LINE_STAT_NONE);
6819 io_done(&io);
6820 return TRUE;
6823 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6824 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6826 static const char *status_list_other_argv[] = {
6827 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6830 static const char *status_list_no_head_argv[] = {
6831 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6834 static const char *update_index_argv[] = {
6835 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6838 /* Restore the previous line number to stay in the context or select a
6839 * line with something that can be updated. */
6840 static void
6841 status_restore(struct view *view)
6843 if (!check_position(&view->prev_pos))
6844 return;
6846 if (view->prev_pos.lineno >= view->lines)
6847 view->prev_pos.lineno = view->lines - 1;
6848 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6849 view->prev_pos.lineno++;
6850 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6851 view->prev_pos.lineno--;
6853 /* If the above fails, always skip the "On branch" line. */
6854 if (view->prev_pos.lineno < view->lines)
6855 view->pos.lineno = view->prev_pos.lineno;
6856 else
6857 view->pos.lineno = 1;
6859 if (view->prev_pos.offset > view->pos.lineno)
6860 view->pos.offset = view->pos.lineno;
6861 else if (view->prev_pos.offset < view->lines)
6862 view->pos.offset = view->prev_pos.offset;
6864 clear_position(&view->prev_pos);
6867 static void
6868 status_update_onbranch(void)
6870 static const char *paths[][2] = {
6871 { "rebase-apply/rebasing", "Rebasing" },
6872 { "rebase-apply/applying", "Applying mailbox" },
6873 { "rebase-apply/", "Rebasing mailbox" },
6874 { "rebase-merge/interactive", "Interactive rebase" },
6875 { "rebase-merge/", "Rebase merge" },
6876 { "MERGE_HEAD", "Merging" },
6877 { "BISECT_LOG", "Bisecting" },
6878 { "HEAD", "On branch" },
6880 char buf[SIZEOF_STR];
6881 struct stat stat;
6882 int i;
6884 if (is_initial_commit()) {
6885 string_copy(status_onbranch, "Initial commit");
6886 return;
6889 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6890 char *head = opt_head;
6892 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6893 lstat(buf, &stat) < 0)
6894 continue;
6896 if (!*opt_head) {
6897 struct io io;
6899 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6900 io_read_buf(&io, buf, sizeof(buf))) {
6901 head = buf;
6902 if (!prefixcmp(head, "refs/heads/"))
6903 head += STRING_SIZE("refs/heads/");
6907 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6908 string_copy(status_onbranch, opt_head);
6909 return;
6912 string_copy(status_onbranch, "Not currently on any branch");
6915 /* First parse staged info using git-diff-index(1), then parse unstaged
6916 * info using git-diff-files(1), and finally untracked files using
6917 * git-ls-files(1). */
6918 static bool
6919 status_open(struct view *view, enum open_flags flags)
6921 const char **staged_argv = is_initial_commit() ?
6922 status_list_no_head_argv : status_diff_index_argv;
6923 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6925 if (opt_is_inside_work_tree == FALSE) {
6926 report("The status view requires a working tree");
6927 return FALSE;
6930 reset_view(view);
6932 add_line_nodata(view, LINE_STAT_HEAD);
6933 status_update_onbranch();
6935 io_run_bg(update_index_argv);
6937 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6938 opt_untracked_dirs_content ? NULL : "--directory";
6940 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6941 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6942 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6943 report("Failed to load status data");
6944 return FALSE;
6947 /* Restore the exact position or use the specialized restore
6948 * mode? */
6949 status_restore(view);
6950 return TRUE;
6953 static bool
6954 status_draw(struct view *view, struct line *line, unsigned int lineno)
6956 struct status *status = line->data;
6957 enum line_type type;
6958 const char *text;
6960 if (!status) {
6961 switch (line->type) {
6962 case LINE_STAT_STAGED:
6963 type = LINE_STAT_SECTION;
6964 text = "Changes to be committed:";
6965 break;
6967 case LINE_STAT_UNSTAGED:
6968 type = LINE_STAT_SECTION;
6969 text = "Changed but not updated:";
6970 break;
6972 case LINE_STAT_UNTRACKED:
6973 type = LINE_STAT_SECTION;
6974 text = "Untracked files:";
6975 break;
6977 case LINE_STAT_NONE:
6978 type = LINE_DEFAULT;
6979 text = " (no files)";
6980 break;
6982 case LINE_STAT_HEAD:
6983 type = LINE_STAT_HEAD;
6984 text = status_onbranch;
6985 break;
6987 default:
6988 return FALSE;
6990 } else {
6991 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6993 buf[0] = status->status;
6994 if (draw_text(view, line->type, buf))
6995 return TRUE;
6996 type = LINE_DEFAULT;
6997 text = status->new.name;
7000 draw_text(view, type, text);
7001 return TRUE;
7004 static enum request
7005 status_enter(struct view *view, struct line *line)
7007 struct status *status = line->data;
7008 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7010 if (line->type == LINE_STAT_NONE ||
7011 (!status && line[1].type == LINE_STAT_NONE)) {
7012 report("No file to diff");
7013 return REQ_NONE;
7016 switch (line->type) {
7017 case LINE_STAT_STAGED:
7018 case LINE_STAT_UNSTAGED:
7019 break;
7021 case LINE_STAT_UNTRACKED:
7022 if (!status) {
7023 report("No file to show");
7024 return REQ_NONE;
7027 if (!suffixcmp(status->new.name, -1, "/")) {
7028 report("Cannot display a directory");
7029 return REQ_NONE;
7031 break;
7033 case LINE_STAT_HEAD:
7034 return REQ_NONE;
7036 default:
7037 die("line type %d not handled in switch", line->type);
7040 if (status) {
7041 stage_status = *status;
7042 } else {
7043 memset(&stage_status, 0, sizeof(stage_status));
7046 stage_line_type = line->type;
7048 open_view(view, REQ_VIEW_STAGE, flags);
7049 return REQ_NONE;
7052 static bool
7053 status_exists(struct view *view, struct status *status, enum line_type type)
7055 unsigned long lineno;
7057 for (lineno = 0; lineno < view->lines; lineno++) {
7058 struct line *line = &view->line[lineno];
7059 struct status *pos = line->data;
7061 if (line->type != type)
7062 continue;
7063 if (!pos && (!status || !status->status) && line[1].data) {
7064 select_view_line(view, lineno);
7065 return TRUE;
7067 if (pos && !strcmp(status->new.name, pos->new.name)) {
7068 select_view_line(view, lineno);
7069 return TRUE;
7073 return FALSE;
7077 static bool
7078 status_update_prepare(struct io *io, enum line_type type)
7080 const char *staged_argv[] = {
7081 "git", "update-index", "-z", "--index-info", NULL
7083 const char *others_argv[] = {
7084 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
7087 switch (type) {
7088 case LINE_STAT_STAGED:
7089 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
7091 case LINE_STAT_UNSTAGED:
7092 case LINE_STAT_UNTRACKED:
7093 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
7095 default:
7096 die("line type %d not handled in switch", type);
7097 return FALSE;
7101 static bool
7102 status_update_write(struct io *io, struct status *status, enum line_type type)
7104 switch (type) {
7105 case LINE_STAT_STAGED:
7106 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
7107 status->old.rev, status->old.name, 0);
7109 case LINE_STAT_UNSTAGED:
7110 case LINE_STAT_UNTRACKED:
7111 return io_printf(io, "%s%c", status->new.name, 0);
7113 default:
7114 die("line type %d not handled in switch", type);
7115 return FALSE;
7119 static bool
7120 status_update_file(struct status *status, enum line_type type)
7122 struct io io;
7123 bool result;
7125 if (!status_update_prepare(&io, type))
7126 return FALSE;
7128 result = status_update_write(&io, status, type);
7129 return io_done(&io) && result;
7132 static bool
7133 status_update_files(struct view *view, struct line *line)
7135 char buf[sizeof(view->ref)];
7136 struct io io;
7137 bool result = TRUE;
7138 struct line *pos;
7139 int files = 0;
7140 int file, done;
7141 int cursor_y = -1, cursor_x = -1;
7143 if (!status_update_prepare(&io, line->type))
7144 return FALSE;
7146 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7147 files++;
7149 string_copy(buf, view->ref);
7150 getsyx(cursor_y, cursor_x);
7151 for (file = 0, done = 5; result && file < files; line++, file++) {
7152 int almost_done = file * 100 / files;
7154 if (almost_done > done) {
7155 done = almost_done;
7156 string_format(view->ref, "updating file %u of %u (%d%% done)",
7157 file, files, done);
7158 update_view_title(view);
7159 setsyx(cursor_y, cursor_x);
7160 doupdate();
7162 result = status_update_write(&io, line->data, line->type);
7164 string_copy(view->ref, buf);
7166 return io_done(&io) && result;
7169 static bool
7170 status_update(struct view *view)
7172 struct line *line = &view->line[view->pos.lineno];
7174 assert(view->lines);
7176 if (!line->data) {
7177 if (status_has_none(view, line)) {
7178 report("Nothing to update");
7179 return FALSE;
7182 if (!status_update_files(view, line + 1)) {
7183 report("Failed to update file status");
7184 return FALSE;
7187 } else if (!status_update_file(line->data, line->type)) {
7188 report("Failed to update file status");
7189 return FALSE;
7192 return TRUE;
7195 static bool
7196 status_revert(struct status *status, enum line_type type, bool has_none)
7198 if (!status || type != LINE_STAT_UNSTAGED) {
7199 if (type == LINE_STAT_STAGED) {
7200 report("Cannot revert changes to staged files");
7201 } else if (type == LINE_STAT_UNTRACKED) {
7202 report("Cannot revert changes to untracked files");
7203 } else if (has_none) {
7204 report("Nothing to revert");
7205 } else {
7206 report("Cannot revert changes to multiple files");
7209 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7210 char mode[10] = "100644";
7211 const char *reset_argv[] = {
7212 "git", "update-index", "--cacheinfo", mode,
7213 status->old.rev, status->old.name, NULL
7215 const char *checkout_argv[] = {
7216 "git", "checkout", "--", status->old.name, NULL
7219 if (status->status == 'U') {
7220 string_format(mode, "%5o", status->old.mode);
7222 if (status->old.mode == 0 && status->new.mode == 0) {
7223 reset_argv[2] = "--force-remove";
7224 reset_argv[3] = status->old.name;
7225 reset_argv[4] = NULL;
7228 if (!io_run_fg(reset_argv, opt_cdup))
7229 return FALSE;
7230 if (status->old.mode == 0 && status->new.mode == 0)
7231 return TRUE;
7234 return io_run_fg(checkout_argv, opt_cdup);
7237 return FALSE;
7240 static enum request
7241 status_request(struct view *view, enum request request, struct line *line)
7243 struct status *status = line->data;
7245 switch (request) {
7246 case REQ_STATUS_UPDATE:
7247 if (!status_update(view))
7248 return REQ_NONE;
7249 break;
7251 case REQ_STATUS_REVERT:
7252 if (!status_revert(status, line->type, status_has_none(view, line)))
7253 return REQ_NONE;
7254 break;
7256 case REQ_STATUS_MERGE:
7257 if (!status || status->status != 'U') {
7258 report("Merging only possible for files with unmerged status ('U').");
7259 return REQ_NONE;
7261 open_mergetool(status->new.name);
7262 break;
7264 case REQ_EDIT:
7265 if (!status)
7266 return request;
7267 if (status->status == 'D') {
7268 report("File has been deleted.");
7269 return REQ_NONE;
7272 open_editor(status->new.name, 0);
7273 break;
7275 case REQ_VIEW_BLAME:
7276 if (line->type == LINE_STAT_UNTRACKED || !status) {
7277 report("Nothing to blame here");
7278 return REQ_NONE;
7280 if (status)
7281 opt_ref[0] = 0;
7282 return request;
7284 case REQ_ENTER:
7285 /* After returning the status view has been split to
7286 * show the stage view. No further reloading is
7287 * necessary. */
7288 return status_enter(view, line);
7290 case REQ_REFRESH:
7291 /* Load the current branch information and then the view. */
7292 load_refs(TRUE);
7293 break;
7295 default:
7296 return request;
7299 refresh_view(view);
7301 return REQ_NONE;
7304 static bool
7305 status_stage_info_(char *buf, size_t bufsize,
7306 enum line_type type, struct status *status)
7308 const char *file = status ? status->new.name : "";
7309 const char *info;
7311 switch (type) {
7312 case LINE_STAT_STAGED:
7313 if (status && status->status)
7314 info = "Staged changes to %s";
7315 else
7316 info = "Staged changes";
7317 break;
7319 case LINE_STAT_UNSTAGED:
7320 if (status && status->status)
7321 info = "Unstaged changes to %s";
7322 else
7323 info = "Unstaged changes";
7324 break;
7326 case LINE_STAT_UNTRACKED:
7327 info = "Untracked file %s";
7328 break;
7330 case LINE_STAT_HEAD:
7331 default:
7332 info = "";
7335 return string_nformat(buf, bufsize, NULL, info, file);
7337 #define status_stage_info(buf, type, status) \
7338 status_stage_info_(buf, sizeof(buf), type, status)
7340 static void
7341 status_select(struct view *view, struct line *line)
7343 struct status *status = line->data;
7344 char file[SIZEOF_STR] = "all files";
7345 const char *text;
7346 const char *key;
7348 if (status && !string_format(file, "'%s'", status->new.name))
7349 return;
7351 if (!status && line[1].type == LINE_STAT_NONE)
7352 line++;
7354 switch (line->type) {
7355 case LINE_STAT_STAGED:
7356 text = "Press %s to unstage %s for commit";
7357 break;
7359 case LINE_STAT_UNSTAGED:
7360 text = "Press %s to stage %s for commit";
7361 break;
7363 case LINE_STAT_UNTRACKED:
7364 text = "Press %s to stage %s for addition";
7365 break;
7367 case LINE_STAT_HEAD:
7368 case LINE_STAT_NONE:
7369 text = "Nothing to update";
7370 break;
7372 default:
7373 die("line type %d not handled in switch", line->type);
7376 if (status && status->status == 'U') {
7377 text = "Press %s to resolve conflict in %s";
7378 key = get_view_key(view, REQ_STATUS_MERGE);
7380 } else {
7381 key = get_view_key(view, REQ_STATUS_UPDATE);
7384 string_format(view->ref, text, key, file);
7385 status_stage_info(ref_status, line->type, status);
7386 if (status)
7387 string_copy(opt_file, status->new.name);
7390 static bool
7391 status_grep(struct view *view, struct line *line)
7393 struct status *status = line->data;
7395 if (status) {
7396 const char buf[2] = { status->status, 0 };
7397 const char *text[] = { status->new.name, buf, NULL };
7399 return grep_text(view, text);
7402 return FALSE;
7405 static struct view_ops status_ops = {
7406 "file",
7407 { "status" },
7408 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE | VIEW_REFRESH,
7410 status_open,
7411 NULL,
7412 status_draw,
7413 status_request,
7414 status_grep,
7415 status_select,
7419 struct stage_state {
7420 struct diff_state diff;
7421 size_t chunks;
7422 int *chunk;
7425 static bool
7426 stage_diff_write(struct io *io, struct line *line, struct line *end)
7428 while (line < end) {
7429 if (!io_write(io, line->data, strlen(line->data)) ||
7430 !io_write(io, "\n", 1))
7431 return FALSE;
7432 line++;
7433 if (line->type == LINE_DIFF_CHUNK ||
7434 line->type == LINE_DIFF_HEADER)
7435 break;
7438 return TRUE;
7441 static bool
7442 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7444 const char *apply_argv[SIZEOF_ARG] = {
7445 "git", "apply", "--whitespace=nowarn", NULL
7447 struct line *diff_hdr;
7448 struct io io;
7449 int argc = 3;
7451 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7452 if (!diff_hdr)
7453 return FALSE;
7455 if (!revert)
7456 apply_argv[argc++] = "--cached";
7457 if (line != NULL)
7458 apply_argv[argc++] = "--unidiff-zero";
7459 if (revert || stage_line_type == LINE_STAT_STAGED)
7460 apply_argv[argc++] = "-R";
7461 apply_argv[argc++] = "-";
7462 apply_argv[argc++] = NULL;
7463 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7464 return FALSE;
7466 if (line != NULL) {
7467 unsigned long lineno = 0;
7468 struct line *context = chunk + 1;
7469 const char *markers[] = {
7470 line->type == LINE_DIFF_DEL ? "" : ",0",
7471 line->type == LINE_DIFF_DEL ? ",0" : "",
7474 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7476 while (context < line) {
7477 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7478 break;
7479 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7480 lineno++;
7482 context++;
7485 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7486 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
7487 lineno, markers[0], lineno, markers[1]) ||
7488 !stage_diff_write(&io, line, line + 1)) {
7489 chunk = NULL;
7491 } else {
7492 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7493 !stage_diff_write(&io, chunk, view->line + view->lines))
7494 chunk = NULL;
7497 io_done(&io);
7499 return chunk ? TRUE : FALSE;
7502 static bool
7503 stage_update(struct view *view, struct line *line, bool single)
7505 struct line *chunk = NULL;
7507 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7508 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7510 if (chunk) {
7511 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7512 report("Failed to apply chunk");
7513 return FALSE;
7516 } else if (!stage_status.status) {
7517 view = view->parent;
7519 for (line = view->line; view_has_line(view, line); line++)
7520 if (line->type == stage_line_type)
7521 break;
7523 if (!status_update_files(view, line + 1)) {
7524 report("Failed to update files");
7525 return FALSE;
7528 } else if (!status_update_file(&stage_status, stage_line_type)) {
7529 report("Failed to update file");
7530 return FALSE;
7533 return TRUE;
7536 static bool
7537 stage_revert(struct view *view, struct line *line)
7539 struct line *chunk = NULL;
7541 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7542 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7544 if (chunk) {
7545 if (!prompt_yesno("Are you sure you want to revert changes?"))
7546 return FALSE;
7548 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7549 report("Failed to revert chunk");
7550 return FALSE;
7552 return TRUE;
7554 } else {
7555 return status_revert(stage_status.status ? &stage_status : NULL,
7556 stage_line_type, FALSE);
7561 static void
7562 stage_next(struct view *view, struct line *line)
7564 struct stage_state *state = view->private;
7565 int i;
7567 if (!state->chunks) {
7568 for (line = view->line; view_has_line(view, line); line++) {
7569 if (line->type != LINE_DIFF_CHUNK)
7570 continue;
7572 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7573 report("Allocation failure");
7574 return;
7577 state->chunk[state->chunks++] = line - view->line;
7581 for (i = 0; i < state->chunks; i++) {
7582 if (state->chunk[i] > view->pos.lineno) {
7583 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7584 report("Chunk %d of %zd", i + 1, state->chunks);
7585 return;
7589 report("No next chunk found");
7592 static struct line *
7593 stage_insert_chunk(struct view *view, struct chunk_header *header,
7594 struct line *from, struct line *to, struct line *last_unchanged_line)
7596 char buf[SIZEOF_STR];
7597 char *chunk_line;
7598 unsigned long from_lineno = last_unchanged_line - view->line;
7599 unsigned long to_lineno = to - view->line;
7600 unsigned long after_lineno = to_lineno;
7602 if (!string_format(buf, "@@ -%lu,%lu +%lu,%lu @@",
7603 header->old.position, header->old.lines,
7604 header->new.position, header->new.lines))
7605 return NULL;
7607 chunk_line = strdup(buf);
7608 if (!chunk_line)
7609 return NULL;
7611 free(from->data);
7612 from->data = chunk_line;
7614 if (!to)
7615 return from;
7617 if (!add_line_at(view, after_lineno++, buf, LINE_DIFF_CHUNK, strlen(buf) + 1, FALSE))
7618 return NULL;
7620 while (from_lineno < to_lineno) {
7621 struct line *line = &view->line[from_lineno++];
7623 if (!add_line_at(view, after_lineno++, line->data, line->type, strlen(line->data) + 1, FALSE))
7624 return FALSE;
7627 return view->line + after_lineno;
7630 static void
7631 stage_split_chunk(struct view *view, struct line *chunk_start)
7633 struct chunk_header header;
7634 struct line *last_changed_line = NULL, *last_unchanged_line = NULL, *pos;
7635 int chunks = 0;
7637 if (!chunk_start || !parse_chunk_header(&header, chunk_start->data)) {
7638 report("Failed to parse chunk header");
7639 return;
7642 header.old.lines = header.new.lines = 0;
7644 for (pos = chunk_start + 1; view_has_line(view, pos); pos++) {
7645 const char *chunk_line = pos->data;
7647 if (*chunk_line == '@' || *chunk_line == '\\')
7648 break;
7650 if (*chunk_line == ' ') {
7651 header.old.lines++;
7652 header.new.lines++;
7653 if (last_unchanged_line < last_changed_line)
7654 last_unchanged_line = pos;
7655 continue;
7658 if (last_changed_line && last_changed_line < last_unchanged_line) {
7659 unsigned long chunk_start_lineno = pos - view->line;
7660 unsigned long diff = pos - last_unchanged_line;
7662 pos = stage_insert_chunk(view, &header, chunk_start, pos, last_unchanged_line);
7664 header.old.position += header.old.lines - diff;
7665 header.new.position += header.new.lines - diff;
7666 header.old.lines = header.new.lines = diff;
7668 chunk_start = view->line + chunk_start_lineno;
7669 last_changed_line = last_unchanged_line = NULL;
7670 chunks++;
7673 if (*chunk_line == '-') {
7674 header.old.lines++;
7675 last_changed_line = pos;
7676 } else if (*chunk_line == '+') {
7677 header.new.lines++;
7678 last_changed_line = pos;
7682 if (chunks) {
7683 stage_insert_chunk(view, &header, chunk_start, NULL, NULL);
7684 redraw_view(view);
7685 report("Split the chunk in %d", chunks + 1);
7686 } else {
7687 report("The chunk cannot be split");
7691 static enum request
7692 stage_request(struct view *view, enum request request, struct line *line)
7694 switch (request) {
7695 case REQ_STATUS_UPDATE:
7696 if (!stage_update(view, line, FALSE))
7697 return REQ_NONE;
7698 break;
7700 case REQ_STATUS_REVERT:
7701 if (!stage_revert(view, line))
7702 return REQ_NONE;
7703 break;
7705 case REQ_STAGE_UPDATE_LINE:
7706 if (stage_line_type == LINE_STAT_UNTRACKED ||
7707 stage_status.status == 'A') {
7708 report("Staging single lines is not supported for new files");
7709 return REQ_NONE;
7711 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7712 report("Please select a change to stage");
7713 return REQ_NONE;
7715 if (!stage_update(view, line, TRUE))
7716 return REQ_NONE;
7717 break;
7719 case REQ_STAGE_NEXT:
7720 if (stage_line_type == LINE_STAT_UNTRACKED) {
7721 report("File is untracked; press %s to add",
7722 get_view_key(view, REQ_STATUS_UPDATE));
7723 return REQ_NONE;
7725 stage_next(view, line);
7726 return REQ_NONE;
7728 case REQ_STAGE_SPLIT_CHUNK:
7729 if (stage_line_type == LINE_STAT_UNTRACKED ||
7730 !(line = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK))) {
7731 report("No chunks to split in sight");
7732 return REQ_NONE;
7734 stage_split_chunk(view, line);
7735 return REQ_NONE;
7737 case REQ_EDIT:
7738 if (!stage_status.new.name[0])
7739 return diff_common_edit(view, request, line);
7741 if (stage_status.status == 'D') {
7742 report("File has been deleted.");
7743 return REQ_NONE;
7746 if (stage_line_type == LINE_STAT_UNTRACKED) {
7747 open_editor(stage_status.new.name, (line - view->line) + 1);
7748 } else {
7749 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7751 break;
7753 case REQ_REFRESH:
7754 /* Reload everything(including current branch information) ... */
7755 load_refs(TRUE);
7756 break;
7758 case REQ_VIEW_BLAME:
7759 if (stage_line_type == LINE_STAT_UNTRACKED) {
7760 report("Nothing to blame here");
7761 return REQ_NONE;
7764 if (stage_status.new.name[0]) {
7765 string_copy(opt_file, stage_status.new.name);
7766 } else {
7767 const char *file = diff_get_pathname(view, line);
7769 if (file)
7770 string_copy(opt_file, file);
7773 opt_ref[0] = 0;
7774 opt_goto_line = diff_get_lineno(view, line);
7775 if (opt_goto_line > 0)
7776 opt_goto_line--;
7777 return request;
7779 case REQ_ENTER:
7780 return diff_common_enter(view, request, line);
7782 case REQ_DIFF_CONTEXT_UP:
7783 case REQ_DIFF_CONTEXT_DOWN:
7784 if (!update_diff_context(request))
7785 return REQ_NONE;
7786 break;
7788 default:
7789 return request;
7792 refresh_view(view->parent);
7794 /* Check whether the staged entry still exists, and close the
7795 * stage view if it doesn't. */
7796 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7797 status_restore(view->parent);
7798 return REQ_VIEW_CLOSE;
7801 refresh_view(view);
7803 return REQ_NONE;
7806 static bool
7807 stage_open(struct view *view, enum open_flags flags)
7809 static const char *no_head_diff_argv[] = {
7810 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7811 stage_status.new.name)
7813 static const char *index_show_argv[] = {
7814 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7815 stage_status.old.name, stage_status.new.name)
7817 static const char *files_show_argv[] = {
7818 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7819 stage_status.old.name, stage_status.new.name)
7821 /* Diffs for unmerged entries are empty when passing the new
7822 * path, so leave out the new path. */
7823 static const char *files_unmerged_argv[] = {
7824 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7825 opt_diff_context_arg, opt_ignore_space_arg, "--",
7826 stage_status.old.name, NULL
7828 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7829 const char **argv = NULL;
7831 if (!stage_line_type) {
7832 report("No stage content, press %s to open the status view and choose file",
7833 get_view_key(view, REQ_VIEW_STATUS));
7834 return FALSE;
7837 view->encoding = NULL;
7839 switch (stage_line_type) {
7840 case LINE_STAT_STAGED:
7841 if (is_initial_commit()) {
7842 argv = no_head_diff_argv;
7843 } else {
7844 argv = index_show_argv;
7846 break;
7848 case LINE_STAT_UNSTAGED:
7849 if (stage_status.status != 'U')
7850 argv = files_show_argv;
7851 else
7852 argv = files_unmerged_argv;
7853 break;
7855 case LINE_STAT_UNTRACKED:
7856 argv = file_argv;
7857 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7858 break;
7860 case LINE_STAT_HEAD:
7861 default:
7862 die("line type %d not handled in switch", stage_line_type);
7865 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7866 || !argv_copy(&view->argv, argv)) {
7867 report("Failed to open staged view");
7868 return FALSE;
7871 view->vid[0] = 0;
7872 view->dir = opt_cdup;
7873 return begin_update(view, NULL, NULL, flags);
7876 static bool
7877 stage_read(struct view *view, char *data)
7879 struct stage_state *state = view->private;
7881 if (stage_line_type == LINE_STAT_UNTRACKED)
7882 return pager_common_read(view, data, LINE_DEFAULT);
7884 if (data && diff_common_read(view, data, &state->diff))
7885 return TRUE;
7887 return pager_read(view, data);
7890 static struct view_ops stage_ops = {
7891 "line",
7892 { "stage" },
7893 VIEW_DIFF_LIKE | VIEW_REFRESH,
7894 sizeof(struct stage_state),
7895 stage_open,
7896 stage_read,
7897 diff_common_draw,
7898 stage_request,
7899 pager_grep,
7900 pager_select,
7905 * Revision graph
7908 static const enum line_type graph_colors[] = {
7909 LINE_PALETTE_0,
7910 LINE_PALETTE_1,
7911 LINE_PALETTE_2,
7912 LINE_PALETTE_3,
7913 LINE_PALETTE_4,
7914 LINE_PALETTE_5,
7915 LINE_PALETTE_6,
7918 static enum line_type get_graph_color(struct graph_symbol *symbol)
7920 if (symbol->commit)
7921 return LINE_GRAPH_COMMIT;
7922 assert(symbol->color < ARRAY_SIZE(graph_colors));
7923 return graph_colors[symbol->color];
7926 static bool
7927 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7929 const char *chars = graph_symbol_to_utf8(symbol);
7931 return draw_text(view, color, chars + !!first);
7934 static bool
7935 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7937 const char *chars = graph_symbol_to_ascii(symbol);
7939 return draw_text(view, color, chars + !!first);
7942 static bool
7943 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7945 const chtype *chars = graph_symbol_to_chtype(symbol);
7947 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7950 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7952 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7954 static const draw_graph_fn fns[] = {
7955 draw_graph_ascii,
7956 draw_graph_chtype,
7957 draw_graph_utf8
7959 draw_graph_fn fn = fns[opt_line_graphics];
7960 int i;
7962 for (i = 0; i < canvas->size; i++) {
7963 struct graph_symbol *symbol = &canvas->symbols[i];
7964 enum line_type color = get_graph_color(symbol);
7966 if (fn(view, symbol, color, i == 0))
7967 return TRUE;
7970 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7974 * Main view backend
7977 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7979 struct commit {
7980 char id[SIZEOF_REV]; /* SHA1 ID. */
7981 const struct ident *author; /* Author of the commit. */
7982 struct time time; /* Date from the author ident. */
7983 struct graph_canvas graph; /* Ancestry chain graphics. */
7984 char title[1]; /* First line of the commit message. */
7987 struct main_state {
7988 struct graph graph;
7989 struct commit current;
7990 char **reflog;
7991 size_t reflogs;
7992 int reflog_width;
7993 char reflogmsg[SIZEOF_STR / 2];
7994 bool in_header;
7995 bool added_changes_commits;
7996 bool with_graph;
7999 static void
8000 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
8002 struct main_state *state = view->private;
8004 string_copy_rev(commit->id, ids);
8005 if (state->with_graph)
8006 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
8009 static struct commit *
8010 main_add_commit(struct view *view, enum line_type type, struct commit *template,
8011 const char *title, bool custom)
8013 struct main_state *state = view->private;
8014 size_t titlelen = strlen(title);
8015 struct commit *commit;
8016 char buf[SIZEOF_STR / 2];
8018 /* FIXME: More graceful handling of titles; append "..." to
8019 * shortened titles, etc. */
8020 string_expand(buf, sizeof(buf), title, 1);
8021 title = buf;
8022 titlelen = strlen(title);
8024 if (!add_line_alloc(view, &commit, type, titlelen, custom))
8025 return NULL;
8027 *commit = *template;
8028 strncpy(commit->title, title, titlelen);
8029 state->graph.canvas = &commit->graph;
8030 memset(template, 0, sizeof(*template));
8031 state->reflogmsg[0] = 0;
8032 return commit;
8035 static inline void
8036 main_flush_commit(struct view *view, struct commit *commit)
8038 if (*commit->id)
8039 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
8042 static bool
8043 main_has_changes(const char *argv[])
8045 struct io io;
8047 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
8048 return FALSE;
8049 io_done(&io);
8050 return io.status == 1;
8053 static void
8054 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
8056 char ids[SIZEOF_STR] = NULL_ID " ";
8057 struct main_state *state = view->private;
8058 struct commit commit = {};
8059 struct timeval now;
8060 struct timezone tz;
8062 if (!parent)
8063 return;
8065 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
8067 if (!gettimeofday(&now, &tz)) {
8068 commit.time.tz = tz.tz_minuteswest * 60;
8069 commit.time.sec = now.tv_sec - commit.time.tz;
8072 commit.author = &unknown_ident;
8073 main_register_commit(view, &commit, ids, FALSE);
8074 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
8075 graph_render_parents(&state->graph);
8078 static void
8079 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
8081 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
8082 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
8083 const char *staged_parent = NULL_ID;
8084 const char *unstaged_parent = parent;
8086 if (!is_head_commit(parent))
8087 return;
8089 state->added_changes_commits = TRUE;
8091 io_run_bg(update_index_argv);
8093 if (!main_has_changes(unstaged_argv)) {
8094 unstaged_parent = NULL;
8095 staged_parent = parent;
8098 if (!main_has_changes(staged_argv)) {
8099 staged_parent = NULL;
8102 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
8103 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
8106 static bool
8107 main_open(struct view *view, enum open_flags flags)
8109 static const char *main_argv[] = {
8110 GIT_MAIN_LOG(encoding_arg, "%(cmdlineargs)", "%(revargs)", "%(fileargs)")
8112 struct main_state *state = view->private;
8114 state->with_graph = opt_rev_graph &&
8115 opt_commit_order != COMMIT_ORDER_REVERSE;
8117 if (flags & OPEN_PAGER_MODE) {
8118 state->added_changes_commits = TRUE;
8119 state->with_graph = FALSE;
8122 return begin_update(view, NULL, main_argv, flags);
8125 static void
8126 main_done(struct view *view)
8128 struct main_state *state = view->private;
8129 int i;
8131 for (i = 0; i < view->lines; i++) {
8132 struct commit *commit = view->line[i].data;
8134 free(commit->graph.symbols);
8137 for (i = 0; i < state->reflogs; i++)
8138 free(state->reflog[i]);
8139 free(state->reflog);
8142 #define MAIN_NO_COMMIT_REFS 1
8143 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
8144 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
8146 static inline struct ref_list *
8147 main_get_commit_refs(struct line *line, struct commit *commit)
8149 struct ref_list *refs = NULL;
8151 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
8152 main_mark_no_commit_refs(line);
8154 return refs;
8157 static bool
8158 main_draw(struct view *view, struct line *line, unsigned int lineno)
8160 struct main_state *state = view->private;
8161 struct commit *commit = line->data;
8162 struct ref_list *refs = NULL;
8164 if (!commit->author)
8165 return FALSE;
8167 if (draw_lineno(view, lineno))
8168 return TRUE;
8170 if (opt_show_id) {
8171 if (state->reflogs) {
8172 const char *id = state->reflog[line->lineno - 1];
8174 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
8175 return TRUE;
8176 } else if (draw_id(view, commit->id)) {
8177 return TRUE;
8181 if (draw_date(view, &commit->time))
8182 return TRUE;
8184 if (draw_author(view, commit->author))
8185 return TRUE;
8187 if (state->with_graph && draw_graph(view, &commit->graph))
8188 return TRUE;
8190 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
8191 return TRUE;
8193 if (commit->title)
8194 draw_commit_title(view, commit->title, 0);
8195 return TRUE;
8198 static bool
8199 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
8201 char *end = strchr(reflog, ' ');
8202 int id_width;
8204 if (!end)
8205 return FALSE;
8206 *end = 0;
8208 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
8209 || !(reflog = strdup(reflog)))
8210 return FALSE;
8212 state->reflog[state->reflogs++] = reflog;
8213 id_width = strlen(reflog);
8214 if (state->reflog_width < id_width) {
8215 state->reflog_width = id_width;
8216 if (opt_show_id)
8217 view->force_redraw = TRUE;
8220 return TRUE;
8223 /* Reads git log --pretty=raw output and parses it into the commit struct. */
8224 static bool
8225 main_read(struct view *view, char *line)
8227 struct main_state *state = view->private;
8228 struct graph *graph = &state->graph;
8229 enum line_type type;
8230 struct commit *commit = &state->current;
8232 if (!line) {
8233 main_flush_commit(view, commit);
8235 if (!view->lines && !view->prev)
8236 die("No revisions match the given arguments.");
8237 if (view->lines > 0) {
8238 struct commit *last = view->line[view->lines - 1].data;
8240 view->line[view->lines - 1].dirty = 1;
8241 if (!last->author) {
8242 view->lines--;
8243 free(last);
8247 if (state->with_graph)
8248 done_graph(graph);
8249 return TRUE;
8252 type = get_line_type(line);
8253 if (type == LINE_COMMIT) {
8254 bool is_boundary;
8256 state->in_header = TRUE;
8257 line += STRING_SIZE("commit ");
8258 is_boundary = *line == '-';
8259 while (*line && !isalnum(*line))
8260 line++;
8262 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
8263 main_add_changes_commits(view, state, line);
8264 else
8265 main_flush_commit(view, commit);
8267 main_register_commit(view, &state->current, line, is_boundary);
8268 return TRUE;
8271 if (!*commit->id)
8272 return TRUE;
8274 /* Empty line separates the commit header from the log itself. */
8275 if (*line == '\0')
8276 state->in_header = FALSE;
8278 switch (type) {
8279 case LINE_PP_REFLOG:
8280 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8281 return FALSE;
8282 break;
8284 case LINE_PP_REFLOGMSG:
8285 line += STRING_SIZE("Reflog message: ");
8286 string_ncopy(state->reflogmsg, line, strlen(line));
8287 break;
8289 case LINE_PARENT:
8290 if (state->with_graph && !graph->has_parents)
8291 graph_add_parent(graph, line + STRING_SIZE("parent "));
8292 break;
8294 case LINE_AUTHOR:
8295 parse_author_line(line + STRING_SIZE("author "),
8296 &commit->author, &commit->time);
8297 if (state->with_graph)
8298 graph_render_parents(graph);
8299 break;
8301 default:
8302 /* Fill in the commit title if it has not already been set. */
8303 if (*commit->title)
8304 break;
8306 /* Skip lines in the commit header. */
8307 if (state->in_header)
8308 break;
8310 /* Require titles to start with a non-space character at the
8311 * offset used by git log. */
8312 if (strncmp(line, " ", 4))
8313 break;
8314 line += 4;
8315 /* Well, if the title starts with a whitespace character,
8316 * try to be forgiving. Otherwise we end up with no title. */
8317 while (isspace(*line))
8318 line++;
8319 if (*line == '\0')
8320 break;
8321 if (*state->reflogmsg)
8322 line = state->reflogmsg;
8323 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8326 return TRUE;
8329 static enum request
8330 main_request(struct view *view, enum request request, struct line *line)
8332 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8333 ? OPEN_SPLIT : OPEN_DEFAULT;
8335 switch (request) {
8336 case REQ_NEXT:
8337 case REQ_PREVIOUS:
8338 if (view_is_displayed(view) && display[0] != view)
8339 return request;
8340 /* Do not pass navigation requests to the branch view
8341 * when the main view is maximized. (GH #38) */
8342 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8344 case REQ_VIEW_DIFF:
8345 case REQ_ENTER:
8346 if (view_is_displayed(view) && display[0] != view)
8347 maximize_view(view, TRUE);
8349 if (line->type == LINE_STAT_UNSTAGED
8350 || line->type == LINE_STAT_STAGED) {
8351 struct view *diff = VIEW(REQ_VIEW_DIFF);
8352 const char *diff_staged_argv[] = {
8353 GIT_DIFF_STAGED(encoding_arg,
8354 opt_diff_context_arg,
8355 opt_ignore_space_arg, NULL, NULL)
8357 const char *diff_unstaged_argv[] = {
8358 GIT_DIFF_UNSTAGED(encoding_arg,
8359 opt_diff_context_arg,
8360 opt_ignore_space_arg, NULL, NULL)
8362 const char **diff_argv = line->type == LINE_STAT_STAGED
8363 ? diff_staged_argv : diff_unstaged_argv;
8365 open_argv(view, diff, diff_argv, NULL, flags);
8366 break;
8369 open_view(view, REQ_VIEW_DIFF, flags);
8370 break;
8372 case REQ_REFRESH:
8373 load_refs(TRUE);
8374 refresh_view(view);
8375 break;
8377 case REQ_JUMP_COMMIT:
8379 int lineno;
8381 for (lineno = 0; lineno < view->lines; lineno++) {
8382 struct commit *commit = view->line[lineno].data;
8384 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8385 select_view_line(view, lineno);
8386 report_clear();
8387 return REQ_NONE;
8391 report("Unable to find commit '%s'", opt_search);
8392 break;
8394 default:
8395 return request;
8398 return REQ_NONE;
8401 static bool
8402 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8404 struct ref_list *list;
8405 regmatch_t pmatch;
8406 size_t i;
8408 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8409 return FALSE;
8411 for (i = 0; i < list->size; i++) {
8412 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8413 return TRUE;
8416 return FALSE;
8419 static bool
8420 main_grep(struct view *view, struct line *line)
8422 struct commit *commit = line->data;
8423 const char *text[] = {
8424 commit->id,
8425 commit->title,
8426 mkauthor(commit->author, opt_author_width, opt_author),
8427 mkdate(&commit->time, opt_date),
8428 NULL
8431 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8434 static struct ref *
8435 main_get_commit_branch(struct line *line, struct commit *commit)
8437 struct ref_list *list = main_get_commit_refs(line, commit);
8438 struct ref *branch = NULL;
8439 size_t i;
8441 for (i = 0; list && i < list->size; i++) {
8442 struct ref *ref = list->refs[i];
8444 switch (get_line_type_from_ref(ref)) {
8445 case LINE_MAIN_HEAD:
8446 case LINE_MAIN_REF:
8447 /* Always prefer local branches. */
8448 return ref;
8450 default:
8451 branch = ref;
8455 return branch;
8458 static void
8459 main_select(struct view *view, struct line *line)
8461 struct commit *commit = line->data;
8463 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED) {
8464 string_ncopy(view->ref, commit->title, strlen(commit->title));
8465 } else {
8466 struct ref *branch = main_get_commit_branch(line, commit);
8468 if (branch)
8469 string_copy_rev(ref_branch, branch->name);
8470 string_copy_rev(view->ref, commit->id);
8472 string_copy_rev(ref_commit, commit->id);
8475 static struct view_ops main_ops = {
8476 "commit",
8477 { "main" },
8478 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE | VIEW_REFRESH,
8479 sizeof(struct main_state),
8480 main_open,
8481 main_read,
8482 main_draw,
8483 main_request,
8484 main_grep,
8485 main_select,
8486 main_done,
8489 static bool
8490 stash_open(struct view *view, enum open_flags flags)
8492 static const char *stash_argv[] = { "git", "stash", "list",
8493 encoding_arg, "--no-color", "--pretty=raw", NULL };
8494 struct main_state *state = view->private;
8496 state->added_changes_commits = TRUE;
8497 state->with_graph = FALSE;
8498 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8501 static void
8502 stash_select(struct view *view, struct line *line)
8504 main_select(view, line);
8505 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8506 string_copy(view->ref, ref_stash);
8509 static struct view_ops stash_ops = {
8510 "stash",
8511 { "stash" },
8512 VIEW_SEND_CHILD_ENTER | VIEW_REFRESH,
8513 sizeof(struct main_state),
8514 stash_open,
8515 main_read,
8516 main_draw,
8517 main_request,
8518 main_grep,
8519 stash_select,
8523 * Status management
8526 /* Whether or not the curses interface has been initialized. */
8527 static bool cursed = FALSE;
8529 /* Terminal hacks and workarounds. */
8530 static bool use_scroll_redrawwin;
8531 static bool use_scroll_status_wclear;
8533 /* The status window is used for polling keystrokes. */
8534 static WINDOW *status_win;
8536 /* Reading from the prompt? */
8537 static bool input_mode = FALSE;
8539 static bool status_empty = FALSE;
8541 /* Update status and title window. */
8542 static void
8543 report(const char *msg, ...)
8545 struct view *view = display[current_view];
8547 if (input_mode)
8548 return;
8550 if (!view) {
8551 char buf[SIZEOF_STR];
8552 int retval;
8554 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8555 die("%s", buf);
8558 if (!status_empty || *msg) {
8559 va_list args;
8561 va_start(args, msg);
8563 wmove(status_win, 0, 0);
8564 if (view->has_scrolled && use_scroll_status_wclear)
8565 wclear(status_win);
8566 if (*msg) {
8567 vwprintw(status_win, msg, args);
8568 status_empty = FALSE;
8569 } else {
8570 status_empty = TRUE;
8572 wclrtoeol(status_win);
8573 wnoutrefresh(status_win);
8575 va_end(args);
8578 update_view_title(view);
8581 static void
8582 done_display(void)
8584 endwin();
8587 static void
8588 init_display(void)
8590 const char *term;
8591 int x, y;
8593 die_callback = done_display;
8595 /* Initialize the curses library */
8596 if (isatty(STDIN_FILENO)) {
8597 cursed = !!initscr();
8598 opt_tty = stdin;
8599 } else {
8600 /* Leave stdin and stdout alone when acting as a pager. */
8601 opt_tty = fopen("/dev/tty", "r+");
8602 if (!opt_tty)
8603 die("Failed to open /dev/tty");
8604 cursed = !!newterm(NULL, opt_tty, opt_tty);
8607 if (!cursed)
8608 die("Failed to initialize curses");
8610 nonl(); /* Disable conversion and detect newlines from input. */
8611 cbreak(); /* Take input chars one at a time, no wait for \n */
8612 noecho(); /* Don't echo input */
8613 leaveok(stdscr, FALSE);
8615 if (has_colors())
8616 init_colors();
8618 getmaxyx(stdscr, y, x);
8619 status_win = newwin(1, x, y - 1, 0);
8620 if (!status_win)
8621 die("Failed to create status window");
8623 /* Enable keyboard mapping */
8624 keypad(status_win, TRUE);
8625 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8626 #ifdef NCURSES_MOUSE_VERSION
8627 /* Enable mouse */
8628 if (opt_mouse){
8629 mousemask(ALL_MOUSE_EVENTS, NULL);
8630 mouseinterval(0);
8632 #endif
8634 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8635 set_tabsize(opt_tab_size);
8636 #else
8637 TABSIZE = opt_tab_size;
8638 #endif
8640 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8641 if (term && !strcmp(term, "gnome-terminal")) {
8642 /* In the gnome-terminal-emulator, the message from
8643 * scrolling up one line when impossible followed by
8644 * scrolling down one line causes corruption of the
8645 * status line. This is fixed by calling wclear. */
8646 use_scroll_status_wclear = TRUE;
8647 use_scroll_redrawwin = FALSE;
8649 } else if (term && !strcmp(term, "xrvt-xpm")) {
8650 /* No problems with full optimizations in xrvt-(unicode)
8651 * and aterm. */
8652 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8654 } else {
8655 /* When scrolling in (u)xterm the last line in the
8656 * scrolling direction will update slowly. */
8657 use_scroll_redrawwin = TRUE;
8658 use_scroll_status_wclear = FALSE;
8662 static int
8663 get_input(int prompt_position)
8665 struct view *view;
8666 int i, key, cursor_y, cursor_x;
8668 if (prompt_position)
8669 input_mode = TRUE;
8671 while (TRUE) {
8672 bool loading = FALSE;
8674 foreach_view (view, i) {
8675 update_view(view);
8676 if (view_is_displayed(view) && view->has_scrolled &&
8677 use_scroll_redrawwin)
8678 redrawwin(view->win);
8679 view->has_scrolled = FALSE;
8680 if (view->pipe)
8681 loading = TRUE;
8684 /* Update the cursor position. */
8685 if (prompt_position) {
8686 getbegyx(status_win, cursor_y, cursor_x);
8687 cursor_x = prompt_position;
8688 } else {
8689 view = display[current_view];
8690 getbegyx(view->win, cursor_y, cursor_x);
8691 cursor_x = view->width - 1;
8692 cursor_y += view->pos.lineno - view->pos.offset;
8694 setsyx(cursor_y, cursor_x);
8696 /* Refresh, accept single keystroke of input */
8697 doupdate();
8698 nodelay(status_win, loading);
8699 key = wgetch(status_win);
8701 /* wgetch() with nodelay() enabled returns ERR when
8702 * there's no input. */
8703 if (key == ERR) {
8705 } else if (key == KEY_RESIZE) {
8706 int height, width;
8708 getmaxyx(stdscr, height, width);
8710 wresize(status_win, 1, width);
8711 mvwin(status_win, height - 1, 0);
8712 wnoutrefresh(status_win);
8713 resize_display();
8714 redraw_display(TRUE);
8716 } else {
8717 input_mode = FALSE;
8718 if (key == erasechar())
8719 key = KEY_BACKSPACE;
8720 return key;
8725 static char *
8726 prompt_input(const char *prompt, input_handler handler, void *data)
8728 enum input_status status = INPUT_OK;
8729 static char buf[SIZEOF_STR];
8730 size_t pos = 0;
8732 buf[pos] = 0;
8734 while (status == INPUT_OK || status == INPUT_SKIP) {
8735 int key;
8737 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8738 wclrtoeol(status_win);
8740 key = get_input(pos + 1);
8741 switch (key) {
8742 case KEY_RETURN:
8743 case KEY_ENTER:
8744 case '\n':
8745 status = pos ? INPUT_STOP : INPUT_CANCEL;
8746 break;
8748 case KEY_BACKSPACE:
8749 if (pos > 0)
8750 buf[--pos] = 0;
8751 else
8752 status = INPUT_CANCEL;
8753 break;
8755 case KEY_ESC:
8756 status = INPUT_CANCEL;
8757 break;
8759 default:
8760 if (pos >= sizeof(buf)) {
8761 report("Input string too long");
8762 return NULL;
8765 status = handler(data, buf, key);
8766 if (status == INPUT_OK)
8767 buf[pos++] = (char) key;
8771 /* Clear the status window */
8772 status_empty = FALSE;
8773 report_clear();
8775 if (status == INPUT_CANCEL)
8776 return NULL;
8778 buf[pos++] = 0;
8780 return buf;
8783 static enum input_status
8784 prompt_yesno_handler(void *data, char *buf, int c)
8786 if (c == 'y' || c == 'Y')
8787 return INPUT_STOP;
8788 if (c == 'n' || c == 'N')
8789 return INPUT_CANCEL;
8790 return INPUT_SKIP;
8793 static bool
8794 prompt_yesno(const char *prompt)
8796 char prompt2[SIZEOF_STR];
8798 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8799 return FALSE;
8801 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8804 static enum input_status
8805 read_prompt_handler(void *data, char *buf, int c)
8807 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8810 static char *
8811 read_prompt(const char *prompt)
8813 return prompt_input(prompt, read_prompt_handler, NULL);
8816 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8818 enum input_status status = INPUT_OK;
8819 int size = 0;
8821 while (items[size].text)
8822 size++;
8824 assert(size > 0);
8826 while (status == INPUT_OK) {
8827 const struct menu_item *item = &items[*selected];
8828 int key;
8829 int i;
8831 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8832 prompt, *selected + 1, size);
8833 if (item->hotkey)
8834 wprintw(status_win, "[%c] ", (char) item->hotkey);
8835 wprintw(status_win, "%s", item->text);
8836 wclrtoeol(status_win);
8838 key = get_input(COLS - 1);
8839 switch (key) {
8840 case KEY_RETURN:
8841 case KEY_ENTER:
8842 case '\n':
8843 status = INPUT_STOP;
8844 break;
8846 case KEY_LEFT:
8847 case KEY_UP:
8848 *selected = *selected - 1;
8849 if (*selected < 0)
8850 *selected = size - 1;
8851 break;
8853 case KEY_RIGHT:
8854 case KEY_DOWN:
8855 *selected = (*selected + 1) % size;
8856 break;
8858 case KEY_ESC:
8859 status = INPUT_CANCEL;
8860 break;
8862 default:
8863 for (i = 0; items[i].text; i++)
8864 if (items[i].hotkey == key) {
8865 *selected = i;
8866 status = INPUT_STOP;
8867 break;
8872 /* Clear the status window */
8873 status_empty = FALSE;
8874 report_clear();
8876 return status != INPUT_CANCEL;
8880 * Repository properties
8884 static void
8885 set_remote_branch(const char *name, const char *value, size_t valuelen)
8887 if (!strcmp(name, ".remote")) {
8888 string_ncopy(opt_remote, value, valuelen);
8890 } else if (*opt_remote && !strcmp(name, ".merge")) {
8891 size_t from = strlen(opt_remote);
8893 if (!prefixcmp(value, "refs/heads/"))
8894 value += STRING_SIZE("refs/heads/");
8896 if (!string_format_from(opt_remote, &from, "/%s", value))
8897 opt_remote[0] = 0;
8901 static void
8902 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8904 const char *argv[SIZEOF_ARG] = { name, "=" };
8905 int argc = 1 + (cmd == option_set_command);
8906 enum status_code error;
8908 if (!argv_from_string(argv, &argc, value))
8909 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8910 else
8911 error = cmd(argc, argv);
8913 if (error != SUCCESS)
8914 warn("Option 'tig.%s': %s", name, get_status_message(error));
8917 static void
8918 set_work_tree(const char *value)
8920 char cwd[SIZEOF_STR];
8922 if (!getcwd(cwd, sizeof(cwd)))
8923 die("Failed to get cwd path: %s", strerror(errno));
8924 if (chdir(cwd) < 0)
8925 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8926 if (chdir(opt_git_dir) < 0)
8927 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8928 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8929 die("Failed to get git path: %s", strerror(errno));
8930 if (chdir(value) < 0)
8931 die("Failed to chdir(%s): %s", value, strerror(errno));
8932 if (!getcwd(cwd, sizeof(cwd)))
8933 die("Failed to get cwd path: %s", strerror(errno));
8934 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8935 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8936 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8937 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8938 opt_is_inside_work_tree = TRUE;
8941 static void
8942 parse_git_color_option(enum line_type type, char *value)
8944 struct line_info *info = &line_info[type];
8945 const char *argv[SIZEOF_ARG];
8946 int argc = 0;
8947 bool first_color = TRUE;
8948 int i;
8950 if (!argv_from_string(argv, &argc, value))
8951 return;
8953 info->fg = COLOR_DEFAULT;
8954 info->bg = COLOR_DEFAULT;
8955 info->attr = 0;
8957 for (i = 0; i < argc; i++) {
8958 int attr = 0;
8960 if (set_attribute(&attr, argv[i])) {
8961 info->attr |= attr;
8963 } else if (set_color(&attr, argv[i])) {
8964 if (first_color)
8965 info->fg = attr;
8966 else
8967 info->bg = attr;
8968 first_color = FALSE;
8973 static void
8974 set_git_color_option(const char *name, char *value)
8976 static const struct enum_map_entry color_option_map[] = {
8977 ENUM_MAP_ENTRY("branch.current", LINE_MAIN_HEAD),
8978 ENUM_MAP_ENTRY("branch.local", LINE_MAIN_REF),
8979 ENUM_MAP_ENTRY("branch.plain", LINE_MAIN_REF),
8980 ENUM_MAP_ENTRY("branch.remote", LINE_MAIN_REMOTE),
8982 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_HEADER),
8983 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_INDEX),
8984 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_OLDMODE),
8985 ENUM_MAP_ENTRY("diff.meta", LINE_DIFF_NEWMODE),
8986 ENUM_MAP_ENTRY("diff.frag", LINE_DIFF_CHUNK),
8987 ENUM_MAP_ENTRY("diff.old", LINE_DIFF_DEL),
8988 ENUM_MAP_ENTRY("diff.new", LINE_DIFF_ADD),
8990 //ENUM_MAP_ENTRY("diff.commit", LINE_DIFF_ADD),
8992 ENUM_MAP_ENTRY("status.branch", LINE_STAT_HEAD),
8993 //ENUM_MAP_ENTRY("status.nobranch", LINE_STAT_HEAD),
8994 ENUM_MAP_ENTRY("status.added", LINE_STAT_STAGED),
8995 ENUM_MAP_ENTRY("status.updated", LINE_STAT_STAGED),
8996 ENUM_MAP_ENTRY("status.changed", LINE_STAT_UNSTAGED),
8997 ENUM_MAP_ENTRY("status.untracked", LINE_STAT_UNTRACKED),
8999 int type = LINE_NONE;
9001 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
9002 parse_git_color_option(type, value);
9006 static void
9007 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
9009 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
9010 encoding_arg[0] = 0;
9013 static int
9014 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9016 if (!strcmp(name, "i18n.commitencoding"))
9017 set_encoding(&default_encoding, value, FALSE);
9019 else if (!strcmp(name, "gui.encoding"))
9020 set_encoding(&default_encoding, value, TRUE);
9022 else if (!strcmp(name, "core.editor"))
9023 string_ncopy(opt_editor, value, valuelen);
9025 else if (!strcmp(name, "core.worktree"))
9026 set_work_tree(value);
9028 else if (!strcmp(name, "core.abbrev"))
9029 parse_id(&opt_id_cols, value);
9031 else if (!prefixcmp(name, "tig.color."))
9032 set_repo_config_option(name + 10, value, option_color_command);
9034 else if (!prefixcmp(name, "tig.bind."))
9035 set_repo_config_option(name + 9, value, option_bind_command);
9037 else if (!prefixcmp(name, "tig."))
9038 set_repo_config_option(name + 4, value, option_set_command);
9040 else if (!prefixcmp(name, "color."))
9041 set_git_color_option(name + STRING_SIZE("color."), value);
9043 else if (*opt_head && !prefixcmp(name, "branch.") &&
9044 !strncmp(name + 7, opt_head, strlen(opt_head)))
9045 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
9047 return OK;
9050 static int
9051 load_git_config(void)
9053 const char *config_list_argv[] = { "git", "config", "--list", NULL };
9055 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
9058 #define REPO_INFO_GIT_DIR "--git-dir"
9059 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
9060 #define REPO_INFO_SHOW_CDUP "--show-cdup"
9061 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
9062 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
9063 #define REPO_INFO_RESOLVED_HEAD "HEAD"
9065 struct repo_info_state {
9066 const char **argv;
9067 char head_id[SIZEOF_REV];
9070 static int
9071 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9073 struct repo_info_state *state = data;
9074 const char *arg = *state->argv ? *state->argv++ : "";
9076 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
9077 string_ncopy(opt_git_dir, name, namelen);
9079 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
9080 /* This can be 3 different values depending on the
9081 * version of git being used. If git-rev-parse does not
9082 * understand --is-inside-work-tree it will simply echo
9083 * the option else either "true" or "false" is printed.
9084 * Default to true for the unknown case. */
9085 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
9087 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
9088 string_ncopy(opt_cdup, name, namelen);
9090 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
9091 string_ncopy(opt_prefix, name, namelen);
9093 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
9094 string_ncopy(state->head_id, name, namelen);
9096 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
9097 if (!prefixcmp(name, "refs/heads/")) {
9098 char *offset = name + STRING_SIZE("refs/heads/");
9100 string_ncopy(opt_head, offset, strlen(offset) + 1);
9101 add_ref(state->head_id, name, opt_remote, opt_head);
9103 state->argv++;
9106 return OK;
9109 static int
9110 load_repo_info(void)
9112 const char *rev_parse_argv[] = {
9113 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
9114 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
9115 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
9116 NULL
9118 struct repo_info_state state = { rev_parse_argv + 2 };
9120 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
9125 * Main
9128 static const char usage[] =
9129 "tig " TIG_VERSION " (" __DATE__ ")\n"
9130 "\n"
9131 "Usage: tig [options] [revs] [--] [paths]\n"
9132 " or: tig log [options] [revs] [--] [paths]\n"
9133 " or: tig show [options] [revs] [--] [paths]\n"
9134 " or: tig blame [options] [rev] [--] path\n"
9135 " or: tig stash\n"
9136 " or: tig status\n"
9137 " or: tig < [git command output]\n"
9138 "\n"
9139 "Options:\n"
9140 " +<number> Select line <number> in the first view\n"
9141 " -v, --version Show version and exit\n"
9142 " -h, --help Show help message and exit";
9144 static void TIG_NORETURN
9145 quit(int sig)
9147 if (sig)
9148 signal(sig, SIG_DFL);
9150 /* XXX: Restore tty modes and let the OS cleanup the rest! */
9151 if (cursed)
9152 endwin();
9153 exit(0);
9156 static int
9157 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9159 const char ***filter_args = data;
9161 return argv_append(filter_args, name) ? OK : ERR;
9164 static void
9165 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
9167 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
9168 const char **all_argv = NULL;
9170 if (!argv_append_array(&all_argv, rev_parse_argv) ||
9171 !argv_append_array(&all_argv, argv) ||
9172 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
9173 die("Failed to split arguments");
9174 argv_free(all_argv);
9175 free(all_argv);
9178 static bool
9179 is_rev_flag(const char *flag)
9181 static const char *rev_flags[] = { GIT_REV_FLAGS };
9182 int i;
9184 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
9185 if (!strcmp(flag, rev_flags[i]))
9186 return TRUE;
9188 return FALSE;
9191 static void
9192 filter_options(const char *argv[], bool blame)
9194 const char **flags = NULL;
9195 int next, flags_pos;
9197 for (next = flags_pos = 0; argv[next]; next++) {
9198 const char *flag = argv[next];
9199 int value = -1;
9201 if (map_enum(&value, commit_order_arg_map, flag)) {
9202 opt_commit_order = value;
9203 update_commit_order_arg();
9204 continue;
9207 if (map_enum(&value, ignore_space_arg_map, flag)) {
9208 opt_ignore_space = value;
9209 update_ignore_space_arg();
9210 continue;
9213 if (!prefixcmp(flag, "-U")
9214 && parse_int(&value, flag + 2, 0, 999999) == SUCCESS) {
9215 opt_diff_context = value;
9216 update_diff_context_arg(opt_diff_context);
9217 continue;
9220 argv[flags_pos++] = flag;
9223 argv[flags_pos] = NULL;
9225 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
9226 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
9228 if (flags) {
9229 for (next = flags_pos = 0; flags && flags[next]; next++) {
9230 const char *flag = flags[next];
9232 if (is_rev_flag(flag))
9233 argv_append(&opt_rev_argv, flag);
9234 else
9235 flags[flags_pos++] = flag;
9238 flags[flags_pos] = NULL;
9240 if (blame)
9241 opt_blame_argv = flags;
9242 else
9243 opt_cmdline_argv = flags;
9246 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
9249 static enum request
9250 parse_options(int argc, const char *argv[], bool pager_mode)
9252 enum request request;
9253 const char *subcommand;
9254 bool seen_dashdash = FALSE;
9255 const char **filter_argv = NULL;
9256 int i;
9258 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
9260 if (argc <= 1)
9261 return request;
9263 subcommand = argv[1];
9264 if (!strcmp(subcommand, "status")) {
9265 request = REQ_VIEW_STATUS;
9267 } else if (!strcmp(subcommand, "blame")) {
9268 request = REQ_VIEW_BLAME;
9270 } else if (!strcmp(subcommand, "show")) {
9271 request = REQ_VIEW_DIFF;
9273 } else if (!strcmp(subcommand, "log")) {
9274 request = REQ_VIEW_LOG;
9276 } else if (!strcmp(subcommand, "stash")) {
9277 request = REQ_VIEW_STASH;
9279 } else {
9280 subcommand = NULL;
9283 for (i = 1 + !!subcommand; i < argc; i++) {
9284 const char *opt = argv[i];
9286 // stop parsing our options after -- and let rev-parse handle the rest
9287 if (!seen_dashdash) {
9288 if (!strcmp(opt, "--")) {
9289 seen_dashdash = TRUE;
9290 continue;
9292 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
9293 printf("tig version %s\n", TIG_VERSION);
9294 quit(0);
9296 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
9297 printf("%s\n", usage);
9298 quit(0);
9300 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
9301 opt_lineno = atoi(opt + 1);
9302 continue;
9307 if (!argv_append(&filter_argv, opt))
9308 die("command too long");
9311 if (filter_argv)
9312 filter_options(filter_argv, request == REQ_VIEW_BLAME);
9314 /* Finish validating and setting up blame options */
9315 if (request == REQ_VIEW_BLAME) {
9316 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
9317 die("invalid number of options to blame\n\n%s", usage);
9319 if (opt_rev_argv) {
9320 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
9323 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
9326 return request;
9329 static enum request
9330 open_pager_mode(enum request request)
9332 enum open_flags flags = OPEN_DEFAULT;
9334 if (request == REQ_VIEW_PAGER) {
9335 /* Detect if the user requested the main view. */
9336 if (argv_contains(opt_rev_argv, "--stdin")) {
9337 request = REQ_VIEW_MAIN;
9338 flags |= OPEN_FORWARD_STDIN;
9339 } else if (argv_contains(opt_cmdline_argv, "--pretty=raw")) {
9340 request = REQ_VIEW_MAIN;
9341 flags |= OPEN_STDIN;
9342 } else {
9343 flags |= OPEN_STDIN;
9346 } else if (request == REQ_VIEW_DIFF) {
9347 if (argv_contains(opt_rev_argv, "--stdin"))
9348 flags |= OPEN_FORWARD_STDIN;
9351 /* Open the requested view even if the pager mode is enabled so
9352 * the warning message below is displayed correctly. */
9353 open_view(NULL, request, flags);
9355 if (!open_in_pager_mode(flags)) {
9356 close(STDIN_FILENO);
9357 report("Ignoring stdin.");
9360 return REQ_NONE;
9363 static enum request
9364 run_prompt_command(struct view *view, char *cmd)
9366 enum request request;
9368 if (cmd && string_isnumber(cmd)) {
9369 int lineno = view->pos.lineno + 1;
9371 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9372 select_view_line(view, lineno - 1);
9373 report_clear();
9374 } else {
9375 report("Unable to parse '%s' as a line number", cmd);
9377 } else if (cmd && iscommit(cmd)) {
9378 string_ncopy(opt_search, cmd, strlen(cmd));
9380 request = view_request(view, REQ_JUMP_COMMIT);
9381 if (request == REQ_JUMP_COMMIT) {
9382 report("Jumping to commits is not supported by the '%s' view", view->name);
9385 } else if (cmd && strlen(cmd) == 1) {
9386 request = get_keybinding(&view->ops->keymap, cmd[0]);
9387 return request;
9389 } else if (cmd && cmd[0] == '!') {
9390 struct view *next = VIEW(REQ_VIEW_PAGER);
9391 const char *argv[SIZEOF_ARG];
9392 int argc = 0;
9394 cmd++;
9395 /* When running random commands, initially show the
9396 * command in the title. However, it maybe later be
9397 * overwritten if a commit line is selected. */
9398 string_ncopy(next->ref, cmd, strlen(cmd));
9400 if (!argv_from_string(argv, &argc, cmd)) {
9401 report("Too many arguments");
9402 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9403 report("Argument formatting failed");
9404 } else {
9405 next->dir = NULL;
9406 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9409 } else if (cmd) {
9410 request = get_request(cmd);
9411 if (request != REQ_UNKNOWN)
9412 return request;
9414 char *args = strchr(cmd, ' ');
9415 if (args) {
9416 *args++ = 0;
9417 if (set_option(cmd, args) == SUCCESS) {
9418 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9419 if (!strcmp(cmd, "color"))
9420 init_colors();
9423 return request;
9425 return REQ_NONE;
9428 #ifdef NCURSES_MOUSE_VERSION
9429 static struct view *
9430 find_clicked_view(MEVENT *event)
9432 struct view *view;
9433 int i;
9435 foreach_displayed_view (view, i) {
9436 int beg_y = 0, beg_x = 0;
9438 getbegyx(view->win, beg_y, beg_x);
9440 if (beg_y <= event->y && event->y < beg_y + view->height
9441 && beg_x <= event->x && event->x < beg_x + view->width) {
9442 if (i != current_view) {
9443 current_view = i;
9445 return view;
9449 return NULL;
9452 static enum request
9453 handle_mouse_event(void)
9455 MEVENT event;
9456 struct view *view;
9458 if (getmouse(&event) != OK)
9459 return REQ_NONE;
9461 view = find_clicked_view(&event);
9462 if (!view)
9463 return REQ_NONE;
9465 if (event.bstate & BUTTON2_PRESSED)
9466 return REQ_SCROLL_WHEEL_DOWN;
9468 if (event.bstate & BUTTON4_PRESSED)
9469 return REQ_SCROLL_WHEEL_UP;
9471 if (event.bstate & BUTTON1_PRESSED) {
9472 if (event.y == view->pos.lineno - view->pos.offset) {
9473 /* Click is on the same line, perform an "ENTER" */
9474 return REQ_ENTER;
9476 } else {
9477 int y = getbegy(view->win);
9478 unsigned long lineno = (event.y - y) + view->pos.offset;
9480 select_view_line(view, lineno);
9481 update_view_title(view);
9482 report_clear();
9486 return REQ_NONE;
9488 #endif
9491 main(int argc, const char *argv[])
9493 const char *codeset = ENCODING_UTF8;
9494 bool pager_mode = !isatty(STDIN_FILENO);
9495 enum request request = parse_options(argc, argv, pager_mode);
9496 struct view *view;
9497 int i;
9499 signal(SIGINT, quit);
9500 signal(SIGQUIT, quit);
9501 signal(SIGPIPE, SIG_IGN);
9503 if (setlocale(LC_ALL, "")) {
9504 codeset = nl_langinfo(CODESET);
9507 foreach_view(view, i) {
9508 add_keymap(&view->ops->keymap);
9511 if (load_repo_info() == ERR)
9512 die("Failed to load repo info.");
9514 if (load_options() == ERR)
9515 die("Failed to load user config.");
9517 if (load_git_config() == ERR)
9518 die("Failed to load repo config.");
9520 /* Require a git repository unless when running in pager mode. */
9521 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9522 die("Not a git repository");
9524 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9525 char translit[SIZEOF_STR];
9527 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9528 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9529 else
9530 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9531 if (opt_iconv_out == ICONV_NONE)
9532 die("Failed to initialize character set conversion");
9535 if (load_refs(FALSE) == ERR)
9536 die("Failed to load refs.");
9538 init_display();
9540 if (pager_mode)
9541 request = open_pager_mode(request);
9543 while (view_driver(display[current_view], request)) {
9544 int key = get_input(0);
9546 #ifdef NCURSES_MOUSE_VERSION
9547 if (key == KEY_MOUSE) {
9548 request = handle_mouse_event();
9549 continue;
9551 #endif
9553 if (key == KEY_ESC)
9554 key = get_input(0) + 0x80;
9556 view = display[current_view];
9557 request = get_keybinding(&view->ops->keymap, key);
9559 /* Some low-level request handling. This keeps access to
9560 * status_win restricted. */
9561 switch (request) {
9562 case REQ_NONE:
9563 report("Unknown key, press %s for help",
9564 get_view_key(view, REQ_VIEW_HELP));
9565 break;
9566 case REQ_PROMPT:
9568 char *cmd = read_prompt(":");
9569 request = run_prompt_command(view, cmd);
9570 break;
9572 case REQ_SEARCH:
9573 case REQ_SEARCH_BACK:
9575 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9576 char *search = read_prompt(prompt);
9578 if (search)
9579 string_ncopy(opt_search, search, strlen(search));
9580 else if (*opt_search)
9581 request = request == REQ_SEARCH ?
9582 REQ_FIND_NEXT :
9583 REQ_FIND_PREV;
9584 else
9585 request = REQ_NONE;
9586 break;
9588 default:
9589 break;
9593 quit(0);
9595 return 0;
9598 /* vim: set ts=8 sw=8 noexpandtab: */