Rework custom line tracking to allow custom lines at any place
[tig.git] / tig.c
blobcbc7ca706037fc3133b65869c7084cb64fb10086
1 /* Copyright (c) 2006-2012 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 #include "tig.h"
15 #include "io.h"
16 #include "refs.h"
17 #include "graph.h"
18 #include "git.h"
20 static void __NORETURN die(const char *err, ...);
21 static void warn(const char *msg, ...);
22 static void report(const char *msg, ...);
25 enum input_status {
26 INPUT_OK,
27 INPUT_SKIP,
28 INPUT_STOP,
29 INPUT_CANCEL
32 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
34 static char *prompt_input(const char *prompt, input_handler handler, void *data);
35 static bool prompt_yesno(const char *prompt);
36 static char *read_prompt(const char *prompt);
38 struct menu_item {
39 int hotkey;
40 const char *text;
41 void *data;
44 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
46 #define GRAPHIC_ENUM(_) \
47 _(GRAPHIC, ASCII), \
48 _(GRAPHIC, DEFAULT), \
49 _(GRAPHIC, UTF_8)
51 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
53 #define DATE_ENUM(_) \
54 _(DATE, NO), \
55 _(DATE, DEFAULT), \
56 _(DATE, LOCAL), \
57 _(DATE, RELATIVE), \
58 _(DATE, SHORT)
60 DEFINE_ENUM(date, DATE_ENUM);
62 struct time {
63 time_t sec;
64 int tz;
67 static inline int timecmp(const struct time *t1, const struct time *t2)
69 return t1->sec - t2->sec;
72 static const char *
73 mkdate(const struct time *time, enum date date)
75 static char buf[DATE_COLS + 1];
76 static const struct enum_map reldate[] = {
77 { "second", 1, 60 * 2 },
78 { "minute", 60, 60 * 60 * 2 },
79 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
80 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
81 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
82 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
83 { "year", 60 * 60 * 24 * 365, 0 },
85 struct tm tm;
87 if (!date || !time || !time->sec)
88 return "";
90 if (date == DATE_RELATIVE) {
91 struct timeval now;
92 time_t date = time->sec + time->tz;
93 time_t seconds;
94 int i;
96 gettimeofday(&now, NULL);
97 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
98 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
99 if (seconds >= reldate[i].value && reldate[i].value)
100 continue;
102 seconds /= reldate[i].namelen;
103 if (!string_format(buf, "%ld %s%s %s",
104 seconds, reldate[i].name,
105 seconds > 1 ? "s" : "",
106 now.tv_sec >= date ? "ago" : "ahead"))
107 break;
108 return buf;
112 if (date == DATE_LOCAL) {
113 time_t date = time->sec + time->tz;
114 localtime_r(&date, &tm);
116 else {
117 gmtime_r(&time->sec, &tm);
119 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
123 #define AUTHOR_ENUM(_) \
124 _(AUTHOR, NO), \
125 _(AUTHOR, FULL), \
126 _(AUTHOR, ABBREVIATED)
128 DEFINE_ENUM(author, AUTHOR_ENUM);
130 static const char *
131 get_author_initials(const char *author)
133 static char initials[AUTHOR_COLS * 6 + 1];
134 size_t pos = 0;
135 const char *end = strchr(author, '\0');
137 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
139 memset(initials, 0, sizeof(initials));
140 while (author < end) {
141 unsigned char bytes;
142 size_t i;
144 while (author < end && is_initial_sep(*author))
145 author++;
147 bytes = utf8_char_length(author, end);
148 if (bytes >= sizeof(initials) - 1 - pos)
149 break;
150 while (bytes--) {
151 initials[pos++] = *author++;
154 i = pos;
155 while (author < end && !is_initial_sep(*author)) {
156 bytes = utf8_char_length(author, end);
157 if (bytes >= sizeof(initials) - 1 - i) {
158 while (author < end && !is_initial_sep(*author))
159 author++;
160 break;
162 while (bytes--) {
163 initials[i++] = *author++;
167 initials[i++] = 0;
170 return initials;
173 #define author_trim(cols) (cols == 0 || cols > 10)
175 static const char *
176 mkauthor(const char *text, int cols, enum author author)
178 bool trim = author_trim(cols);
179 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
181 if (author == AUTHOR_NO)
182 return "";
183 if (abbreviate && text)
184 return get_author_initials(text);
185 return text;
188 static const char *
189 mkmode(mode_t mode)
191 if (S_ISDIR(mode))
192 return "drwxr-xr-x";
193 else if (S_ISLNK(mode))
194 return "lrwxrwxrwx";
195 else if (S_ISGITLINK(mode))
196 return "m---------";
197 else if (S_ISREG(mode) && mode & S_IXUSR)
198 return "-rwxr-xr-x";
199 else if (S_ISREG(mode))
200 return "-rw-r--r--";
201 else
202 return "----------";
205 #define FILENAME_ENUM(_) \
206 _(FILENAME, NO), \
207 _(FILENAME, ALWAYS), \
208 _(FILENAME, AUTO)
210 DEFINE_ENUM(filename, FILENAME_ENUM);
212 #define IGNORE_SPACE_ENUM(_) \
213 _(IGNORE_SPACE, NO), \
214 _(IGNORE_SPACE, ALL), \
215 _(IGNORE_SPACE, SOME), \
216 _(IGNORE_SPACE, AT_EOL)
218 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
220 #define COMMIT_ORDER_ENUM(_) \
221 _(COMMIT_ORDER, DEFAULT), \
222 _(COMMIT_ORDER, TOPO), \
223 _(COMMIT_ORDER, DATE), \
224 _(COMMIT_ORDER, REVERSE)
226 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
228 #define VIEW_INFO(_) \
229 _(MAIN, main, ref_head), \
230 _(DIFF, diff, ref_commit), \
231 _(LOG, log, ref_head), \
232 _(TREE, tree, ref_commit), \
233 _(BLOB, blob, ref_blob), \
234 _(BLAME, blame, ref_commit), \
235 _(BRANCH, branch, ref_head), \
236 _(HELP, help, ""), \
237 _(PAGER, pager, ""), \
238 _(STATUS, status, "status"), \
239 _(STAGE, stage, "stage")
241 static struct encoding *
242 get_path_encoding(const char *path, struct encoding *default_encoding)
244 const char *check_attr_argv[] = {
245 "git", "check-attr", "encoding", "--", path, NULL
247 char buf[SIZEOF_STR];
248 char *encoding;
250 /* <path>: encoding: <encoding> */
252 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
253 || !(encoding = strstr(buf, ENCODING_SEP)))
254 return default_encoding;
256 encoding += STRING_SIZE(ENCODING_SEP);
257 if (!strcmp(encoding, ENCODING_UTF8)
258 || !strcmp(encoding, "unspecified")
259 || !strcmp(encoding, "set"))
260 return default_encoding;
262 return encoding_open(encoding);
266 * User requests
269 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
271 #define REQ_INFO \
272 REQ_GROUP("View switching") \
273 VIEW_INFO(VIEW_REQ), \
275 REQ_GROUP("View manipulation") \
276 REQ_(ENTER, "Enter current line and scroll"), \
277 REQ_(NEXT, "Move to next"), \
278 REQ_(PREVIOUS, "Move to previous"), \
279 REQ_(PARENT, "Move to parent"), \
280 REQ_(VIEW_NEXT, "Move focus to next view"), \
281 REQ_(REFRESH, "Reload and refresh"), \
282 REQ_(MAXIMIZE, "Maximize the current view"), \
283 REQ_(VIEW_CLOSE, "Close the current view"), \
284 REQ_(QUIT, "Close all views and quit"), \
286 REQ_GROUP("View specific requests") \
287 REQ_(STATUS_UPDATE, "Update file status"), \
288 REQ_(STATUS_REVERT, "Revert file changes"), \
289 REQ_(STATUS_MERGE, "Merge file using external tool"), \
290 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
291 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
292 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
293 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
295 REQ_GROUP("Cursor navigation") \
296 REQ_(MOVE_UP, "Move cursor one line up"), \
297 REQ_(MOVE_DOWN, "Move cursor one line down"), \
298 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
299 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
300 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
301 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
303 REQ_GROUP("Scrolling") \
304 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
305 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
306 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
307 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
308 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
309 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
310 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
312 REQ_GROUP("Searching") \
313 REQ_(SEARCH, "Search the view"), \
314 REQ_(SEARCH_BACK, "Search backwards in the view"), \
315 REQ_(FIND_NEXT, "Find next search match"), \
316 REQ_(FIND_PREV, "Find previous search match"), \
318 REQ_GROUP("Option manipulation") \
319 REQ_(OPTIONS, "Open option menu"), \
320 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
321 REQ_(TOGGLE_DATE, "Toggle date display"), \
322 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
323 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
324 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
325 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
326 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
327 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
328 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
329 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
330 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
331 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
333 REQ_GROUP("Misc") \
334 REQ_(PROMPT, "Bring up the prompt"), \
335 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
336 REQ_(SHOW_VERSION, "Show version information"), \
337 REQ_(STOP_LOADING, "Stop all loading views"), \
338 REQ_(EDIT, "Open in editor"), \
339 REQ_(NONE, "Do nothing")
342 /* User action requests. */
343 enum request {
344 #define REQ_GROUP(help)
345 #define REQ_(req, help) REQ_##req
347 /* Offset all requests to avoid conflicts with ncurses getch values. */
348 REQ_UNKNOWN = KEY_MAX + 1,
349 REQ_OFFSET,
350 REQ_INFO,
352 /* Internal requests. */
353 REQ_JUMP_COMMIT,
355 #undef REQ_GROUP
356 #undef REQ_
359 struct request_info {
360 enum request request;
361 const char *name;
362 int namelen;
363 const char *help;
366 static const struct request_info req_info[] = {
367 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
368 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
369 REQ_INFO
370 #undef REQ_GROUP
371 #undef REQ_
374 static enum request
375 get_request(const char *name)
377 int namelen = strlen(name);
378 int i;
380 for (i = 0; i < ARRAY_SIZE(req_info); i++)
381 if (enum_equals(req_info[i], name, namelen))
382 return req_info[i].request;
384 return REQ_UNKNOWN;
389 * Options
392 /* Option and state variables. */
393 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
394 static enum date opt_date = DATE_DEFAULT;
395 static enum author opt_author = AUTHOR_FULL;
396 static enum filename opt_filename = FILENAME_AUTO;
397 static bool opt_rev_graph = TRUE;
398 static bool opt_line_number = FALSE;
399 static bool opt_show_refs = TRUE;
400 static bool opt_show_changes = TRUE;
401 static bool opt_untracked_dirs_content = TRUE;
402 static bool opt_read_git_colors = TRUE;
403 static bool opt_ignore_case = FALSE;
404 static int opt_diff_context = 3;
405 static char opt_diff_context_arg[9] = "";
406 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
407 static char opt_ignore_space_arg[22] = "";
408 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
409 static char opt_commit_order_arg[22] = "";
410 static bool opt_notes = TRUE;
411 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
412 static int opt_num_interval = 5;
413 static double opt_hscroll = 0.50;
414 static double opt_scale_split_view = 2.0 / 3.0;
415 static int opt_tab_size = 8;
416 static int opt_author_cols = AUTHOR_COLS;
417 static int opt_filename_cols = FILENAME_COLS;
418 static char opt_path[SIZEOF_STR] = "";
419 static char opt_file[SIZEOF_STR] = "";
420 static char opt_ref[SIZEOF_REF] = "";
421 static unsigned long opt_goto_line = 0;
422 static char opt_head[SIZEOF_REF] = "";
423 static char opt_remote[SIZEOF_REF] = "";
424 static struct encoding *opt_encoding = NULL;
425 static iconv_t opt_iconv_out = ICONV_NONE;
426 static char opt_search[SIZEOF_STR] = "";
427 static char opt_cdup[SIZEOF_STR] = "";
428 static char opt_prefix[SIZEOF_STR] = "";
429 static char opt_git_dir[SIZEOF_STR] = "";
430 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
431 static char opt_editor[SIZEOF_STR] = "";
432 static FILE *opt_tty = NULL;
433 static const char **opt_diff_argv = NULL;
434 static const char **opt_rev_argv = NULL;
435 static const char **opt_file_argv = NULL;
436 static const char **opt_blame_argv = NULL;
437 static int opt_lineno = 0;
439 #define is_initial_commit() (!get_ref_head())
440 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
441 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
443 static inline void
444 update_diff_context_arg(int diff_context)
446 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
447 string_ncopy(opt_diff_context_arg, "-U3", 3);
450 static inline void
451 update_ignore_space_arg()
453 if (opt_ignore_space == IGNORE_SPACE_ALL) {
454 string_copy(opt_ignore_space_arg, "--ignore-all-space");
455 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
456 string_copy(opt_ignore_space_arg, "--ignore-space-change");
457 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
458 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
459 } else {
460 string_copy(opt_ignore_space_arg, "");
464 static inline void
465 update_commit_order_arg()
467 if (opt_commit_order == COMMIT_ORDER_TOPO) {
468 string_copy(opt_commit_order_arg, "--topo-order");
469 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
470 string_copy(opt_commit_order_arg, "--date-order");
471 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
472 string_copy(opt_commit_order_arg, "--reverse");
473 } else {
474 string_copy(opt_commit_order_arg, "");
478 static inline void
479 update_notes_arg()
481 if (opt_notes) {
482 string_copy(opt_notes_arg, "--show-notes");
483 } else {
484 /* Notes are disabled by default when passing --pretty args. */
485 string_copy(opt_notes_arg, "");
490 * Line-oriented content detection.
493 #define LINE_INFO \
494 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
495 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
496 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
497 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
498 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
499 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
500 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
501 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
506 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
507 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
508 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
509 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
510 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
511 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
512 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
513 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
515 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
517 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
518 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
519 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
520 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
521 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
522 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
527 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
528 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
529 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
530 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
531 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
532 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
533 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
534 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
535 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
536 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
537 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
538 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
539 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
540 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
541 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
542 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
543 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
544 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
545 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
546 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
547 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
548 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
549 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
550 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
551 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
553 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
554 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
555 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
556 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
557 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
558 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
559 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
560 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
561 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
562 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
563 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
564 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
565 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
567 enum line_type {
568 #define LINE(type, line, fg, bg, attr) \
569 LINE_##type
570 LINE_INFO,
571 LINE_NONE
572 #undef LINE
575 struct line_info {
576 const char *name; /* Option name. */
577 int namelen; /* Size of option name. */
578 const char *line; /* The start of line to match. */
579 int linelen; /* Size of string to match. */
580 int fg, bg, attr; /* Color and text attributes for the lines. */
581 int color_pair;
584 static struct line_info line_info[] = {
585 #define LINE(type, line, fg, bg, attr) \
586 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
587 LINE_INFO
588 #undef LINE
591 static struct line_info **color_pair;
592 static size_t color_pairs;
594 static struct line_info *custom_color;
595 static size_t custom_colors;
597 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
598 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
600 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
601 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
603 /* Color IDs must be 1 or higher. [GH #15] */
604 #define COLOR_ID(line_type) ((line_type) + 1)
606 static enum line_type
607 get_line_type(const char *line)
609 int linelen = strlen(line);
610 enum line_type type;
612 for (type = 0; type < custom_colors; type++)
613 /* Case insensitive search matches Signed-off-by lines better. */
614 if (linelen >= custom_color[type].linelen &&
615 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
616 return TO_CUSTOM_COLOR_TYPE(type);
618 for (type = 0; type < ARRAY_SIZE(line_info); type++)
619 /* Case insensitive search matches Signed-off-by lines better. */
620 if (linelen >= line_info[type].linelen &&
621 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
622 return type;
624 return LINE_DEFAULT;
627 static enum line_type
628 get_line_type_from_ref(const struct ref *ref)
630 if (ref->head)
631 return LINE_MAIN_HEAD;
632 else if (ref->ltag)
633 return LINE_MAIN_LOCAL_TAG;
634 else if (ref->tag)
635 return LINE_MAIN_TAG;
636 else if (ref->tracked)
637 return LINE_MAIN_TRACKED;
638 else if (ref->remote)
639 return LINE_MAIN_REMOTE;
640 else if (ref->replace)
641 return LINE_MAIN_REPLACE;
643 return LINE_MAIN_REF;
646 static inline struct line_info *
647 get_line(enum line_type type)
649 if (type > LINE_NONE) {
650 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
651 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
652 } else {
653 assert(type < ARRAY_SIZE(line_info));
654 return &line_info[type];
658 static inline int
659 get_line_color(enum line_type type)
661 return COLOR_ID(get_line(type)->color_pair);
664 static inline int
665 get_line_attr(enum line_type type)
667 struct line_info *info = get_line(type);
669 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
672 static struct line_info *
673 get_line_info(const char *name)
675 size_t namelen = strlen(name);
676 enum line_type type;
678 for (type = 0; type < ARRAY_SIZE(line_info); type++)
679 if (enum_equals(line_info[type], name, namelen))
680 return &line_info[type];
682 return NULL;
685 static struct line_info *
686 add_custom_color(const char *quoted_line)
688 struct line_info *info;
689 char *line;
690 size_t linelen;
692 if (!realloc_custom_color(&custom_color, custom_colors, 1))
693 die("Failed to alloc custom line info");
695 linelen = strlen(quoted_line) - 1;
696 line = malloc(linelen);
697 if (!line)
698 return NULL;
700 strncpy(line, quoted_line + 1, linelen);
701 line[linelen - 1] = 0;
703 info = &custom_color[custom_colors++];
704 info->name = info->line = line;
705 info->namelen = info->linelen = strlen(line);
707 return info;
710 static void
711 init_line_info_color_pair(struct line_info *info, enum line_type type,
712 int default_bg, int default_fg)
714 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
715 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
716 int i;
718 for (i = 0; i < color_pairs; i++) {
719 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
720 info->color_pair = i;
721 return;
725 if (!realloc_color_pair(&color_pair, color_pairs, 1))
726 die("Failed to alloc color pair");
728 color_pair[color_pairs] = info;
729 info->color_pair = color_pairs++;
730 init_pair(COLOR_ID(info->color_pair), fg, bg);
733 static void
734 init_colors(void)
736 int default_bg = line_info[LINE_DEFAULT].bg;
737 int default_fg = line_info[LINE_DEFAULT].fg;
738 enum line_type type;
740 start_color();
742 if (assume_default_colors(default_fg, default_bg) == ERR) {
743 default_bg = COLOR_BLACK;
744 default_fg = COLOR_WHITE;
747 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
748 struct line_info *info = &line_info[type];
750 init_line_info_color_pair(info, type, default_bg, default_fg);
753 for (type = 0; type < custom_colors; type++) {
754 struct line_info *info = &custom_color[type];
756 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
757 default_bg, default_fg);
761 struct line {
762 enum line_type type;
763 unsigned int lineno:24;
765 /* State flags */
766 unsigned int selected:1;
767 unsigned int dirty:1;
768 unsigned int cleareol:1;
769 unsigned int dont_free:1;
771 void *data; /* User data */
776 * Keys
779 struct keybinding {
780 int alias;
781 enum request request;
784 static struct keybinding default_keybindings[] = {
785 /* View switching */
786 { 'm', REQ_VIEW_MAIN },
787 { 'd', REQ_VIEW_DIFF },
788 { 'l', REQ_VIEW_LOG },
789 { 't', REQ_VIEW_TREE },
790 { 'f', REQ_VIEW_BLOB },
791 { 'B', REQ_VIEW_BLAME },
792 { 'H', REQ_VIEW_BRANCH },
793 { 'p', REQ_VIEW_PAGER },
794 { 'h', REQ_VIEW_HELP },
795 { 'S', REQ_VIEW_STATUS },
796 { 'c', REQ_VIEW_STAGE },
798 /* View manipulation */
799 { 'q', REQ_VIEW_CLOSE },
800 { KEY_TAB, REQ_VIEW_NEXT },
801 { KEY_RETURN, REQ_ENTER },
802 { KEY_UP, REQ_PREVIOUS },
803 { KEY_CTL('P'), REQ_PREVIOUS },
804 { KEY_DOWN, REQ_NEXT },
805 { KEY_CTL('N'), REQ_NEXT },
806 { 'R', REQ_REFRESH },
807 { KEY_F(5), REQ_REFRESH },
808 { 'O', REQ_MAXIMIZE },
809 { ',', REQ_PARENT },
811 /* View specific */
812 { 'u', REQ_STATUS_UPDATE },
813 { '!', REQ_STATUS_REVERT },
814 { 'M', REQ_STATUS_MERGE },
815 { '1', REQ_STAGE_UPDATE_LINE },
816 { '@', REQ_STAGE_NEXT },
817 { '[', REQ_DIFF_CONTEXT_DOWN },
818 { ']', REQ_DIFF_CONTEXT_UP },
820 /* Cursor navigation */
821 { 'k', REQ_MOVE_UP },
822 { 'j', REQ_MOVE_DOWN },
823 { KEY_HOME, REQ_MOVE_FIRST_LINE },
824 { KEY_END, REQ_MOVE_LAST_LINE },
825 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
826 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
827 { ' ', REQ_MOVE_PAGE_DOWN },
828 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
829 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
830 { 'b', REQ_MOVE_PAGE_UP },
831 { '-', REQ_MOVE_PAGE_UP },
833 /* Scrolling */
834 { '|', REQ_SCROLL_FIRST_COL },
835 { KEY_LEFT, REQ_SCROLL_LEFT },
836 { KEY_RIGHT, REQ_SCROLL_RIGHT },
837 { KEY_IC, REQ_SCROLL_LINE_UP },
838 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
839 { KEY_DC, REQ_SCROLL_LINE_DOWN },
840 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
841 { 'w', REQ_SCROLL_PAGE_UP },
842 { 's', REQ_SCROLL_PAGE_DOWN },
844 /* Searching */
845 { '/', REQ_SEARCH },
846 { '?', REQ_SEARCH_BACK },
847 { 'n', REQ_FIND_NEXT },
848 { 'N', REQ_FIND_PREV },
850 /* Misc */
851 { 'Q', REQ_QUIT },
852 { 'z', REQ_STOP_LOADING },
853 { 'v', REQ_SHOW_VERSION },
854 { 'r', REQ_SCREEN_REDRAW },
855 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
856 { 'o', REQ_OPTIONS },
857 { '.', REQ_TOGGLE_LINENO },
858 { 'D', REQ_TOGGLE_DATE },
859 { 'A', REQ_TOGGLE_AUTHOR },
860 { 'g', REQ_TOGGLE_REV_GRAPH },
861 { '~', REQ_TOGGLE_GRAPHIC },
862 { '#', REQ_TOGGLE_FILENAME },
863 { 'F', REQ_TOGGLE_REFS },
864 { 'I', REQ_TOGGLE_SORT_ORDER },
865 { 'i', REQ_TOGGLE_SORT_FIELD },
866 { 'W', REQ_TOGGLE_IGNORE_SPACE },
867 { ':', REQ_PROMPT },
868 { 'e', REQ_EDIT },
871 struct keymap {
872 const char *name;
873 struct keymap *next;
874 struct keybinding *data;
875 size_t size;
876 bool hidden;
879 static struct keymap generic_keymap = { "generic" };
880 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
882 static struct keymap *keymaps = &generic_keymap;
884 static void
885 add_keymap(struct keymap *keymap)
887 keymap->next = keymaps;
888 keymaps = keymap;
891 static struct keymap *
892 get_keymap(const char *name)
894 struct keymap *keymap = keymaps;
896 while (keymap) {
897 if (!strcasecmp(keymap->name, name))
898 return keymap;
899 keymap = keymap->next;
902 return NULL;
906 static void
907 add_keybinding(struct keymap *table, enum request request, int key)
909 size_t i;
911 for (i = 0; i < table->size; i++) {
912 if (table->data[i].alias == key) {
913 table->data[i].request = request;
914 return;
918 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
919 if (!table->data)
920 die("Failed to allocate keybinding");
921 table->data[table->size].alias = key;
922 table->data[table->size++].request = request;
924 if (request == REQ_NONE && is_generic_keymap(table)) {
925 int i;
927 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
928 if (default_keybindings[i].alias == key)
929 default_keybindings[i].request = REQ_NONE;
933 /* Looks for a key binding first in the given map, then in the generic map, and
934 * lastly in the default keybindings. */
935 static enum request
936 get_keybinding(struct keymap *keymap, int key)
938 size_t i;
940 for (i = 0; i < keymap->size; i++)
941 if (keymap->data[i].alias == key)
942 return keymap->data[i].request;
944 for (i = 0; i < generic_keymap.size; i++)
945 if (generic_keymap.data[i].alias == key)
946 return generic_keymap.data[i].request;
948 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
949 if (default_keybindings[i].alias == key)
950 return default_keybindings[i].request;
952 return (enum request) key;
956 struct key {
957 const char *name;
958 int value;
961 static const struct key key_table[] = {
962 { "Enter", KEY_RETURN },
963 { "Space", ' ' },
964 { "Backspace", KEY_BACKSPACE },
965 { "Tab", KEY_TAB },
966 { "Escape", KEY_ESC },
967 { "Left", KEY_LEFT },
968 { "Right", KEY_RIGHT },
969 { "Up", KEY_UP },
970 { "Down", KEY_DOWN },
971 { "Insert", KEY_IC },
972 { "Delete", KEY_DC },
973 { "Hash", '#' },
974 { "Home", KEY_HOME },
975 { "End", KEY_END },
976 { "PageUp", KEY_PPAGE },
977 { "PageDown", KEY_NPAGE },
978 { "F1", KEY_F(1) },
979 { "F2", KEY_F(2) },
980 { "F3", KEY_F(3) },
981 { "F4", KEY_F(4) },
982 { "F5", KEY_F(5) },
983 { "F6", KEY_F(6) },
984 { "F7", KEY_F(7) },
985 { "F8", KEY_F(8) },
986 { "F9", KEY_F(9) },
987 { "F10", KEY_F(10) },
988 { "F11", KEY_F(11) },
989 { "F12", KEY_F(12) },
992 static int
993 get_key_value(const char *name)
995 int i;
997 for (i = 0; i < ARRAY_SIZE(key_table); i++)
998 if (!strcasecmp(key_table[i].name, name))
999 return key_table[i].value;
1001 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1002 return (int)name[1] & 0x1f;
1003 if (strlen(name) == 1 && isprint(*name))
1004 return (int) *name;
1005 return ERR;
1008 static const char *
1009 get_key_name(int key_value)
1011 static char key_char[] = "'X'\0";
1012 const char *seq = NULL;
1013 int key;
1015 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1016 if (key_table[key].value == key_value)
1017 seq = key_table[key].name;
1019 if (seq == NULL && key_value < 0x7f) {
1020 char *s = key_char + 1;
1022 if (key_value >= 0x20) {
1023 *s++ = key_value;
1024 } else {
1025 *s++ = '^';
1026 *s++ = 0x40 | (key_value & 0x1f);
1028 *s++ = '\'';
1029 *s++ = '\0';
1030 seq = key_char;
1033 return seq ? seq : "(no key)";
1036 static bool
1037 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1039 const char *sep = *pos > 0 ? ", " : "";
1040 const char *keyname = get_key_name(keybinding->alias);
1042 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1045 static bool
1046 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1047 struct keymap *keymap, bool all)
1049 int i;
1051 for (i = 0; i < keymap->size; i++) {
1052 if (keymap->data[i].request == request) {
1053 if (!append_key(buf, pos, &keymap->data[i]))
1054 return FALSE;
1055 if (!all)
1056 break;
1060 return TRUE;
1063 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1065 static const char *
1066 get_keys(struct keymap *keymap, enum request request, bool all)
1068 static char buf[BUFSIZ];
1069 size_t pos = 0;
1070 int i;
1072 buf[pos] = 0;
1074 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1075 return "Too many keybindings!";
1076 if (pos > 0 && !all)
1077 return buf;
1079 if (!is_generic_keymap(keymap)) {
1080 /* Only the generic keymap includes the default keybindings when
1081 * listing all keys. */
1082 if (all)
1083 return buf;
1085 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1086 return "Too many keybindings!";
1087 if (pos)
1088 return buf;
1091 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1092 if (default_keybindings[i].request == request) {
1093 if (!append_key(buf, &pos, &default_keybindings[i]))
1094 return "Too many keybindings!";
1095 if (!all)
1096 return buf;
1100 return buf;
1103 enum run_request_flag {
1104 RUN_REQUEST_DEFAULT = 0,
1105 RUN_REQUEST_FORCE = 1,
1106 RUN_REQUEST_SILENT = 2,
1107 RUN_REQUEST_CONFIRM = 4,
1110 struct run_request {
1111 struct keymap *keymap;
1112 int key;
1113 const char **argv;
1114 bool silent;
1115 bool confirm;
1118 static struct run_request *run_request;
1119 static size_t run_requests;
1121 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1123 static bool
1124 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1126 bool force = flags & RUN_REQUEST_FORCE;
1127 struct run_request *req;
1129 if (!force && get_keybinding(keymap, key) != key)
1130 return TRUE;
1132 if (!realloc_run_requests(&run_request, run_requests, 1))
1133 return FALSE;
1135 if (!argv_copy(&run_request[run_requests].argv, argv))
1136 return FALSE;
1138 req = &run_request[run_requests++];
1139 req->silent = flags & RUN_REQUEST_SILENT;
1140 req->confirm = flags & RUN_REQUEST_CONFIRM;
1141 req->keymap = keymap;
1142 req->key = key;
1144 add_keybinding(keymap, REQ_NONE + run_requests, key);
1145 return TRUE;
1148 static struct run_request *
1149 get_run_request(enum request request)
1151 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1152 return NULL;
1153 return &run_request[request - REQ_NONE - 1];
1156 static void
1157 add_builtin_run_requests(void)
1159 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1160 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1161 const char *commit[] = { "git", "commit", NULL };
1162 const char *gc[] = { "git", "gc", NULL };
1164 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1165 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1166 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1167 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1171 * User config file handling.
1174 #define OPT_ERR_INFO \
1175 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1176 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1177 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1178 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1179 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1180 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1181 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1182 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1183 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1184 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1185 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1186 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1187 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1188 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1189 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1190 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1191 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1192 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1193 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1195 enum option_code {
1196 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1197 OPT_ERR_INFO
1198 #undef OPT_ERR_
1199 OPT_OK
1202 static const char *option_errors[] = {
1203 #define OPT_ERR_(name, msg) msg
1204 OPT_ERR_INFO
1205 #undef OPT_ERR_
1208 static const struct enum_map color_map[] = {
1209 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1210 COLOR_MAP(DEFAULT),
1211 COLOR_MAP(BLACK),
1212 COLOR_MAP(BLUE),
1213 COLOR_MAP(CYAN),
1214 COLOR_MAP(GREEN),
1215 COLOR_MAP(MAGENTA),
1216 COLOR_MAP(RED),
1217 COLOR_MAP(WHITE),
1218 COLOR_MAP(YELLOW),
1221 static const struct enum_map attr_map[] = {
1222 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1223 ATTR_MAP(NORMAL),
1224 ATTR_MAP(BLINK),
1225 ATTR_MAP(BOLD),
1226 ATTR_MAP(DIM),
1227 ATTR_MAP(REVERSE),
1228 ATTR_MAP(STANDOUT),
1229 ATTR_MAP(UNDERLINE),
1232 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1234 static enum option_code
1235 parse_step(double *opt, const char *arg)
1237 *opt = atoi(arg);
1238 if (!strchr(arg, '%'))
1239 return OPT_OK;
1241 /* "Shift down" so 100% and 1 does not conflict. */
1242 *opt = (*opt - 1) / 100;
1243 if (*opt >= 1.0) {
1244 *opt = 0.99;
1245 return OPT_ERR_INVALID_STEP_VALUE;
1247 if (*opt < 0.0) {
1248 *opt = 1;
1249 return OPT_ERR_INVALID_STEP_VALUE;
1251 return OPT_OK;
1254 static enum option_code
1255 parse_int(int *opt, const char *arg, int min, int max)
1257 int value = atoi(arg);
1259 if (min <= value && value <= max) {
1260 *opt = value;
1261 return OPT_OK;
1264 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1267 static bool
1268 set_color(int *color, const char *name)
1270 if (map_enum(color, color_map, name))
1271 return TRUE;
1272 if (!prefixcmp(name, "color"))
1273 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1274 return FALSE;
1277 /* Wants: object fgcolor bgcolor [attribute] */
1278 static enum option_code
1279 option_color_command(int argc, const char *argv[])
1281 struct line_info *info;
1283 if (argc < 3)
1284 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1286 if (*argv[0] == '"' || *argv[0] == '\'') {
1287 info = add_custom_color(argv[0]);
1288 } else {
1289 info = get_line_info(argv[0]);
1291 if (!info) {
1292 static const struct enum_map obsolete[] = {
1293 ENUM_MAP("main-delim", LINE_DELIMITER),
1294 ENUM_MAP("main-date", LINE_DATE),
1295 ENUM_MAP("main-author", LINE_AUTHOR),
1297 int index;
1299 if (!map_enum(&index, obsolete, argv[0]))
1300 return OPT_ERR_UNKNOWN_COLOR_NAME;
1301 info = &line_info[index];
1304 if (!set_color(&info->fg, argv[1]) ||
1305 !set_color(&info->bg, argv[2]))
1306 return OPT_ERR_UNKNOWN_COLOR;
1308 info->attr = 0;
1309 while (argc-- > 3) {
1310 int attr;
1312 if (!set_attribute(&attr, argv[argc]))
1313 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1314 info->attr |= attr;
1317 return OPT_OK;
1320 static enum option_code
1321 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1323 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1324 ? TRUE : FALSE;
1325 if (matched)
1326 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1327 return OPT_OK;
1330 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1332 static enum option_code
1333 parse_enum_do(unsigned int *opt, const char *arg,
1334 const struct enum_map *map, size_t map_size)
1336 bool is_true;
1338 assert(map_size > 1);
1340 if (map_enum_do(map, map_size, (int *) opt, arg))
1341 return OPT_OK;
1343 parse_bool(&is_true, arg);
1344 *opt = is_true ? map[1].value : map[0].value;
1345 return OPT_OK;
1348 #define parse_enum(opt, arg, map) \
1349 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1351 static enum option_code
1352 parse_string(char *opt, const char *arg, size_t optsize)
1354 int arglen = strlen(arg);
1356 switch (arg[0]) {
1357 case '\"':
1358 case '\'':
1359 if (arglen == 1 || arg[arglen - 1] != arg[0])
1360 return OPT_ERR_UNMATCHED_QUOTATION;
1361 arg += 1; arglen -= 2;
1362 default:
1363 string_ncopy_do(opt, optsize, arg, arglen);
1364 return OPT_OK;
1368 static enum option_code
1369 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1371 char buf[SIZEOF_STR];
1372 enum option_code code = parse_string(buf, arg, sizeof(buf));
1374 if (code == OPT_OK) {
1375 struct encoding *encoding = *encoding_ref;
1377 if (encoding && !priority)
1378 return code;
1379 encoding = encoding_open(buf);
1380 if (encoding)
1381 *encoding_ref = encoding;
1384 return code;
1387 static enum option_code
1388 parse_args(const char ***args, const char *argv[])
1390 if (*args == NULL && !argv_copy(args, argv))
1391 return OPT_ERR_OUT_OF_MEMORY;
1392 return OPT_OK;
1395 /* Wants: name = value */
1396 static enum option_code
1397 option_set_command(int argc, const char *argv[])
1399 if (argc < 3)
1400 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1402 if (strcmp(argv[1], "="))
1403 return OPT_ERR_NO_VALUE_ASSIGNED;
1405 if (!strcmp(argv[0], "blame-options"))
1406 return parse_args(&opt_blame_argv, argv + 2);
1408 if (argc != 3)
1409 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1411 if (!strcmp(argv[0], "show-author"))
1412 return parse_enum(&opt_author, argv[2], author_map);
1414 if (!strcmp(argv[0], "show-date"))
1415 return parse_enum(&opt_date, argv[2], date_map);
1417 if (!strcmp(argv[0], "show-rev-graph"))
1418 return parse_bool(&opt_rev_graph, argv[2]);
1420 if (!strcmp(argv[0], "show-refs"))
1421 return parse_bool(&opt_show_refs, argv[2]);
1423 if (!strcmp(argv[0], "show-changes"))
1424 return parse_bool(&opt_show_changes, argv[2]);
1426 if (!strcmp(argv[0], "show-notes")) {
1427 bool matched = FALSE;
1428 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1430 if (res == OPT_OK && matched) {
1431 update_notes_arg();
1432 return res;
1435 opt_notes = TRUE;
1436 strcpy(opt_notes_arg, "--show-notes=");
1437 res = parse_string(opt_notes_arg + 8, argv[2],
1438 sizeof(opt_notes_arg) - 8);
1439 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1440 opt_notes_arg[7] = '\0';
1441 return res;
1444 if (!strcmp(argv[0], "show-line-numbers"))
1445 return parse_bool(&opt_line_number, argv[2]);
1447 if (!strcmp(argv[0], "line-graphics"))
1448 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1450 if (!strcmp(argv[0], "line-number-interval"))
1451 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1453 if (!strcmp(argv[0], "author-width"))
1454 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1456 if (!strcmp(argv[0], "filename-width"))
1457 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1459 if (!strcmp(argv[0], "show-filename"))
1460 return parse_enum(&opt_filename, argv[2], filename_map);
1462 if (!strcmp(argv[0], "horizontal-scroll"))
1463 return parse_step(&opt_hscroll, argv[2]);
1465 if (!strcmp(argv[0], "split-view-height"))
1466 return parse_step(&opt_scale_split_view, argv[2]);
1468 if (!strcmp(argv[0], "tab-size"))
1469 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1471 if (!strcmp(argv[0], "diff-context")) {
1472 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1474 if (code == OPT_OK)
1475 update_diff_context_arg(opt_diff_context);
1476 return code;
1479 if (!strcmp(argv[0], "ignore-space")) {
1480 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1482 if (code == OPT_OK)
1483 update_ignore_space_arg();
1484 return code;
1487 if (!strcmp(argv[0], "commit-order")) {
1488 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1490 if (code == OPT_OK)
1491 update_commit_order_arg();
1492 return code;
1495 if (!strcmp(argv[0], "status-untracked-dirs"))
1496 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1498 if (!strcmp(argv[0], "use-git-colors"))
1499 return parse_bool(&opt_read_git_colors, argv[2]);
1501 if (!strcmp(argv[0], "ignore-case"))
1502 return parse_bool(&opt_ignore_case, argv[2]);
1504 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1507 /* Wants: mode request key */
1508 static enum option_code
1509 option_bind_command(int argc, const char *argv[])
1511 enum request request;
1512 struct keymap *keymap;
1513 int key;
1515 if (argc < 3)
1516 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1518 if (!(keymap = get_keymap(argv[0])))
1519 return OPT_ERR_UNKNOWN_KEY_MAP;
1521 key = get_key_value(argv[1]);
1522 if (key == ERR)
1523 return OPT_ERR_UNKNOWN_KEY;
1525 request = get_request(argv[2]);
1526 if (request == REQ_UNKNOWN) {
1527 static const struct enum_map obsolete[] = {
1528 ENUM_MAP("cherry-pick", REQ_NONE),
1529 ENUM_MAP("screen-resize", REQ_NONE),
1530 ENUM_MAP("tree-parent", REQ_PARENT),
1532 int alias;
1534 if (map_enum(&alias, obsolete, argv[2])) {
1535 if (alias != REQ_NONE)
1536 add_keybinding(keymap, alias, key);
1537 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1540 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1541 enum run_request_flag flags = RUN_REQUEST_FORCE;
1543 while (*argv[2]) {
1544 if (*argv[2] == '@') {
1545 flags |= RUN_REQUEST_SILENT;
1546 } else if (*argv[2] == '?') {
1547 flags |= RUN_REQUEST_CONFIRM;
1548 } else {
1549 break;
1551 argv[2]++;
1554 return add_run_request(keymap, key, argv + 2, flags)
1555 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1557 if (request == REQ_UNKNOWN)
1558 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1560 add_keybinding(keymap, request, key);
1562 return OPT_OK;
1566 static enum option_code load_option_file(const char *path);
1568 static enum option_code
1569 option_source_command(int argc, const char *argv[])
1571 if (argc < 1)
1572 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1574 return load_option_file(argv[0]);
1577 static enum option_code
1578 set_option(const char *opt, char *value)
1580 const char *argv[SIZEOF_ARG];
1581 int argc = 0;
1583 if (!argv_from_string(argv, &argc, value))
1584 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1586 if (!strcmp(opt, "color"))
1587 return option_color_command(argc, argv);
1589 if (!strcmp(opt, "set"))
1590 return option_set_command(argc, argv);
1592 if (!strcmp(opt, "bind"))
1593 return option_bind_command(argc, argv);
1595 if (!strcmp(opt, "source"))
1596 return option_source_command(argc, argv);
1598 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1601 struct config_state {
1602 const char *path;
1603 int lineno;
1604 bool errors;
1607 static int
1608 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1610 struct config_state *config = data;
1611 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1613 config->lineno++;
1615 /* Check for comment markers, since read_properties() will
1616 * only ensure opt and value are split at first " \t". */
1617 optlen = strcspn(opt, "#");
1618 if (optlen == 0)
1619 return OK;
1621 if (opt[optlen] == 0) {
1622 /* Look for comment endings in the value. */
1623 size_t len = strcspn(value, "#");
1625 if (len < valuelen) {
1626 valuelen = len;
1627 value[valuelen] = 0;
1630 status = set_option(opt, value);
1633 if (status != OPT_OK) {
1634 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1635 option_errors[status], (int) optlen, opt);
1636 config->errors = TRUE;
1639 /* Always keep going if errors are encountered. */
1640 return OK;
1643 static enum option_code
1644 load_option_file(const char *path)
1646 struct config_state config = { path, 0, FALSE };
1647 struct io io;
1649 /* Do not read configuration from stdin if set to "" */
1650 if (!path || !strlen(path))
1651 return OPT_OK;
1653 /* It's OK that the file doesn't exist. */
1654 if (!io_open(&io, "%s", path))
1655 return OPT_ERR_FILE_DOES_NOT_EXIST;
1657 if (io_load(&io, " \t", read_option, &config) == ERR ||
1658 config.errors == TRUE)
1659 warn("Errors while loading %s.", path);
1660 return OPT_OK;
1663 static int
1664 load_options(void)
1666 const char *home = getenv("HOME");
1667 const char *tigrc_user = getenv("TIGRC_USER");
1668 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1669 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1670 char buf[SIZEOF_STR];
1672 if (!tigrc_system)
1673 tigrc_system = SYSCONFDIR "/tigrc";
1674 load_option_file(tigrc_system);
1676 if (!tigrc_user) {
1677 if (!home || !string_format(buf, "%s/.tigrc", home))
1678 return ERR;
1679 tigrc_user = buf;
1681 load_option_file(tigrc_user);
1683 /* Add _after_ loading config files to avoid adding run requests
1684 * that conflict with keybindings. */
1685 add_builtin_run_requests();
1687 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1688 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1689 int argc = 0;
1691 if (!string_format(buf, "%s", tig_diff_opts) ||
1692 !argv_from_string(diff_opts, &argc, buf))
1693 die("TIG_DIFF_OPTS contains too many arguments");
1694 else if (!argv_copy(&opt_diff_argv, diff_opts))
1695 die("Failed to format TIG_DIFF_OPTS arguments");
1698 return OK;
1703 * The viewer
1706 struct view;
1707 struct view_ops;
1709 /* The display array of active views and the index of the current view. */
1710 static struct view *display[2];
1711 static WINDOW *display_win[2];
1712 static WINDOW *display_title[2];
1713 static unsigned int current_view;
1715 #define foreach_displayed_view(view, i) \
1716 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1718 #define displayed_views() (display[1] != NULL ? 2 : 1)
1720 /* Current head and commit ID */
1721 static char ref_blob[SIZEOF_REF] = "";
1722 static char ref_commit[SIZEOF_REF] = "HEAD";
1723 static char ref_head[SIZEOF_REF] = "HEAD";
1724 static char ref_branch[SIZEOF_REF] = "";
1726 enum view_flag {
1727 VIEW_NO_FLAGS = 0,
1728 VIEW_ALWAYS_LINENO = 1 << 0,
1729 VIEW_CUSTOM_STATUS = 1 << 1,
1730 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1731 VIEW_ADD_PAGER_REFS = 1 << 3,
1732 VIEW_OPEN_DIFF = 1 << 4,
1733 VIEW_NO_REF = 1 << 5,
1734 VIEW_NO_GIT_DIR = 1 << 6,
1735 VIEW_DIFF_LIKE = 1 << 7,
1738 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1740 struct position {
1741 unsigned long offset; /* Offset of the window top */
1742 unsigned long col; /* Offset from the window side. */
1743 unsigned long lineno; /* Current line number */
1746 struct view {
1747 const char *name; /* View name */
1748 const char *id; /* Points to either of ref_{head,commit,blob} */
1750 struct view_ops *ops; /* View operations */
1752 char ref[SIZEOF_REF]; /* Hovered commit reference */
1753 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1755 int height, width; /* The width and height of the main window */
1756 WINDOW *win; /* The main window */
1758 /* Navigation */
1759 struct position pos; /* Current position. */
1760 struct position prev_pos; /* Previous position. */
1762 /* Searching */
1763 char grep[SIZEOF_STR]; /* Search string */
1764 regex_t *regex; /* Pre-compiled regexp */
1766 /* If non-NULL, points to the view that opened this view. If this view
1767 * is closed tig will switch back to the parent view. */
1768 struct view *parent;
1769 struct view *prev;
1771 /* Buffering */
1772 size_t lines; /* Total number of lines */
1773 struct line *line; /* Line index */
1774 unsigned int digits; /* Number of digits in the lines member. */
1776 /* Number of lines with custom status, not to be counted in the
1777 * view title. */
1778 unsigned int custom_lines;
1780 /* Drawing */
1781 struct line *curline; /* Line currently being drawn. */
1782 enum line_type curtype; /* Attribute currently used for drawing. */
1783 unsigned long col; /* Column when drawing. */
1784 bool has_scrolled; /* View was scrolled. */
1786 /* Loading */
1787 const char **argv; /* Shell command arguments. */
1788 const char *dir; /* Directory from which to execute. */
1789 struct io io;
1790 struct io *pipe;
1791 time_t start_time;
1792 time_t update_secs;
1793 struct encoding *encoding;
1795 /* Private data */
1796 void *private;
1799 enum open_flags {
1800 OPEN_DEFAULT = 0, /* Use default view switching. */
1801 OPEN_SPLIT = 1, /* Split current view. */
1802 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1803 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1804 OPEN_PREPARED = 32, /* Open already prepared command. */
1805 OPEN_EXTRA = 64, /* Open extra data from command. */
1808 struct view_ops {
1809 /* What type of content being displayed. Used in the title bar. */
1810 const char *type;
1811 /* What keymap does this view have */
1812 struct keymap keymap;
1813 /* Flags to control the view behavior. */
1814 enum view_flag flags;
1815 /* Size of private data. */
1816 size_t private_size;
1817 /* Open and reads in all view content. */
1818 bool (*open)(struct view *view, enum open_flags flags);
1819 /* Read one line; updates view->line. */
1820 bool (*read)(struct view *view, char *data);
1821 /* Draw one line; @lineno must be < view->height. */
1822 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1823 /* Depending on view handle a special requests. */
1824 enum request (*request)(struct view *view, enum request request, struct line *line);
1825 /* Search for regexp in a line. */
1826 bool (*grep)(struct view *view, struct line *line);
1827 /* Select line */
1828 void (*select)(struct view *view, struct line *line);
1831 #define VIEW_OPS(id, name, ref) name##_ops
1832 static struct view_ops VIEW_INFO(VIEW_OPS);
1834 static struct view views[] = {
1835 #define VIEW_DATA(id, name, ref) \
1836 { #name, ref, &name##_ops }
1837 VIEW_INFO(VIEW_DATA)
1840 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1842 #define foreach_view(view, i) \
1843 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1845 #define view_is_displayed(view) \
1846 (view == display[0] || view == display[1])
1848 #define view_has_line(view, line_) \
1849 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1851 static enum request
1852 view_request(struct view *view, enum request request)
1854 if (!view || !view->lines)
1855 return request;
1856 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1860 * View drawing.
1863 static inline void
1864 set_view_attr(struct view *view, enum line_type type)
1866 if (!view->curline->selected && view->curtype != type) {
1867 (void) wattrset(view->win, get_line_attr(type));
1868 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1869 view->curtype = type;
1873 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1875 static bool
1876 draw_chars(struct view *view, enum line_type type, const char *string,
1877 int max_len, bool use_tilde)
1879 static char out_buffer[BUFSIZ * 2];
1880 int len = 0;
1881 int col = 0;
1882 int trimmed = FALSE;
1883 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1885 if (max_len <= 0)
1886 return VIEW_MAX_LEN(view) <= 0;
1888 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1890 set_view_attr(view, type);
1891 if (len > 0) {
1892 if (opt_iconv_out != ICONV_NONE) {
1893 size_t inlen = len + 1;
1894 char *instr = calloc(1, inlen);
1895 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1896 if (!instr)
1897 return VIEW_MAX_LEN(view) <= 0;
1899 strncpy(instr, string, len);
1901 char *outbuf = out_buffer;
1902 size_t outlen = sizeof(out_buffer);
1904 size_t ret;
1906 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1907 if (ret != (size_t) -1) {
1908 string = out_buffer;
1909 len = sizeof(out_buffer) - outlen;
1911 free(instr);
1914 waddnstr(view->win, string, len);
1916 if (trimmed && use_tilde) {
1917 set_view_attr(view, LINE_DELIMITER);
1918 waddch(view->win, '~');
1919 col++;
1923 view->col += col;
1924 return VIEW_MAX_LEN(view) <= 0;
1927 static bool
1928 draw_space(struct view *view, enum line_type type, int max, int spaces)
1930 static char space[] = " ";
1932 spaces = MIN(max, spaces);
1934 while (spaces > 0) {
1935 int len = MIN(spaces, sizeof(space) - 1);
1937 if (draw_chars(view, type, space, len, FALSE))
1938 return TRUE;
1939 spaces -= len;
1942 return VIEW_MAX_LEN(view) <= 0;
1945 static bool
1946 draw_text(struct view *view, enum line_type type, const char *string)
1948 static char text[SIZEOF_STR];
1950 do {
1951 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1953 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1954 return TRUE;
1955 string += pos;
1956 } while (*string);
1958 return VIEW_MAX_LEN(view) <= 0;
1961 static bool
1962 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1964 char text[SIZEOF_STR];
1965 int retval;
1967 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1968 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1971 static bool
1972 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1974 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1975 int max = VIEW_MAX_LEN(view);
1976 int i;
1978 if (max < size)
1979 size = max;
1981 set_view_attr(view, type);
1982 /* Using waddch() instead of waddnstr() ensures that
1983 * they'll be rendered correctly for the cursor line. */
1984 for (i = skip; i < size; i++)
1985 waddch(view->win, graphic[i]);
1987 view->col += size;
1988 if (separator) {
1989 if (size < max && skip <= size)
1990 waddch(view->win, ' ');
1991 view->col++;
1994 return VIEW_MAX_LEN(view) <= 0;
1997 static bool
1998 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
2000 int max = MIN(VIEW_MAX_LEN(view), len);
2001 int col = view->col;
2003 if (!text)
2004 return draw_space(view, type, max, max);
2006 return draw_chars(view, type, text, max - 1, trim)
2007 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2010 static bool
2011 draw_date(struct view *view, struct time *time)
2013 const char *date = mkdate(time, opt_date);
2014 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
2016 if (opt_date == DATE_NO)
2017 return FALSE;
2019 return draw_field(view, LINE_DATE, date, cols, FALSE);
2022 static bool
2023 draw_author(struct view *view, const char *author)
2025 bool trim = author_trim(opt_author_cols);
2026 const char *text = mkauthor(author, opt_author_cols, opt_author);
2028 if (opt_author == AUTHOR_NO)
2029 return FALSE;
2031 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2034 static bool
2035 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2037 bool trim = filename && strlen(filename) >= opt_filename_cols;
2039 if (opt_filename == FILENAME_NO)
2040 return FALSE;
2042 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2043 return FALSE;
2045 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2048 static bool
2049 draw_mode(struct view *view, mode_t mode)
2051 const char *str = mkmode(mode);
2053 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2056 static bool
2057 draw_lineno(struct view *view, unsigned int lineno)
2059 char number[10];
2060 int digits3 = view->digits < 3 ? 3 : view->digits;
2061 int max = MIN(VIEW_MAX_LEN(view), digits3);
2062 char *text = NULL;
2063 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2065 if (!opt_line_number)
2066 return FALSE;
2068 lineno += view->pos.offset + 1;
2069 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2070 static char fmt[] = "%1ld";
2072 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2073 if (string_format(number, fmt, lineno))
2074 text = number;
2076 if (text)
2077 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2078 else
2079 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2080 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2083 static bool
2084 draw_refs(struct view *view, struct ref_list *refs)
2086 size_t i;
2088 if (!opt_show_refs || !refs)
2089 return FALSE;
2091 for (i = 0; i < refs->size; i++) {
2092 struct ref *ref = refs->refs[i];
2093 enum line_type type = get_line_type_from_ref(ref);
2095 if (draw_formatted(view, type, "[%s]", ref->name))
2096 return TRUE;
2098 if (draw_text(view, LINE_DEFAULT, " "))
2099 return TRUE;
2102 return FALSE;
2105 static bool
2106 draw_view_line(struct view *view, unsigned int lineno)
2108 struct line *line;
2109 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2111 assert(view_is_displayed(view));
2113 if (view->pos.offset + lineno >= view->lines)
2114 return FALSE;
2116 line = &view->line[view->pos.offset + lineno];
2118 wmove(view->win, lineno, 0);
2119 if (line->cleareol)
2120 wclrtoeol(view->win);
2121 view->col = 0;
2122 view->curline = line;
2123 view->curtype = LINE_NONE;
2124 line->selected = FALSE;
2125 line->dirty = line->cleareol = 0;
2127 if (selected) {
2128 set_view_attr(view, LINE_CURSOR);
2129 line->selected = TRUE;
2130 view->ops->select(view, line);
2133 return view->ops->draw(view, line, lineno);
2136 static void
2137 redraw_view_dirty(struct view *view)
2139 bool dirty = FALSE;
2140 int lineno;
2142 for (lineno = 0; lineno < view->height; lineno++) {
2143 if (view->pos.offset + lineno >= view->lines)
2144 break;
2145 if (!view->line[view->pos.offset + lineno].dirty)
2146 continue;
2147 dirty = TRUE;
2148 if (!draw_view_line(view, lineno))
2149 break;
2152 if (!dirty)
2153 return;
2154 wnoutrefresh(view->win);
2157 static void
2158 redraw_view_from(struct view *view, int lineno)
2160 assert(0 <= lineno && lineno < view->height);
2162 for (; lineno < view->height; lineno++) {
2163 if (!draw_view_line(view, lineno))
2164 break;
2167 wnoutrefresh(view->win);
2170 static void
2171 redraw_view(struct view *view)
2173 werase(view->win);
2174 redraw_view_from(view, 0);
2178 static void
2179 update_view_title(struct view *view)
2181 char buf[SIZEOF_STR];
2182 char state[SIZEOF_STR];
2183 size_t bufpos = 0, statelen = 0;
2184 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2185 struct line *line = &view->line[view->pos.lineno];
2187 assert(view_is_displayed(view));
2189 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2190 line->lineno) {
2191 unsigned int view_lines = view->pos.offset + view->height;
2192 unsigned int lines = view->lines
2193 ? MIN(view_lines, view->lines) * 100 / view->lines
2194 : 0;
2196 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2197 view->ops->type,
2198 line->lineno,
2199 view->lines - view->custom_lines,
2200 lines);
2204 if (view->pipe) {
2205 time_t secs = time(NULL) - view->start_time;
2207 /* Three git seconds are a long time ... */
2208 if (secs > 2)
2209 string_format_from(state, &statelen, " loading %lds", secs);
2212 string_format_from(buf, &bufpos, "[%s]", view->name);
2213 if (*view->ref && bufpos < view->width) {
2214 size_t refsize = strlen(view->ref);
2215 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2217 if (minsize < view->width)
2218 refsize = view->width - minsize + 7;
2219 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2222 if (statelen && bufpos < view->width) {
2223 string_format_from(buf, &bufpos, "%s", state);
2226 if (view == display[current_view])
2227 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2228 else
2229 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2231 mvwaddnstr(window, 0, 0, buf, bufpos);
2232 wclrtoeol(window);
2233 wnoutrefresh(window);
2236 static int
2237 apply_step(double step, int value)
2239 if (step >= 1)
2240 return (int) step;
2241 value *= step + 0.01;
2242 return value ? value : 1;
2245 static void
2246 resize_display(void)
2248 int offset, i;
2249 struct view *base = display[0];
2250 struct view *view = display[1] ? display[1] : display[0];
2252 /* Setup window dimensions */
2254 getmaxyx(stdscr, base->height, base->width);
2256 /* Make room for the status window. */
2257 base->height -= 1;
2259 if (view != base) {
2260 /* Horizontal split. */
2261 view->width = base->width;
2262 view->height = apply_step(opt_scale_split_view, base->height);
2263 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2264 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2265 base->height -= view->height;
2267 /* Make room for the title bar. */
2268 view->height -= 1;
2271 /* Make room for the title bar. */
2272 base->height -= 1;
2274 offset = 0;
2276 foreach_displayed_view (view, i) {
2277 if (!display_win[i]) {
2278 display_win[i] = newwin(view->height, view->width, offset, 0);
2279 if (!display_win[i])
2280 die("Failed to create %s view", view->name);
2282 scrollok(display_win[i], FALSE);
2284 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2285 if (!display_title[i])
2286 die("Failed to create title window");
2288 } else {
2289 wresize(display_win[i], view->height, view->width);
2290 mvwin(display_win[i], offset, 0);
2291 mvwin(display_title[i], offset + view->height, 0);
2294 view->win = display_win[i];
2296 offset += view->height + 1;
2300 static void
2301 redraw_display(bool clear)
2303 struct view *view;
2304 int i;
2306 foreach_displayed_view (view, i) {
2307 if (clear)
2308 wclear(view->win);
2309 redraw_view(view);
2310 update_view_title(view);
2316 * Option management
2319 #define TOGGLE_MENU \
2320 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2321 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2322 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2323 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2324 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2325 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2326 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2327 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2328 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2329 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2331 static bool
2332 toggle_option(enum request request)
2334 const struct {
2335 enum request request;
2336 const struct enum_map *map;
2337 size_t map_size;
2338 } data[] = {
2339 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2340 TOGGLE_MENU
2341 #undef TOGGLE_
2343 const struct menu_item menu[] = {
2344 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2345 TOGGLE_MENU
2346 #undef TOGGLE_
2347 { 0 }
2349 int i = 0;
2351 if (request == REQ_OPTIONS) {
2352 if (!prompt_menu("Toggle option", menu, &i))
2353 return FALSE;
2354 } else {
2355 while (i < ARRAY_SIZE(data) && data[i].request != request)
2356 i++;
2357 if (i >= ARRAY_SIZE(data))
2358 die("Invalid request (%d)", request);
2361 if (data[i].map != NULL) {
2362 unsigned int *opt = menu[i].data;
2364 *opt = (*opt + 1) % data[i].map_size;
2365 if (data[i].map == ignore_space_map) {
2366 update_ignore_space_arg();
2367 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2368 return TRUE;
2370 } else if (data[i].map == commit_order_map) {
2371 update_commit_order_arg();
2372 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2373 return TRUE;
2376 redraw_display(FALSE);
2377 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2379 } else {
2380 bool *option = menu[i].data;
2382 *option = !*option;
2383 redraw_display(FALSE);
2384 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2387 return FALSE;
2392 * Navigation
2395 static bool
2396 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2398 if (lineno >= view->lines)
2399 lineno = view->lines > 0 ? view->lines - 1 : 0;
2401 if (offset > lineno || offset + view->height <= lineno) {
2402 unsigned long half = view->height / 2;
2404 if (lineno > half)
2405 offset = lineno - half;
2406 else
2407 offset = 0;
2410 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2411 view->pos.offset = offset;
2412 view->pos.lineno = lineno;
2413 return TRUE;
2416 return FALSE;
2419 /* Scrolling backend */
2420 static void
2421 do_scroll_view(struct view *view, int lines)
2423 bool redraw_current_line = FALSE;
2425 /* The rendering expects the new offset. */
2426 view->pos.offset += lines;
2428 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2429 assert(lines);
2431 /* Move current line into the view. */
2432 if (view->pos.lineno < view->pos.offset) {
2433 view->pos.lineno = view->pos.offset;
2434 redraw_current_line = TRUE;
2435 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2436 view->pos.lineno = view->pos.offset + view->height - 1;
2437 redraw_current_line = TRUE;
2440 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2442 /* Redraw the whole screen if scrolling is pointless. */
2443 if (view->height < ABS(lines)) {
2444 redraw_view(view);
2446 } else {
2447 int line = lines > 0 ? view->height - lines : 0;
2448 int end = line + ABS(lines);
2450 scrollok(view->win, TRUE);
2451 wscrl(view->win, lines);
2452 scrollok(view->win, FALSE);
2454 while (line < end && draw_view_line(view, line))
2455 line++;
2457 if (redraw_current_line)
2458 draw_view_line(view, view->pos.lineno - view->pos.offset);
2459 wnoutrefresh(view->win);
2462 view->has_scrolled = TRUE;
2463 report("");
2466 /* Scroll frontend */
2467 static void
2468 scroll_view(struct view *view, enum request request)
2470 int lines = 1;
2472 assert(view_is_displayed(view));
2474 switch (request) {
2475 case REQ_SCROLL_FIRST_COL:
2476 view->pos.col = 0;
2477 redraw_view_from(view, 0);
2478 report("");
2479 return;
2480 case REQ_SCROLL_LEFT:
2481 if (view->pos.col == 0) {
2482 report("Cannot scroll beyond the first column");
2483 return;
2485 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2486 view->pos.col = 0;
2487 else
2488 view->pos.col -= apply_step(opt_hscroll, view->width);
2489 redraw_view_from(view, 0);
2490 report("");
2491 return;
2492 case REQ_SCROLL_RIGHT:
2493 view->pos.col += apply_step(opt_hscroll, view->width);
2494 redraw_view(view);
2495 report("");
2496 return;
2497 case REQ_SCROLL_PAGE_DOWN:
2498 lines = view->height;
2499 case REQ_SCROLL_LINE_DOWN:
2500 if (view->pos.offset + lines > view->lines)
2501 lines = view->lines - view->pos.offset;
2503 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2504 report("Cannot scroll beyond the last line");
2505 return;
2507 break;
2509 case REQ_SCROLL_PAGE_UP:
2510 lines = view->height;
2511 case REQ_SCROLL_LINE_UP:
2512 if (lines > view->pos.offset)
2513 lines = view->pos.offset;
2515 if (lines == 0) {
2516 report("Cannot scroll beyond the first line");
2517 return;
2520 lines = -lines;
2521 break;
2523 default:
2524 die("request %d not handled in switch", request);
2527 do_scroll_view(view, lines);
2530 /* Cursor moving */
2531 static void
2532 move_view(struct view *view, enum request request)
2534 int scroll_steps = 0;
2535 int steps;
2537 switch (request) {
2538 case REQ_MOVE_FIRST_LINE:
2539 steps = -view->pos.lineno;
2540 break;
2542 case REQ_MOVE_LAST_LINE:
2543 steps = view->lines - view->pos.lineno - 1;
2544 break;
2546 case REQ_MOVE_PAGE_UP:
2547 steps = view->height > view->pos.lineno
2548 ? -view->pos.lineno : -view->height;
2549 break;
2551 case REQ_MOVE_PAGE_DOWN:
2552 steps = view->pos.lineno + view->height >= view->lines
2553 ? view->lines - view->pos.lineno - 1 : view->height;
2554 break;
2556 case REQ_MOVE_UP:
2557 case REQ_PREVIOUS:
2558 steps = -1;
2559 break;
2561 case REQ_MOVE_DOWN:
2562 case REQ_NEXT:
2563 steps = 1;
2564 break;
2566 default:
2567 die("request %d not handled in switch", request);
2570 if (steps <= 0 && view->pos.lineno == 0) {
2571 report("Cannot move beyond the first line");
2572 return;
2574 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2575 report("Cannot move beyond the last line");
2576 return;
2579 /* Move the current line */
2580 view->pos.lineno += steps;
2581 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2583 /* Check whether the view needs to be scrolled */
2584 if (view->pos.lineno < view->pos.offset ||
2585 view->pos.lineno >= view->pos.offset + view->height) {
2586 scroll_steps = steps;
2587 if (steps < 0 && -steps > view->pos.offset) {
2588 scroll_steps = -view->pos.offset;
2590 } else if (steps > 0) {
2591 if (view->pos.lineno == view->lines - 1 &&
2592 view->lines > view->height) {
2593 scroll_steps = view->lines - view->pos.offset - 1;
2594 if (scroll_steps >= view->height)
2595 scroll_steps -= view->height - 1;
2600 if (!view_is_displayed(view)) {
2601 view->pos.offset += scroll_steps;
2602 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2603 view->ops->select(view, &view->line[view->pos.lineno]);
2604 return;
2607 /* Repaint the old "current" line if we be scrolling */
2608 if (ABS(steps) < view->height)
2609 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2611 if (scroll_steps) {
2612 do_scroll_view(view, scroll_steps);
2613 return;
2616 /* Draw the current line */
2617 draw_view_line(view, view->pos.lineno - view->pos.offset);
2619 wnoutrefresh(view->win);
2620 report("");
2625 * Searching
2628 static void search_view(struct view *view, enum request request);
2630 static bool
2631 grep_text(struct view *view, const char *text[])
2633 regmatch_t pmatch;
2634 size_t i;
2636 for (i = 0; text[i]; i++)
2637 if (*text[i] &&
2638 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2639 return TRUE;
2640 return FALSE;
2643 static void
2644 select_view_line(struct view *view, unsigned long lineno)
2646 struct position old = view->pos;
2648 if (goto_view_line(view, view->pos.offset, lineno)) {
2649 if (view_is_displayed(view)) {
2650 if (old.offset != view->pos.offset) {
2651 redraw_view(view);
2652 } else {
2653 draw_view_line(view, old.lineno - view->pos.offset);
2654 draw_view_line(view, view->pos.lineno - view->pos.offset);
2655 wnoutrefresh(view->win);
2657 } else {
2658 view->ops->select(view, &view->line[view->pos.lineno]);
2663 static void
2664 find_next(struct view *view, enum request request)
2666 unsigned long lineno = view->pos.lineno;
2667 int direction;
2669 if (!*view->grep) {
2670 if (!*opt_search)
2671 report("No previous search");
2672 else
2673 search_view(view, request);
2674 return;
2677 switch (request) {
2678 case REQ_SEARCH:
2679 case REQ_FIND_NEXT:
2680 direction = 1;
2681 break;
2683 case REQ_SEARCH_BACK:
2684 case REQ_FIND_PREV:
2685 direction = -1;
2686 break;
2688 default:
2689 return;
2692 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2693 lineno += direction;
2695 /* Note, lineno is unsigned long so will wrap around in which case it
2696 * will become bigger than view->lines. */
2697 for (; lineno < view->lines; lineno += direction) {
2698 if (view->ops->grep(view, &view->line[lineno])) {
2699 select_view_line(view, lineno);
2700 report("Line %ld matches '%s'", lineno + 1, view->grep);
2701 return;
2705 report("No match found for '%s'", view->grep);
2708 static void
2709 search_view(struct view *view, enum request request)
2711 int regex_err;
2712 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
2714 if (view->regex) {
2715 regfree(view->regex);
2716 *view->grep = 0;
2717 } else {
2718 view->regex = calloc(1, sizeof(*view->regex));
2719 if (!view->regex)
2720 return;
2723 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
2724 if (regex_err != 0) {
2725 char buf[SIZEOF_STR] = "unknown error";
2727 regerror(regex_err, view->regex, buf, sizeof(buf));
2728 report("Search failed: %s", buf);
2729 return;
2732 string_copy(view->grep, opt_search);
2734 find_next(view, request);
2738 * Incremental updating
2741 static inline bool
2742 check_position(struct position *pos)
2744 return pos->lineno || pos->col || pos->offset;
2747 static inline void
2748 clear_position(struct position *pos)
2750 memset(pos, 0, sizeof(*pos));
2753 static void
2754 reset_view(struct view *view)
2756 int i;
2758 for (i = 0; i < view->lines; i++)
2759 if (!view->line[i].dont_free)
2760 free(view->line[i].data);
2761 free(view->line);
2763 view->prev_pos = view->pos;
2764 clear_position(&view->pos);
2766 view->line = NULL;
2767 view->lines = 0;
2768 view->vid[0] = 0;
2769 view->custom_lines = 0;
2770 view->update_secs = 0;
2773 static const char *
2774 format_arg(const char *name)
2776 static struct {
2777 const char *name;
2778 size_t namelen;
2779 const char *value;
2780 const char *value_if_empty;
2781 } vars[] = {
2782 #define FORMAT_VAR(name, value, value_if_empty) \
2783 { name, STRING_SIZE(name), value, value_if_empty }
2784 FORMAT_VAR("%(directory)", opt_path, "."),
2785 FORMAT_VAR("%(file)", opt_file, ""),
2786 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2787 FORMAT_VAR("%(head)", ref_head, ""),
2788 FORMAT_VAR("%(commit)", ref_commit, ""),
2789 FORMAT_VAR("%(blob)", ref_blob, ""),
2790 FORMAT_VAR("%(branch)", ref_branch, ""),
2792 int i;
2794 if (!prefixcmp(name, "%(prompt"))
2795 return read_prompt("Command argument: ");
2797 for (i = 0; i < ARRAY_SIZE(vars); i++)
2798 if (!strncmp(name, vars[i].name, vars[i].namelen))
2799 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2801 report("Unknown replacement: `%s`", name);
2802 return NULL;
2805 static bool
2806 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2808 char buf[SIZEOF_STR];
2809 int argc;
2811 argv_free(*dst_argv);
2813 for (argc = 0; src_argv[argc]; argc++) {
2814 const char *arg = src_argv[argc];
2815 size_t bufpos = 0;
2817 if (!strcmp(arg, "%(fileargs)")) {
2818 if (!argv_append_array(dst_argv, opt_file_argv))
2819 break;
2820 continue;
2822 } else if (!strcmp(arg, "%(diffargs)")) {
2823 if (!argv_append_array(dst_argv, opt_diff_argv))
2824 break;
2825 continue;
2827 } else if (!strcmp(arg, "%(blameargs)")) {
2828 if (!argv_append_array(dst_argv, opt_blame_argv))
2829 break;
2830 continue;
2832 } else if (!strcmp(arg, "%(revargs)") ||
2833 (first && !strcmp(arg, "%(commit)"))) {
2834 if (!argv_append_array(dst_argv, opt_rev_argv))
2835 break;
2836 continue;
2839 while (arg) {
2840 char *next = strstr(arg, "%(");
2841 int len = next - arg;
2842 const char *value;
2844 if (!next) {
2845 len = strlen(arg);
2846 value = "";
2848 } else {
2849 value = format_arg(next);
2851 if (!value) {
2852 return FALSE;
2856 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2857 return FALSE;
2859 arg = next ? strchr(next, ')') + 1 : NULL;
2862 if (!argv_append(dst_argv, buf))
2863 break;
2866 return src_argv[argc] == NULL;
2869 static bool
2870 restore_view_position(struct view *view)
2872 /* A view without a previous view is the first view */
2873 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2874 select_view_line(view, opt_lineno - 1);
2875 opt_lineno = 0;
2878 /* Ensure that the view position is in a valid state. */
2879 if (!check_position(&view->prev_pos) ||
2880 (view->pipe && view->lines <= view->prev_pos.lineno))
2881 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2883 /* Changing the view position cancels the restoring. */
2884 /* FIXME: Changing back to the first line is not detected. */
2885 if (check_position(&view->pos)) {
2886 clear_position(&view->prev_pos);
2887 return FALSE;
2890 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2891 view_is_displayed(view))
2892 werase(view->win);
2894 view->pos.col = view->prev_pos.col;
2895 clear_position(&view->prev_pos);
2897 return TRUE;
2900 static void
2901 end_update(struct view *view, bool force)
2903 if (!view->pipe)
2904 return;
2905 while (!view->ops->read(view, NULL))
2906 if (!force)
2907 return;
2908 if (force)
2909 io_kill(view->pipe);
2910 io_done(view->pipe);
2911 view->pipe = NULL;
2914 static void
2915 setup_update(struct view *view, const char *vid)
2917 reset_view(view);
2918 string_copy_rev(view->vid, vid);
2919 view->pipe = &view->io;
2920 view->start_time = time(NULL);
2923 static bool
2924 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2926 bool extra = !!(flags & (OPEN_EXTRA));
2927 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2928 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2930 if (!reload && !strcmp(view->vid, view->id))
2931 return TRUE;
2933 if (view->pipe) {
2934 if (extra)
2935 io_done(view->pipe);
2936 else
2937 end_update(view, TRUE);
2940 if (!refresh && argv) {
2941 view->dir = dir;
2942 if (!format_argv(&view->argv, argv, !view->prev)) {
2943 report("Failed to format %s arguments", view->name);
2944 return FALSE;
2947 /* Put the current ref_* value to the view title ref
2948 * member. This is needed by the blob view. Most other
2949 * views sets it automatically after loading because the
2950 * first line is a commit line. */
2951 string_copy_rev(view->ref, view->id);
2954 if (view->argv && view->argv[0] &&
2955 !io_run(&view->io, IO_RD, view->dir, view->argv)) {
2956 report("Failed to open %s view", view->name);
2957 return FALSE;
2960 if (!extra)
2961 setup_update(view, view->id);
2963 return TRUE;
2966 static bool
2967 update_view(struct view *view)
2969 char *line;
2970 /* Clear the view and redraw everything since the tree sorting
2971 * might have rearranged things. */
2972 bool redraw = view->lines == 0;
2973 bool can_read = TRUE;
2975 if (!view->pipe)
2976 return TRUE;
2978 if (!io_can_read(view->pipe, FALSE)) {
2979 if (view->lines == 0 && view_is_displayed(view)) {
2980 time_t secs = time(NULL) - view->start_time;
2982 if (secs > 1 && secs > view->update_secs) {
2983 if (view->update_secs == 0)
2984 redraw_view(view);
2985 update_view_title(view);
2986 view->update_secs = secs;
2989 return TRUE;
2992 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2993 if (view->encoding) {
2994 line = encoding_convert(view->encoding, line);
2997 if (!view->ops->read(view, line)) {
2998 report("Allocation failure");
2999 end_update(view, TRUE);
3000 return FALSE;
3005 unsigned long lines = view->lines;
3006 int digits;
3008 for (digits = 0; lines; digits++)
3009 lines /= 10;
3011 /* Keep the displayed view in sync with line number scaling. */
3012 if (digits != view->digits) {
3013 view->digits = digits;
3014 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3015 redraw = TRUE;
3019 if (io_error(view->pipe)) {
3020 report("Failed to read: %s", io_strerror(view->pipe));
3021 end_update(view, TRUE);
3023 } else if (io_eof(view->pipe)) {
3024 if (view_is_displayed(view))
3025 report("");
3026 end_update(view, FALSE);
3029 if (restore_view_position(view))
3030 redraw = TRUE;
3032 if (!view_is_displayed(view))
3033 return TRUE;
3035 if (redraw)
3036 redraw_view_from(view, 0);
3037 else
3038 redraw_view_dirty(view);
3040 /* Update the title _after_ the redraw so that if the redraw picks up a
3041 * commit reference in view->ref it'll be available here. */
3042 update_view_title(view);
3043 return TRUE;
3046 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3048 static struct line *
3049 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3051 struct line *line;
3053 if (!realloc_lines(&view->line, view->lines, 1))
3054 return NULL;
3056 if (data_size) {
3057 void *alloc_data = calloc(1, data_size);
3059 if (!alloc_data)
3060 return NULL;
3062 if (data)
3063 memcpy(alloc_data, data, data_size);
3064 data = alloc_data;
3067 line = &view->line[view->lines++];
3068 memset(line, 0, sizeof(*line));
3069 line->type = type;
3070 line->data = (void *) data;
3071 line->dirty = 1;
3073 if (custom)
3074 view->custom_lines++;
3075 else
3076 line->lineno = view->lines - view->custom_lines;
3078 return line;
3081 static struct line *
3082 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3084 struct line *line = add_line(view, NULL, type, data_size, custom);
3086 if (line)
3087 *ptr = line->data;
3088 return line;
3091 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3092 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3094 static struct line *
3095 add_line_nodata(struct view *view, enum line_type type)
3097 return add_line(view, NULL, type, 0, FALSE);
3100 static struct line *
3101 add_line_static_data(struct view *view, const void *data, enum line_type type)
3103 struct line *line = add_line(view, data, type, 0, FALSE);
3105 if (line)
3106 line->dont_free = TRUE;
3107 return line;
3110 static struct line *
3111 add_line_text(struct view *view, const char *text, enum line_type type)
3113 return add_line(view, text, type, strlen(text) + 1, FALSE);
3116 static struct line *
3117 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3119 char buf[SIZEOF_STR];
3120 int retval;
3122 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3123 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3127 * View opening
3130 static void
3131 split_view(struct view *prev, struct view *view)
3133 display[1] = view;
3134 current_view = 1;
3135 view->parent = prev;
3136 resize_display();
3138 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3139 /* Take the title line into account. */
3140 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3142 /* Scroll the view that was split if the current line is
3143 * outside the new limited view. */
3144 do_scroll_view(prev, lines);
3147 if (view != prev && view_is_displayed(prev)) {
3148 /* "Blur" the previous view. */
3149 update_view_title(prev);
3153 static void
3154 maximize_view(struct view *view, bool redraw)
3156 memset(display, 0, sizeof(display));
3157 current_view = 0;
3158 display[current_view] = view;
3159 resize_display();
3160 if (redraw) {
3161 redraw_display(FALSE);
3162 report("");
3166 static void
3167 load_view(struct view *view, struct view *prev, enum open_flags flags)
3169 if (view->pipe)
3170 end_update(view, TRUE);
3171 if (view->ops->private_size) {
3172 if (!view->private)
3173 view->private = calloc(1, view->ops->private_size);
3174 else
3175 memset(view->private, 0, view->ops->private_size);
3178 /* When prev == view it means this is the first loaded view. */
3179 if (prev && view != prev) {
3180 view->prev = prev;
3183 if (!view->ops->open(view, flags))
3184 return;
3186 if (prev) {
3187 bool split = !!(flags & OPEN_SPLIT);
3189 if (split) {
3190 split_view(prev, view);
3191 } else {
3192 maximize_view(view, FALSE);
3196 restore_view_position(view);
3198 if (view->pipe && view->lines == 0) {
3199 /* Clear the old view and let the incremental updating refill
3200 * the screen. */
3201 werase(view->win);
3202 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3203 clear_position(&view->prev_pos);
3204 report("");
3205 } else if (view_is_displayed(view)) {
3206 redraw_view(view);
3207 report("");
3211 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3212 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3214 static void
3215 open_view(struct view *prev, enum request request, enum open_flags flags)
3217 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3218 struct view *view = VIEW(request);
3219 int nviews = displayed_views();
3221 assert(flags ^ OPEN_REFRESH);
3223 if (view == prev && nviews == 1 && !reload) {
3224 report("Already in %s view", view->name);
3225 return;
3228 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3229 report("The %s view is disabled in pager view", view->name);
3230 return;
3233 load_view(view, prev ? prev : view, flags);
3236 static void
3237 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3239 enum request request = view - views + REQ_OFFSET + 1;
3241 if (view->pipe)
3242 end_update(view, TRUE);
3243 view->dir = dir;
3245 if (!argv_copy(&view->argv, argv)) {
3246 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3247 } else {
3248 open_view(prev, request, flags | OPEN_PREPARED);
3252 static void
3253 open_external_viewer(const char *argv[], const char *dir)
3255 def_prog_mode(); /* save current tty modes */
3256 endwin(); /* restore original tty modes */
3257 io_run_fg(argv, dir);
3258 fprintf(stderr, "Press Enter to continue");
3259 getc(opt_tty);
3260 reset_prog_mode();
3261 redraw_display(TRUE);
3264 static void
3265 open_mergetool(const char *file)
3267 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3269 open_external_viewer(mergetool_argv, opt_cdup);
3272 static void
3273 open_editor(const char *file)
3275 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3276 char editor_cmd[SIZEOF_STR];
3277 const char *editor;
3278 int argc = 0;
3280 editor = getenv("GIT_EDITOR");
3281 if (!editor && *opt_editor)
3282 editor = opt_editor;
3283 if (!editor)
3284 editor = getenv("VISUAL");
3285 if (!editor)
3286 editor = getenv("EDITOR");
3287 if (!editor)
3288 editor = "vi";
3290 string_ncopy(editor_cmd, editor, strlen(editor));
3291 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3292 report("Failed to read editor command");
3293 return;
3296 editor_argv[argc] = file;
3297 open_external_viewer(editor_argv, opt_cdup);
3300 static void
3301 open_run_request(enum request request)
3303 struct run_request *req = get_run_request(request);
3304 const char **argv = NULL;
3306 if (!req) {
3307 report("Unknown run request");
3308 return;
3311 if (format_argv(&argv, req->argv, FALSE)) {
3312 bool confirmed = !req->confirm;
3314 if (req->confirm) {
3315 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3317 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3318 string_format(prompt, "Run `%s`?", cmd) &&
3319 prompt_yesno(prompt)) {
3320 confirmed = TRUE;
3324 if (!confirmed)
3325 ; /* Nothing */
3326 else if (req->silent)
3327 io_run_bg(argv);
3328 else
3329 open_external_viewer(argv, NULL);
3331 if (argv)
3332 argv_free(argv);
3333 free(argv);
3337 * User request switch noodle
3340 static int
3341 view_driver(struct view *view, enum request request)
3343 int i;
3345 if (request == REQ_NONE)
3346 return TRUE;
3348 if (request > REQ_NONE) {
3349 open_run_request(request);
3350 view_request(view, REQ_REFRESH);
3351 return TRUE;
3354 request = view_request(view, request);
3355 if (request == REQ_NONE)
3356 return TRUE;
3358 switch (request) {
3359 case REQ_MOVE_UP:
3360 case REQ_MOVE_DOWN:
3361 case REQ_MOVE_PAGE_UP:
3362 case REQ_MOVE_PAGE_DOWN:
3363 case REQ_MOVE_FIRST_LINE:
3364 case REQ_MOVE_LAST_LINE:
3365 move_view(view, request);
3366 break;
3368 case REQ_SCROLL_FIRST_COL:
3369 case REQ_SCROLL_LEFT:
3370 case REQ_SCROLL_RIGHT:
3371 case REQ_SCROLL_LINE_DOWN:
3372 case REQ_SCROLL_LINE_UP:
3373 case REQ_SCROLL_PAGE_DOWN:
3374 case REQ_SCROLL_PAGE_UP:
3375 scroll_view(view, request);
3376 break;
3378 case REQ_VIEW_MAIN:
3379 case REQ_VIEW_DIFF:
3380 case REQ_VIEW_LOG:
3381 case REQ_VIEW_TREE:
3382 case REQ_VIEW_HELP:
3383 case REQ_VIEW_BRANCH:
3384 case REQ_VIEW_BLAME:
3385 case REQ_VIEW_BLOB:
3386 case REQ_VIEW_STATUS:
3387 case REQ_VIEW_STAGE:
3388 case REQ_VIEW_PAGER:
3389 open_view(view, request, OPEN_DEFAULT);
3390 break;
3392 case REQ_NEXT:
3393 case REQ_PREVIOUS:
3394 if (view->parent) {
3395 int line;
3397 view = view->parent;
3398 line = view->pos.lineno;
3399 move_view(view, request);
3400 if (view_is_displayed(view))
3401 update_view_title(view);
3402 if (line != view->pos.lineno)
3403 view_request(view, REQ_ENTER);
3404 } else {
3405 move_view(view, request);
3407 break;
3409 case REQ_VIEW_NEXT:
3411 int nviews = displayed_views();
3412 int next_view = (current_view + 1) % nviews;
3414 if (next_view == current_view) {
3415 report("Only one view is displayed");
3416 break;
3419 current_view = next_view;
3420 /* Blur out the title of the previous view. */
3421 update_view_title(view);
3422 report("");
3423 break;
3425 case REQ_REFRESH:
3426 report("Refreshing is not yet supported for the %s view", view->name);
3427 break;
3429 case REQ_MAXIMIZE:
3430 if (displayed_views() == 2)
3431 maximize_view(view, TRUE);
3432 break;
3434 case REQ_OPTIONS:
3435 case REQ_TOGGLE_LINENO:
3436 case REQ_TOGGLE_DATE:
3437 case REQ_TOGGLE_AUTHOR:
3438 case REQ_TOGGLE_FILENAME:
3439 case REQ_TOGGLE_GRAPHIC:
3440 case REQ_TOGGLE_REV_GRAPH:
3441 case REQ_TOGGLE_REFS:
3442 case REQ_TOGGLE_CHANGES:
3443 case REQ_TOGGLE_IGNORE_SPACE:
3444 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3445 reload_view(view);
3446 break;
3448 case REQ_TOGGLE_SORT_FIELD:
3449 case REQ_TOGGLE_SORT_ORDER:
3450 report("Sorting is not yet supported for the %s view", view->name);
3451 break;
3453 case REQ_DIFF_CONTEXT_UP:
3454 case REQ_DIFF_CONTEXT_DOWN:
3455 report("Changing the diff context is not yet supported for the %s view", view->name);
3456 break;
3458 case REQ_SEARCH:
3459 case REQ_SEARCH_BACK:
3460 search_view(view, request);
3461 break;
3463 case REQ_FIND_NEXT:
3464 case REQ_FIND_PREV:
3465 find_next(view, request);
3466 break;
3468 case REQ_STOP_LOADING:
3469 foreach_view(view, i) {
3470 if (view->pipe)
3471 report("Stopped loading the %s view", view->name),
3472 end_update(view, TRUE);
3474 break;
3476 case REQ_SHOW_VERSION:
3477 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3478 return TRUE;
3480 case REQ_SCREEN_REDRAW:
3481 redraw_display(TRUE);
3482 break;
3484 case REQ_EDIT:
3485 report("Nothing to edit");
3486 break;
3488 case REQ_ENTER:
3489 report("Nothing to enter");
3490 break;
3492 case REQ_VIEW_CLOSE:
3493 /* XXX: Mark closed views by letting view->prev point to the
3494 * view itself. Parents to closed view should never be
3495 * followed. */
3496 if (view->prev && view->prev != view) {
3497 maximize_view(view->prev, TRUE);
3498 view->prev = view;
3499 break;
3501 /* Fall-through */
3502 case REQ_QUIT:
3503 return FALSE;
3505 default:
3506 report("Unknown key, press %s for help",
3507 get_view_key(view, REQ_VIEW_HELP));
3508 return TRUE;
3511 return TRUE;
3516 * View backend utilities
3519 enum sort_field {
3520 ORDERBY_NAME,
3521 ORDERBY_DATE,
3522 ORDERBY_AUTHOR,
3525 struct sort_state {
3526 const enum sort_field *fields;
3527 size_t size, current;
3528 bool reverse;
3531 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3532 #define get_sort_field(state) ((state).fields[(state).current])
3533 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3535 static void
3536 sort_view(struct view *view, enum request request, struct sort_state *state,
3537 int (*compare)(const void *, const void *))
3539 switch (request) {
3540 case REQ_TOGGLE_SORT_FIELD:
3541 state->current = (state->current + 1) % state->size;
3542 break;
3544 case REQ_TOGGLE_SORT_ORDER:
3545 state->reverse = !state->reverse;
3546 break;
3547 default:
3548 die("Not a sort request");
3551 qsort(view->line, view->lines, sizeof(*view->line), compare);
3552 redraw_view(view);
3555 static bool
3556 update_diff_context(enum request request)
3558 int diff_context = opt_diff_context;
3560 switch (request) {
3561 case REQ_DIFF_CONTEXT_UP:
3562 opt_diff_context += 1;
3563 update_diff_context_arg(opt_diff_context);
3564 break;
3566 case REQ_DIFF_CONTEXT_DOWN:
3567 if (opt_diff_context == 0) {
3568 report("Diff context cannot be less than zero");
3569 break;
3571 opt_diff_context -= 1;
3572 update_diff_context_arg(opt_diff_context);
3573 break;
3575 default:
3576 die("Not a diff context request");
3579 return diff_context != opt_diff_context;
3582 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3584 /* Small author cache to reduce memory consumption. It uses binary
3585 * search to lookup or find place to position new entries. No entries
3586 * are ever freed. */
3587 static const char *
3588 get_author(const char *name)
3590 static const char **authors;
3591 static size_t authors_size;
3592 int from = 0, to = authors_size - 1;
3594 while (from <= to) {
3595 size_t pos = (to + from) / 2;
3596 int cmp = strcmp(name, authors[pos]);
3598 if (!cmp)
3599 return authors[pos];
3601 if (cmp < 0)
3602 to = pos - 1;
3603 else
3604 from = pos + 1;
3607 if (!realloc_authors(&authors, authors_size, 1))
3608 return NULL;
3609 name = strdup(name);
3610 if (!name)
3611 return NULL;
3613 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3614 authors[from] = name;
3615 authors_size++;
3617 return name;
3620 static void
3621 parse_timesec(struct time *time, const char *sec)
3623 time->sec = (time_t) atol(sec);
3626 static void
3627 parse_timezone(struct time *time, const char *zone)
3629 long tz;
3631 tz = ('0' - zone[1]) * 60 * 60 * 10;
3632 tz += ('0' - zone[2]) * 60 * 60;
3633 tz += ('0' - zone[3]) * 60 * 10;
3634 tz += ('0' - zone[4]) * 60;
3636 if (zone[0] == '-')
3637 tz = -tz;
3639 time->tz = tz;
3640 time->sec -= tz;
3643 /* Parse author lines where the name may be empty:
3644 * author <email@address.tld> 1138474660 +0100
3646 static void
3647 parse_author_line(char *ident, const char **author, struct time *time)
3649 char *nameend = strchr(ident, '<');
3650 char *emailend = strchr(ident, '>');
3652 if (nameend && emailend)
3653 *nameend = *emailend = 0;
3654 ident = chomp_string(ident);
3655 if (!*ident) {
3656 if (nameend)
3657 ident = chomp_string(nameend + 1);
3658 if (!*ident)
3659 ident = "Unknown";
3662 *author = get_author(ident);
3664 /* Parse epoch and timezone */
3665 if (emailend && emailend[1] == ' ') {
3666 char *secs = emailend + 2;
3667 char *zone = strchr(secs, ' ');
3669 parse_timesec(time, secs);
3671 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3672 parse_timezone(time, zone + 1);
3676 static struct line *
3677 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3679 for (; view_has_line(view, line); line += direction)
3680 if (line->type == type)
3681 return line;
3683 return NULL;
3686 #define find_prev_line_by_type(view, line, type) \
3687 find_line_by_type(view, line, type, -1)
3689 #define find_next_line_by_type(view, line, type) \
3690 find_line_by_type(view, line, type, 1)
3693 * Blame
3696 struct blame_commit {
3697 char id[SIZEOF_REV]; /* SHA1 ID. */
3698 char title[128]; /* First line of the commit message. */
3699 const char *author; /* Author of the commit. */
3700 struct time time; /* Date from the author ident. */
3701 char filename[128]; /* Name of file. */
3702 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3703 char parent_filename[128]; /* Parent/previous name of file. */
3706 struct blame_header {
3707 char id[SIZEOF_REV]; /* SHA1 ID. */
3708 size_t orig_lineno;
3709 size_t lineno;
3710 size_t group;
3713 static bool
3714 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3716 const char *pos = *posref;
3718 *posref = NULL;
3719 pos = strchr(pos + 1, ' ');
3720 if (!pos || !isdigit(pos[1]))
3721 return FALSE;
3722 *number = atoi(pos + 1);
3723 if (*number < min || *number > max)
3724 return FALSE;
3726 *posref = pos;
3727 return TRUE;
3730 static bool
3731 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3733 const char *pos = text + SIZEOF_REV - 2;
3735 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3736 return FALSE;
3738 string_ncopy(header->id, text, SIZEOF_REV);
3740 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3741 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3742 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3743 return FALSE;
3745 return TRUE;
3748 static bool
3749 match_blame_header(const char *name, char **line)
3751 size_t namelen = strlen(name);
3752 bool matched = !strncmp(name, *line, namelen);
3754 if (matched)
3755 *line += namelen;
3757 return matched;
3760 static bool
3761 parse_blame_info(struct blame_commit *commit, char *line)
3763 if (match_blame_header("author ", &line)) {
3764 commit->author = get_author(line);
3766 } else if (match_blame_header("author-time ", &line)) {
3767 parse_timesec(&commit->time, line);
3769 } else if (match_blame_header("author-tz ", &line)) {
3770 parse_timezone(&commit->time, line);
3772 } else if (match_blame_header("summary ", &line)) {
3773 string_ncopy(commit->title, line, strlen(line));
3775 } else if (match_blame_header("previous ", &line)) {
3776 if (strlen(line) <= SIZEOF_REV)
3777 return FALSE;
3778 string_copy_rev(commit->parent_id, line);
3779 line += SIZEOF_REV;
3780 string_ncopy(commit->parent_filename, line, strlen(line));
3782 } else if (match_blame_header("filename ", &line)) {
3783 string_ncopy(commit->filename, line, strlen(line));
3784 return TRUE;
3787 return FALSE;
3791 * Pager backend
3794 static bool
3795 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3797 if (draw_lineno(view, lineno))
3798 return TRUE;
3800 draw_text(view, line->type, line->data);
3801 return TRUE;
3804 static bool
3805 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3807 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3808 char ref[SIZEOF_STR];
3810 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3811 return TRUE;
3813 /* This is the only fatal call, since it can "corrupt" the buffer. */
3814 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3815 return FALSE;
3817 return TRUE;
3820 static void
3821 add_pager_refs(struct view *view, const char *commit_id)
3823 char buf[SIZEOF_STR];
3824 struct ref_list *list;
3825 size_t bufpos = 0, i;
3826 const char *sep = "Refs: ";
3827 bool is_tag = FALSE;
3829 list = get_ref_list(commit_id);
3830 if (!list) {
3831 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3832 goto try_add_describe_ref;
3833 return;
3836 for (i = 0; i < list->size; i++) {
3837 struct ref *ref = list->refs[i];
3838 const char *fmt = ref->tag ? "%s[%s]" :
3839 ref->remote ? "%s<%s>" : "%s%s";
3841 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3842 return;
3843 sep = ", ";
3844 if (ref->tag)
3845 is_tag = TRUE;
3848 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3849 try_add_describe_ref:
3850 /* Add <tag>-g<commit_id> "fake" reference. */
3851 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3852 return;
3855 if (bufpos == 0)
3856 return;
3858 add_line_text(view, buf, LINE_PP_REFS);
3861 static bool
3862 pager_common_read(struct view *view, const char *data, enum line_type type)
3864 struct line *line;
3866 if (!data)
3867 return TRUE;
3869 line = add_line_text(view, data, type);
3870 if (!line)
3871 return FALSE;
3873 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3874 add_pager_refs(view, data + STRING_SIZE("commit "));
3876 return TRUE;
3879 static bool
3880 pager_read(struct view *view, char *data)
3882 if (!data)
3883 return TRUE;
3885 return pager_common_read(view, data, get_line_type(data));
3888 static enum request
3889 pager_request(struct view *view, enum request request, struct line *line)
3891 int split = 0;
3893 if (request != REQ_ENTER)
3894 return request;
3896 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3897 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3898 split = 1;
3901 /* Always scroll the view even if it was split. That way
3902 * you can use Enter to scroll through the log view and
3903 * split open each commit diff. */
3904 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3906 /* FIXME: A minor workaround. Scrolling the view will call report("")
3907 * but if we are scrolling a non-current view this won't properly
3908 * update the view title. */
3909 if (split)
3910 update_view_title(view);
3912 return REQ_NONE;
3915 static bool
3916 pager_grep(struct view *view, struct line *line)
3918 const char *text[] = { line->data, NULL };
3920 return grep_text(view, text);
3923 static void
3924 pager_select(struct view *view, struct line *line)
3926 if (line->type == LINE_COMMIT) {
3927 char *text = (char *)line->data + STRING_SIZE("commit ");
3929 if (!view_has_flags(view, VIEW_NO_REF))
3930 string_copy_rev(view->ref, text);
3931 string_copy_rev(ref_commit, text);
3935 static bool
3936 pager_open(struct view *view, enum open_flags flags)
3938 if (display[0] == NULL) {
3939 if (!io_open(&view->io, ""))
3940 die("Failed to open stdin");
3941 flags = OPEN_PREPARED;
3943 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
3944 report("No pager content, press %s to run command from prompt",
3945 get_view_key(view, REQ_PROMPT));
3946 return FALSE;
3949 return begin_update(view, NULL, NULL, flags);
3952 static struct view_ops pager_ops = {
3953 "line",
3954 { "pager" },
3955 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3957 pager_open,
3958 pager_read,
3959 pager_draw,
3960 pager_request,
3961 pager_grep,
3962 pager_select,
3965 static bool
3966 log_open(struct view *view, enum open_flags flags)
3968 static const char *log_argv[] = {
3969 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3972 return begin_update(view, NULL, log_argv, flags);
3975 static enum request
3976 log_request(struct view *view, enum request request, struct line *line)
3978 switch (request) {
3979 case REQ_REFRESH:
3980 load_refs();
3981 refresh_view(view);
3982 return REQ_NONE;
3983 default:
3984 return pager_request(view, request, line);
3988 static struct view_ops log_ops = {
3989 "line",
3990 { "log" },
3991 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3993 log_open,
3994 pager_read,
3995 pager_draw,
3996 log_request,
3997 pager_grep,
3998 pager_select,
4001 struct diff_state {
4002 bool reading_diff_stat;
4003 bool combined_diff;
4006 static bool
4007 diff_open(struct view *view, enum open_flags flags)
4009 static const char *diff_argv[] = {
4010 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
4011 "--patch-with-stat", "--find-copies-harder", "-C",
4012 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4013 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4016 return begin_update(view, NULL, diff_argv, flags);
4019 static bool
4020 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4022 enum line_type type = get_line_type(data);
4024 if (!view->lines && type != LINE_COMMIT)
4025 state->reading_diff_stat = TRUE;
4027 if (state->reading_diff_stat) {
4028 size_t len = strlen(data);
4029 char *pipe = strchr(data, '|');
4030 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4031 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4032 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4034 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4035 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4036 } else {
4037 state->reading_diff_stat = FALSE;
4040 } else if (!strcmp(data, "---")) {
4041 state->reading_diff_stat = TRUE;
4044 if (type == LINE_DIFF_HEADER) {
4045 const int len = line_info[LINE_DIFF_HEADER].linelen;
4047 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4048 !strncmp(data + len, "cc ", strlen("cc ")))
4049 state->combined_diff = TRUE;
4052 /* ADD2 and DEL2 are only valid in combined diff hunks */
4053 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4054 type = LINE_DEFAULT;
4056 return pager_common_read(view, data, type);
4059 static bool
4060 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4062 struct line *marker = find_next_line_by_type(view, line, type);
4064 return marker &&
4065 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4068 static enum request
4069 diff_common_enter(struct view *view, enum request request, struct line *line)
4071 if (line->type == LINE_DIFF_STAT) {
4072 int file_number = 0;
4074 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4075 file_number++;
4076 line--;
4079 for (line = view->line; view_has_line(view, line); line++) {
4080 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4081 if (!line)
4082 break;
4084 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4085 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4086 if (file_number == 1) {
4087 break;
4089 file_number--;
4093 if (!line) {
4094 report("Failed to find file diff");
4095 return REQ_NONE;
4098 select_view_line(view, line - view->line);
4099 report("");
4100 return REQ_NONE;
4102 } else {
4103 return pager_request(view, request, line);
4107 static bool
4108 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4110 char *sep = strchr(*text, c);
4112 if (sep != NULL) {
4113 *sep = 0;
4114 draw_text(view, *type, *text);
4115 *sep = c;
4116 *text = sep;
4117 *type = next_type;
4120 return sep != NULL;
4123 static bool
4124 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4126 char *text = line->data;
4127 enum line_type type = line->type;
4129 if (draw_lineno(view, lineno))
4130 return TRUE;
4132 if (type == LINE_DIFF_STAT) {
4133 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4134 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4135 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4136 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4137 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4138 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4139 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4141 } else {
4142 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4143 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4147 draw_text(view, type, text);
4148 return TRUE;
4151 static bool
4152 diff_read(struct view *view, char *data)
4154 struct diff_state *state = view->private;
4156 if (!data) {
4157 /* Fall back to retry if no diff will be shown. */
4158 if (view->lines == 0 && opt_file_argv) {
4159 int pos = argv_size(view->argv)
4160 - argv_size(opt_file_argv) - 1;
4162 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4163 for (; view->argv[pos]; pos++) {
4164 free((void *) view->argv[pos]);
4165 view->argv[pos] = NULL;
4168 if (view->pipe)
4169 io_done(view->pipe);
4170 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4171 return FALSE;
4174 return TRUE;
4177 return diff_common_read(view, data, state);
4180 static bool
4181 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4182 struct blame_header *header, struct blame_commit *commit)
4184 char line_arg[SIZEOF_STR];
4185 const char *blame_argv[] = {
4186 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4188 struct io io;
4189 bool ok = FALSE;
4190 char *buf;
4192 if (!string_format(line_arg, "-L%d,+1", lineno))
4193 return FALSE;
4195 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4196 return FALSE;
4198 while ((buf = io_get(&io, '\n', TRUE))) {
4199 if (header) {
4200 if (!parse_blame_header(header, buf, 9999999))
4201 break;
4202 header = NULL;
4204 } else if (parse_blame_info(commit, buf)) {
4205 ok = TRUE;
4206 break;
4210 if (io_error(&io))
4211 ok = FALSE;
4213 io_done(&io);
4214 return ok;
4217 static bool
4218 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4220 return prefixcmp(chunk, "@@ -") ||
4221 !(chunk = strchr(chunk, marker)) ||
4222 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4225 static enum request
4226 diff_trace_origin(struct view *view, struct line *line)
4228 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4229 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4230 const char *chunk_data;
4231 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4232 int lineno = 0;
4233 const char *file = NULL;
4234 char ref[SIZEOF_REF];
4235 struct blame_header header;
4236 struct blame_commit commit;
4238 if (!diff || !chunk || chunk == line) {
4239 report("The line to trace must be inside a diff chunk");
4240 return REQ_NONE;
4243 for (; diff < line && !file; diff++) {
4244 const char *data = diff->data;
4246 if (!prefixcmp(data, "--- a/")) {
4247 file = data + STRING_SIZE("--- a/");
4248 break;
4252 if (diff == line || !file) {
4253 report("Failed to read the file name");
4254 return REQ_NONE;
4257 chunk_data = chunk->data;
4259 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4260 report("Failed to read the line number");
4261 return REQ_NONE;
4264 if (lineno == 0) {
4265 report("This is the origin of the line");
4266 return REQ_NONE;
4269 for (chunk += 1; chunk < line; chunk++) {
4270 if (chunk->type == LINE_DIFF_ADD) {
4271 lineno += chunk_marker == '+';
4272 } else if (chunk->type == LINE_DIFF_DEL) {
4273 lineno += chunk_marker == '-';
4274 } else {
4275 lineno++;
4279 if (chunk_marker == '+')
4280 string_copy(ref, view->vid);
4281 else
4282 string_format(ref, "%s^", view->vid);
4284 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4285 report("Failed to read blame data");
4286 return REQ_NONE;
4289 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4290 string_copy(opt_ref, header.id);
4291 opt_goto_line = header.orig_lineno - 1;
4293 return REQ_VIEW_BLAME;
4296 static enum request
4297 diff_request(struct view *view, enum request request, struct line *line)
4299 switch (request) {
4300 case REQ_VIEW_BLAME:
4301 return diff_trace_origin(view, line);
4303 case REQ_DIFF_CONTEXT_UP:
4304 case REQ_DIFF_CONTEXT_DOWN:
4305 if (!update_diff_context(request))
4306 return REQ_NONE;
4307 reload_view(view);
4308 return REQ_NONE;
4311 case REQ_ENTER:
4312 return diff_common_enter(view, request, line);
4314 default:
4315 return pager_request(view, request, line);
4319 static void
4320 diff_select(struct view *view, struct line *line)
4322 if (line->type == LINE_DIFF_STAT) {
4323 const char *key = get_view_key(view, REQ_ENTER);
4325 string_format(view->ref, "Press '%s' to jump to file diff", key);
4326 } else {
4327 struct line *header = line->type == LINE_DIFF_HEADER ? line :
4328 find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4330 if (header != NULL) {
4331 const char *file_name = NULL;
4333 for (header += 1; view_has_line(view, header); header++) {
4334 if (header->type == LINE_DIFF_RENAME_TO)
4335 file_name = header->data + STRING_SIZE("rename to ");
4336 if (header->type == LINE_DIFF_ADD && !strncmp(header->data, "+++ b/", 6))
4337 file_name = header->data + STRING_SIZE("+++ b/");
4339 /* The diff chunk marks the end of the diff header. */
4340 if (file_name || header->type == LINE_DIFF_CHUNK)
4341 break;
4344 string_format(view->ref, "Diff of '%s'", file_name);
4345 return;
4348 string_ncopy(view->ref, view->id, strlen(view->id));
4349 return pager_select(view, line);
4353 static struct view_ops diff_ops = {
4354 "line",
4355 { "diff" },
4356 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4357 sizeof(struct diff_state),
4358 diff_open,
4359 diff_read,
4360 diff_common_draw,
4361 diff_request,
4362 pager_grep,
4363 diff_select,
4367 * Help backend
4370 static bool
4371 help_draw(struct view *view, struct line *line, unsigned int lineno)
4373 if (line->type == LINE_HELP_KEYMAP) {
4374 struct keymap *keymap = line->data;
4376 draw_formatted(view, line->type, "[%c] %s bindings",
4377 keymap->hidden ? '+' : '-', keymap->name);
4378 return TRUE;
4379 } else {
4380 return pager_draw(view, line, lineno);
4384 static bool
4385 help_open_keymap_title(struct view *view, struct keymap *keymap)
4387 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4388 return keymap->hidden;
4391 static void
4392 help_open_keymap(struct view *view, struct keymap *keymap)
4394 const char *group = NULL;
4395 char buf[SIZEOF_STR];
4396 bool add_title = TRUE;
4397 int i;
4399 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4400 const char *key = NULL;
4402 if (req_info[i].request == REQ_NONE)
4403 continue;
4405 if (!req_info[i].request) {
4406 group = req_info[i].help;
4407 continue;
4410 key = get_keys(keymap, req_info[i].request, TRUE);
4411 if (!key || !*key)
4412 continue;
4414 if (add_title && help_open_keymap_title(view, keymap))
4415 return;
4416 add_title = FALSE;
4418 if (group) {
4419 add_line_text(view, group, LINE_HELP_GROUP);
4420 group = NULL;
4423 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4424 enum_name(req_info[i]), req_info[i].help);
4427 group = "External commands:";
4429 for (i = 0; i < run_requests; i++) {
4430 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4431 const char *key;
4433 if (!req || req->keymap != keymap)
4434 continue;
4436 key = get_key_name(req->key);
4437 if (!*key)
4438 key = "(no key defined)";
4440 if (add_title && help_open_keymap_title(view, keymap))
4441 return;
4442 add_title = FALSE;
4444 if (group) {
4445 add_line_text(view, group, LINE_HELP_GROUP);
4446 group = NULL;
4449 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4450 return;
4452 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4456 static bool
4457 help_open(struct view *view, enum open_flags flags)
4459 struct keymap *keymap;
4461 reset_view(view);
4462 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4463 add_line_text(view, "", LINE_DEFAULT);
4465 for (keymap = keymaps; keymap; keymap = keymap->next)
4466 help_open_keymap(view, keymap);
4468 return TRUE;
4471 static enum request
4472 help_request(struct view *view, enum request request, struct line *line)
4474 switch (request) {
4475 case REQ_ENTER:
4476 if (line->type == LINE_HELP_KEYMAP) {
4477 struct keymap *keymap = line->data;
4479 keymap->hidden = !keymap->hidden;
4480 refresh_view(view);
4483 return REQ_NONE;
4484 default:
4485 return pager_request(view, request, line);
4489 static struct view_ops help_ops = {
4490 "line",
4491 { "help" },
4492 VIEW_NO_GIT_DIR,
4494 help_open,
4495 NULL,
4496 help_draw,
4497 help_request,
4498 pager_grep,
4499 pager_select,
4504 * Tree backend
4507 struct tree_stack_entry {
4508 struct tree_stack_entry *prev; /* Entry below this in the stack */
4509 unsigned long lineno; /* Line number to restore */
4510 char *name; /* Position of name in opt_path */
4513 /* The top of the path stack. */
4514 static struct tree_stack_entry *tree_stack = NULL;
4515 unsigned long tree_lineno = 0;
4517 static void
4518 pop_tree_stack_entry(void)
4520 struct tree_stack_entry *entry = tree_stack;
4522 tree_lineno = entry->lineno;
4523 entry->name[0] = 0;
4524 tree_stack = entry->prev;
4525 free(entry);
4528 static void
4529 push_tree_stack_entry(const char *name, unsigned long lineno)
4531 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4532 size_t pathlen = strlen(opt_path);
4534 if (!entry)
4535 return;
4537 entry->prev = tree_stack;
4538 entry->name = opt_path + pathlen;
4539 tree_stack = entry;
4541 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4542 pop_tree_stack_entry();
4543 return;
4546 /* Move the current line to the first tree entry. */
4547 tree_lineno = 1;
4548 entry->lineno = lineno;
4551 /* Parse output from git-ls-tree(1):
4553 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4556 #define SIZEOF_TREE_ATTR \
4557 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4559 #define SIZEOF_TREE_MODE \
4560 STRING_SIZE("100644 ")
4562 #define TREE_ID_OFFSET \
4563 STRING_SIZE("100644 blob ")
4565 #define tree_path_is_parent(path) (!strcmp("..", (path)))
4567 struct tree_entry {
4568 char id[SIZEOF_REV];
4569 mode_t mode;
4570 struct time time; /* Date from the author ident. */
4571 const char *author; /* Author of the commit. */
4572 char name[1];
4575 struct tree_state {
4576 const char *author_name;
4577 struct time author_time;
4578 bool read_date;
4581 static const char *
4582 tree_path(const struct line *line)
4584 return ((struct tree_entry *) line->data)->name;
4587 static int
4588 tree_compare_entry(const struct line *line1, const struct line *line2)
4590 if (line1->type != line2->type)
4591 return line1->type == LINE_TREE_DIR ? -1 : 1;
4592 return strcmp(tree_path(line1), tree_path(line2));
4595 static const enum sort_field tree_sort_fields[] = {
4596 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4598 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4600 static int
4601 tree_compare(const void *l1, const void *l2)
4603 const struct line *line1 = (const struct line *) l1;
4604 const struct line *line2 = (const struct line *) l2;
4605 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4606 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4608 if (line1->type == LINE_TREE_HEAD)
4609 return -1;
4610 if (line2->type == LINE_TREE_HEAD)
4611 return 1;
4613 switch (get_sort_field(tree_sort_state)) {
4614 case ORDERBY_DATE:
4615 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4617 case ORDERBY_AUTHOR:
4618 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4620 case ORDERBY_NAME:
4621 default:
4622 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4627 static struct line *
4628 tree_entry(struct view *view, enum line_type type, const char *path,
4629 const char *mode, const char *id)
4631 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
4632 struct tree_entry *entry;
4633 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
4635 if (!line)
4636 return NULL;
4638 strncpy(entry->name, path, strlen(path));
4639 if (mode)
4640 entry->mode = strtoul(mode, NULL, 8);
4641 if (id)
4642 string_copy_rev(entry->id, id);
4644 return line;
4647 static bool
4648 tree_read_date(struct view *view, char *text, struct tree_state *state)
4650 if (!text && state->read_date) {
4651 state->read_date = FALSE;
4652 return TRUE;
4654 } else if (!text) {
4655 /* Find next entry to process */
4656 const char *log_file[] = {
4657 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4658 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4661 if (!view->lines) {
4662 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4663 report("Tree is empty");
4664 return TRUE;
4667 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4668 report("Failed to load tree data");
4669 return TRUE;
4672 state->read_date = TRUE;
4673 return FALSE;
4675 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4676 parse_author_line(text + STRING_SIZE("author "),
4677 &state->author_name, &state->author_time);
4679 } else if (*text == ':') {
4680 char *pos;
4681 size_t annotated = 1;
4682 size_t i;
4684 pos = strchr(text, '\t');
4685 if (!pos)
4686 return TRUE;
4687 text = pos + 1;
4688 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4689 text += strlen(opt_path);
4690 pos = strchr(text, '/');
4691 if (pos)
4692 *pos = 0;
4694 for (i = 1; i < view->lines; i++) {
4695 struct line *line = &view->line[i];
4696 struct tree_entry *entry = line->data;
4698 annotated += !!entry->author;
4699 if (entry->author || strcmp(entry->name, text))
4700 continue;
4702 entry->author = state->author_name;
4703 entry->time = state->author_time;
4704 line->dirty = 1;
4705 break;
4708 if (annotated == view->lines)
4709 io_kill(view->pipe);
4711 return TRUE;
4714 static bool
4715 tree_read(struct view *view, char *text)
4717 struct tree_state *state = view->private;
4718 struct tree_entry *data;
4719 struct line *entry, *line;
4720 enum line_type type;
4721 size_t textlen = text ? strlen(text) : 0;
4722 char *path = text + SIZEOF_TREE_ATTR;
4724 if (state->read_date || !text)
4725 return tree_read_date(view, text, state);
4727 if (textlen <= SIZEOF_TREE_ATTR)
4728 return FALSE;
4729 if (view->lines == 0 &&
4730 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4731 return FALSE;
4733 /* Strip the path part ... */
4734 if (*opt_path) {
4735 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4736 size_t striplen = strlen(opt_path);
4738 if (pathlen > striplen)
4739 memmove(path, path + striplen,
4740 pathlen - striplen + 1);
4742 /* Insert "link" to parent directory. */
4743 if (view->lines == 1 &&
4744 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4745 return FALSE;
4748 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4749 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4750 if (!entry)
4751 return FALSE;
4752 data = entry->data;
4754 /* Skip "Directory ..." and ".." line. */
4755 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4756 if (tree_compare_entry(line, entry) <= 0)
4757 continue;
4759 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4761 line->data = data;
4762 line->type = type;
4763 for (; line <= entry; line++)
4764 line->dirty = line->cleareol = 1;
4765 return TRUE;
4768 if (tree_lineno <= view->pos.lineno)
4769 tree_lineno = view->custom_lines;
4771 if (tree_lineno > view->pos.lineno) {
4772 view->pos.lineno = tree_lineno;
4773 tree_lineno = 0;
4776 return TRUE;
4779 static bool
4780 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4782 struct tree_entry *entry = line->data;
4784 if (line->type == LINE_TREE_HEAD) {
4785 if (draw_text(view, line->type, "Directory path /"))
4786 return TRUE;
4787 } else {
4788 if (draw_mode(view, entry->mode))
4789 return TRUE;
4791 if (draw_author(view, entry->author))
4792 return TRUE;
4794 if (draw_date(view, &entry->time))
4795 return TRUE;
4798 draw_text(view, line->type, entry->name);
4799 return TRUE;
4802 static void
4803 open_blob_editor(const char *id)
4805 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4806 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4807 int fd = mkstemp(file);
4809 if (fd == -1)
4810 report("Failed to create temporary file");
4811 else if (!io_run_append(blob_argv, fd))
4812 report("Failed to save blob data to file");
4813 else
4814 open_editor(file);
4815 if (fd != -1)
4816 unlink(file);
4819 static enum request
4820 tree_request(struct view *view, enum request request, struct line *line)
4822 enum open_flags flags;
4823 struct tree_entry *entry = line->data;
4825 switch (request) {
4826 case REQ_VIEW_BLAME:
4827 if (line->type != LINE_TREE_FILE) {
4828 report("Blame only supported for files");
4829 return REQ_NONE;
4832 string_copy(opt_ref, view->vid);
4833 return request;
4835 case REQ_EDIT:
4836 if (line->type != LINE_TREE_FILE) {
4837 report("Edit only supported for files");
4838 } else if (!is_head_commit(view->vid)) {
4839 open_blob_editor(entry->id);
4840 } else {
4841 open_editor(opt_file);
4843 return REQ_NONE;
4845 case REQ_TOGGLE_SORT_FIELD:
4846 case REQ_TOGGLE_SORT_ORDER:
4847 sort_view(view, request, &tree_sort_state, tree_compare);
4848 return REQ_NONE;
4850 case REQ_PARENT:
4851 if (!*opt_path) {
4852 /* quit view if at top of tree */
4853 return REQ_VIEW_CLOSE;
4855 /* fake 'cd ..' */
4856 line = &view->line[1];
4857 break;
4859 case REQ_ENTER:
4860 break;
4862 default:
4863 return request;
4866 /* Cleanup the stack if the tree view is at a different tree. */
4867 while (!*opt_path && tree_stack)
4868 pop_tree_stack_entry();
4870 switch (line->type) {
4871 case LINE_TREE_DIR:
4872 /* Depending on whether it is a subdirectory or parent link
4873 * mangle the path buffer. */
4874 if (line == &view->line[1] && *opt_path) {
4875 pop_tree_stack_entry();
4877 } else {
4878 const char *basename = tree_path(line);
4880 push_tree_stack_entry(basename, view->pos.lineno);
4883 /* Trees and subtrees share the same ID, so they are not not
4884 * unique like blobs. */
4885 flags = OPEN_RELOAD;
4886 request = REQ_VIEW_TREE;
4887 break;
4889 case LINE_TREE_FILE:
4890 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4891 request = REQ_VIEW_BLOB;
4892 break;
4894 default:
4895 return REQ_NONE;
4898 open_view(view, request, flags);
4899 if (request == REQ_VIEW_TREE)
4900 view->pos.lineno = tree_lineno;
4902 return REQ_NONE;
4905 static bool
4906 tree_grep(struct view *view, struct line *line)
4908 struct tree_entry *entry = line->data;
4909 const char *text[] = {
4910 entry->name,
4911 mkauthor(entry->author, opt_author_cols, opt_author),
4912 mkdate(&entry->time, opt_date),
4913 NULL
4916 return grep_text(view, text);
4919 static void
4920 tree_select(struct view *view, struct line *line)
4922 struct tree_entry *entry = line->data;
4924 if (line->type == LINE_TREE_HEAD) {
4925 string_format(view->ref, "Files in /%s", opt_path);
4926 return;
4929 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
4930 string_copy(view->ref, "Open parent directory");
4931 return;
4934 if (line->type == LINE_TREE_FILE) {
4935 string_copy_rev(ref_blob, entry->id);
4936 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4939 string_copy_rev(view->ref, entry->id);
4942 static bool
4943 tree_open(struct view *view, enum open_flags flags)
4945 static const char *tree_argv[] = {
4946 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4949 if (string_rev_is_null(ref_commit)) {
4950 report("No tree exists for this commit");
4951 return FALSE;
4954 if (view->lines == 0 && opt_prefix[0]) {
4955 char *pos = opt_prefix;
4957 while (pos && *pos) {
4958 char *end = strchr(pos, '/');
4960 if (end)
4961 *end = 0;
4962 push_tree_stack_entry(pos, 0);
4963 pos = end;
4964 if (end) {
4965 *end = '/';
4966 pos++;
4970 } else if (strcmp(view->vid, view->id)) {
4971 opt_path[0] = 0;
4974 return begin_update(view, opt_cdup, tree_argv, flags);
4977 static struct view_ops tree_ops = {
4978 "file",
4979 { "tree" },
4980 VIEW_NO_FLAGS,
4981 sizeof(struct tree_state),
4982 tree_open,
4983 tree_read,
4984 tree_draw,
4985 tree_request,
4986 tree_grep,
4987 tree_select,
4990 static bool
4991 blob_open(struct view *view, enum open_flags flags)
4993 static const char *blob_argv[] = {
4994 "git", "cat-file", "blob", "%(blob)", NULL
4997 if (!ref_blob[0]) {
4998 report("No file chosen, press %s to open tree view",
4999 get_view_key(view, REQ_VIEW_TREE));
5000 return FALSE;
5003 view->encoding = get_path_encoding(opt_file, opt_encoding);
5005 return begin_update(view, NULL, blob_argv, flags);
5008 static bool
5009 blob_read(struct view *view, char *line)
5011 if (!line)
5012 return TRUE;
5013 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5016 static enum request
5017 blob_request(struct view *view, enum request request, struct line *line)
5019 switch (request) {
5020 case REQ_EDIT:
5021 open_blob_editor(view->vid);
5022 return REQ_NONE;
5023 default:
5024 return pager_request(view, request, line);
5028 static struct view_ops blob_ops = {
5029 "line",
5030 { "blob" },
5031 VIEW_NO_FLAGS,
5033 blob_open,
5034 blob_read,
5035 pager_draw,
5036 blob_request,
5037 pager_grep,
5038 pager_select,
5042 * Blame backend
5044 * Loading the blame view is a two phase job:
5046 * 1. File content is read either using opt_file from the
5047 * filesystem or using git-cat-file.
5048 * 2. Then blame information is incrementally added by
5049 * reading output from git-blame.
5052 struct blame {
5053 struct blame_commit *commit;
5054 unsigned long lineno;
5055 char text[1];
5058 struct blame_state {
5059 struct blame_commit *commit;
5060 int blamed;
5061 bool done_reading;
5062 bool auto_filename_display;
5065 static bool
5066 blame_detect_filename_display(struct view *view)
5068 bool show_filenames = FALSE;
5069 const char *filename = NULL;
5070 int i;
5072 if (opt_blame_argv) {
5073 for (i = 0; opt_blame_argv[i]; i++) {
5074 if (prefixcmp(opt_blame_argv[i], "-C"))
5075 continue;
5077 show_filenames = TRUE;
5081 for (i = 0; i < view->lines; i++) {
5082 struct blame *blame = view->line[i].data;
5084 if (blame->commit && blame->commit->id[0]) {
5085 if (!filename)
5086 filename = blame->commit->filename;
5087 else if (strcmp(filename, blame->commit->filename))
5088 show_filenames = TRUE;
5092 return show_filenames;
5095 static bool
5096 blame_open(struct view *view, enum open_flags flags)
5098 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5099 char path[SIZEOF_STR];
5100 size_t i;
5102 if (!opt_file[0]) {
5103 report("No file chosen, press %s to open tree view",
5104 get_view_key(view, REQ_VIEW_TREE));
5105 return FALSE;
5108 if (!view->prev && *opt_prefix) {
5109 string_copy(path, opt_file);
5110 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5111 report("Failed to setup the blame view");
5112 return FALSE;
5116 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5117 const char *blame_cat_file_argv[] = {
5118 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5121 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5122 return FALSE;
5125 /* First pass: remove multiple references to the same commit. */
5126 for (i = 0; i < view->lines; i++) {
5127 struct blame *blame = view->line[i].data;
5129 if (blame->commit && blame->commit->id[0])
5130 blame->commit->id[0] = 0;
5131 else
5132 blame->commit = NULL;
5135 /* Second pass: free existing references. */
5136 for (i = 0; i < view->lines; i++) {
5137 struct blame *blame = view->line[i].data;
5139 if (blame->commit)
5140 free(blame->commit);
5143 string_format(view->vid, "%s", opt_file);
5144 string_format(view->ref, "%s ...", opt_file);
5146 return TRUE;
5149 static struct blame_commit *
5150 get_blame_commit(struct view *view, const char *id)
5152 size_t i;
5154 for (i = 0; i < view->lines; i++) {
5155 struct blame *blame = view->line[i].data;
5157 if (!blame->commit)
5158 continue;
5160 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5161 return blame->commit;
5165 struct blame_commit *commit = calloc(1, sizeof(*commit));
5167 if (commit)
5168 string_ncopy(commit->id, id, SIZEOF_REV);
5169 return commit;
5173 static struct blame_commit *
5174 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5176 struct blame_header header;
5177 struct blame_commit *commit;
5178 struct blame *blame;
5180 if (!parse_blame_header(&header, text, view->lines))
5181 return NULL;
5183 commit = get_blame_commit(view, text);
5184 if (!commit)
5185 return NULL;
5187 state->blamed += header.group;
5188 while (header.group--) {
5189 struct line *line = &view->line[header.lineno + header.group - 1];
5191 blame = line->data;
5192 blame->commit = commit;
5193 blame->lineno = header.orig_lineno + header.group - 1;
5194 line->dirty = 1;
5197 return commit;
5200 static bool
5201 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5203 if (!text) {
5204 const char *blame_argv[] = {
5205 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5206 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5209 if (view->lines == 0 && !view->prev)
5210 die("No blame exist for %s", view->vid);
5212 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5213 report("Failed to load blame data");
5214 return TRUE;
5217 if (opt_goto_line > 0) {
5218 select_view_line(view, opt_goto_line);
5219 opt_goto_line = 0;
5222 state->done_reading = TRUE;
5223 return FALSE;
5225 } else {
5226 size_t textlen = strlen(text);
5227 struct blame *blame;
5229 if (!add_line_alloc(view, &blame, LINE_BLAME_ID, textlen, FALSE))
5230 return FALSE;
5232 blame->commit = NULL;
5233 strncpy(blame->text, text, textlen);
5234 blame->text[textlen] = 0;
5235 return TRUE;
5239 static bool
5240 blame_read(struct view *view, char *line)
5242 struct blame_state *state = view->private;
5244 if (!state->done_reading)
5245 return blame_read_file(view, line, state);
5247 if (!line) {
5248 state->auto_filename_display = blame_detect_filename_display(view);
5249 string_format(view->ref, "%s", view->vid);
5250 if (view_is_displayed(view)) {
5251 update_view_title(view);
5252 redraw_view_from(view, 0);
5254 return TRUE;
5257 if (!state->commit) {
5258 state->commit = read_blame_commit(view, line, state);
5259 string_format(view->ref, "%s %2d%%", view->vid,
5260 view->lines ? state->blamed * 100 / view->lines : 0);
5262 } else if (parse_blame_info(state->commit, line)) {
5263 state->commit = NULL;
5266 return TRUE;
5269 static bool
5270 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5272 struct blame_state *state = view->private;
5273 struct blame *blame = line->data;
5274 struct time *time = NULL;
5275 const char *id = NULL, *author = NULL, *filename = NULL;
5276 enum line_type id_type = LINE_BLAME_ID;
5277 static const enum line_type blame_colors[] = {
5278 LINE_PALETTE_0,
5279 LINE_PALETTE_1,
5280 LINE_PALETTE_2,
5281 LINE_PALETTE_3,
5282 LINE_PALETTE_4,
5283 LINE_PALETTE_5,
5284 LINE_PALETTE_6,
5287 #define BLAME_COLOR(i) \
5288 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5290 if (blame->commit && *blame->commit->filename) {
5291 id = blame->commit->id;
5292 author = blame->commit->author;
5293 filename = blame->commit->filename;
5294 time = &blame->commit->time;
5295 id_type = BLAME_COLOR((long) blame->commit);
5298 if (draw_date(view, time))
5299 return TRUE;
5301 if (draw_author(view, author))
5302 return TRUE;
5304 if (draw_filename(view, filename, state->auto_filename_display))
5305 return TRUE;
5307 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5308 return TRUE;
5310 if (draw_lineno(view, lineno))
5311 return TRUE;
5313 draw_text(view, LINE_DEFAULT, blame->text);
5314 return TRUE;
5317 static bool
5318 check_blame_commit(struct blame *blame, bool check_null_id)
5320 if (!blame->commit)
5321 report("Commit data not loaded yet");
5322 else if (check_null_id && string_rev_is_null(blame->commit->id))
5323 report("No commit exist for the selected line");
5324 else
5325 return TRUE;
5326 return FALSE;
5329 static void
5330 setup_blame_parent_line(struct view *view, struct blame *blame)
5332 char from[SIZEOF_REF + SIZEOF_STR];
5333 char to[SIZEOF_REF + SIZEOF_STR];
5334 const char *diff_tree_argv[] = {
5335 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5336 "--no-color", "-U0", from, to, "--", NULL
5338 struct io io;
5339 int parent_lineno = -1;
5340 int blamed_lineno = -1;
5341 char *line;
5343 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5344 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5345 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5346 return;
5348 while ((line = io_get(&io, '\n', TRUE))) {
5349 if (*line == '@') {
5350 char *pos = strchr(line, '+');
5352 parent_lineno = atoi(line + 4);
5353 if (pos)
5354 blamed_lineno = atoi(pos + 1);
5356 } else if (*line == '+' && parent_lineno != -1) {
5357 if (blame->lineno == blamed_lineno - 1 &&
5358 !strcmp(blame->text, line + 1)) {
5359 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5360 break;
5362 blamed_lineno++;
5366 io_done(&io);
5369 static enum request
5370 blame_request(struct view *view, enum request request, struct line *line)
5372 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5373 struct blame *blame = line->data;
5375 switch (request) {
5376 case REQ_VIEW_BLAME:
5377 if (check_blame_commit(blame, TRUE)) {
5378 string_copy(opt_ref, blame->commit->id);
5379 string_copy(opt_file, blame->commit->filename);
5380 if (blame->lineno)
5381 view->pos.lineno = blame->lineno;
5382 reload_view(view);
5384 break;
5386 case REQ_PARENT:
5387 if (!check_blame_commit(blame, TRUE))
5388 break;
5389 if (!*blame->commit->parent_id) {
5390 report("The selected commit has no parents");
5391 } else {
5392 string_copy_rev(opt_ref, blame->commit->parent_id);
5393 string_copy(opt_file, blame->commit->parent_filename);
5394 setup_blame_parent_line(view, blame);
5395 opt_goto_line = blame->lineno;
5396 reload_view(view);
5398 break;
5400 case REQ_ENTER:
5401 if (!check_blame_commit(blame, FALSE))
5402 break;
5404 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5405 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5406 break;
5408 if (string_rev_is_null(blame->commit->id)) {
5409 struct view *diff = VIEW(REQ_VIEW_DIFF);
5410 const char *diff_parent_argv[] = {
5411 GIT_DIFF_BLAME(opt_diff_context_arg,
5412 opt_ignore_space_arg, view->vid)
5414 const char *diff_no_parent_argv[] = {
5415 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5416 opt_ignore_space_arg, view->vid)
5418 const char **diff_index_argv = *blame->commit->parent_id
5419 ? diff_parent_argv : diff_no_parent_argv;
5421 open_argv(view, diff, diff_index_argv, NULL, flags);
5422 if (diff->pipe)
5423 string_copy_rev(diff->ref, NULL_ID);
5424 } else {
5425 open_view(view, REQ_VIEW_DIFF, flags);
5427 break;
5429 default:
5430 return request;
5433 return REQ_NONE;
5436 static bool
5437 blame_grep(struct view *view, struct line *line)
5439 struct blame *blame = line->data;
5440 struct blame_commit *commit = blame->commit;
5441 const char *text[] = {
5442 blame->text,
5443 commit ? commit->title : "",
5444 commit ? commit->id : "",
5445 commit && opt_author ? commit->author : "",
5446 commit ? mkdate(&commit->time, opt_date) : "",
5447 NULL
5450 return grep_text(view, text);
5453 static void
5454 blame_select(struct view *view, struct line *line)
5456 struct blame *blame = line->data;
5457 struct blame_commit *commit = blame->commit;
5459 if (!commit)
5460 return;
5462 if (string_rev_is_null(commit->id))
5463 string_ncopy(ref_commit, "HEAD", 4);
5464 else
5465 string_copy_rev(ref_commit, commit->id);
5468 static struct view_ops blame_ops = {
5469 "line",
5470 { "blame" },
5471 VIEW_ALWAYS_LINENO,
5472 sizeof(struct blame_state),
5473 blame_open,
5474 blame_read,
5475 blame_draw,
5476 blame_request,
5477 blame_grep,
5478 blame_select,
5482 * Branch backend
5485 struct branch {
5486 const char *author; /* Author of the last commit. */
5487 struct time time; /* Date of the last activity. */
5488 char title[128]; /* First line of the commit message. */
5489 const struct ref *ref; /* Name and commit ID information. */
5492 static const struct ref branch_all;
5493 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5495 static const enum sort_field branch_sort_fields[] = {
5496 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5498 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5500 struct branch_state {
5501 char id[SIZEOF_REV];
5502 size_t max_ref_length;
5505 static int
5506 branch_compare(const void *l1, const void *l2)
5508 const struct branch *branch1 = ((const struct line *) l1)->data;
5509 const struct branch *branch2 = ((const struct line *) l2)->data;
5511 if (branch_is_all(branch1))
5512 return -1;
5513 else if (branch_is_all(branch2))
5514 return 1;
5516 switch (get_sort_field(branch_sort_state)) {
5517 case ORDERBY_DATE:
5518 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5520 case ORDERBY_AUTHOR:
5521 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5523 case ORDERBY_NAME:
5524 default:
5525 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5529 static bool
5530 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5532 struct branch_state *state = view->private;
5533 struct branch *branch = line->data;
5534 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5535 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5537 if (draw_date(view, &branch->time))
5538 return TRUE;
5540 if (draw_author(view, branch->author))
5541 return TRUE;
5543 if (draw_field(view, type, branch_name, state->max_ref_length + 1, FALSE))
5544 return TRUE;
5546 draw_text(view, LINE_DEFAULT, branch->title);
5547 return TRUE;
5550 static enum request
5551 branch_request(struct view *view, enum request request, struct line *line)
5553 struct branch *branch = line->data;
5555 switch (request) {
5556 case REQ_REFRESH:
5557 load_refs();
5558 refresh_view(view);
5559 return REQ_NONE;
5561 case REQ_TOGGLE_SORT_FIELD:
5562 case REQ_TOGGLE_SORT_ORDER:
5563 sort_view(view, request, &branch_sort_state, branch_compare);
5564 return REQ_NONE;
5566 case REQ_ENTER:
5568 const struct ref *ref = branch->ref;
5569 const char *all_branches_argv[] = {
5570 GIT_MAIN_LOG("", branch_is_all(branch) ? "--all" : ref->name, "")
5572 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5574 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5575 return REQ_NONE;
5577 case REQ_JUMP_COMMIT:
5579 int lineno;
5581 for (lineno = 0; lineno < view->lines; lineno++) {
5582 struct branch *branch = view->line[lineno].data;
5584 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5585 select_view_line(view, lineno);
5586 report("");
5587 return REQ_NONE;
5591 default:
5592 return request;
5596 static bool
5597 branch_read(struct view *view, char *line)
5599 struct branch_state *state = view->private;
5600 const char *title = NULL;
5601 const char *author = NULL;
5602 struct time time = {};
5603 size_t i;
5605 if (!line)
5606 return TRUE;
5608 switch (get_line_type(line)) {
5609 case LINE_COMMIT:
5610 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5611 return TRUE;
5613 case LINE_AUTHOR:
5614 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5616 default:
5617 title = line + STRING_SIZE("title ");
5620 for (i = 0; i < view->lines; i++) {
5621 struct branch *branch = view->line[i].data;
5623 if (strcmp(branch->ref->id, state->id))
5624 continue;
5626 if (author) {
5627 branch->author = author;
5628 branch->time = time;
5631 if (title)
5632 string_expand(branch->title, sizeof(branch->title), title, 1);
5634 view->line[i].dirty = TRUE;
5637 return TRUE;
5640 static bool
5641 branch_open_visitor(void *data, const struct ref *ref)
5643 struct view *view = data;
5644 struct branch_state *state = view->private;
5645 struct branch *branch;
5646 size_t ref_length;
5648 if (ref->tag || ref->ltag)
5649 return TRUE;
5651 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, ref == &branch_all))
5652 return FALSE;
5654 ref_length = strlen(ref->name);
5655 if (ref_length > state->max_ref_length)
5656 state->max_ref_length = ref_length;
5658 branch->ref = ref;
5659 return TRUE;
5662 static bool
5663 branch_open(struct view *view, enum open_flags flags)
5665 const char *branch_log[] = {
5666 "git", "log", ENCODING_ARG, "--no-color", "--date=raw",
5667 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5668 "--all", "--simplify-by-decoration", NULL
5671 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5672 report("Failed to load branch data");
5673 return FALSE;
5676 branch_open_visitor(view, &branch_all);
5677 foreach_ref(branch_open_visitor, view);
5679 return TRUE;
5682 static bool
5683 branch_grep(struct view *view, struct line *line)
5685 struct branch *branch = line->data;
5686 const char *text[] = {
5687 branch->ref->name,
5688 mkauthor(branch->author, opt_author_cols, opt_author),
5689 NULL
5692 return grep_text(view, text);
5695 static void
5696 branch_select(struct view *view, struct line *line)
5698 struct branch *branch = line->data;
5700 if (branch_is_all(branch)) {
5701 string_copy(view->ref, "All branches");
5702 return;
5704 string_copy_rev(view->ref, branch->ref->id);
5705 string_copy_rev(ref_commit, branch->ref->id);
5706 string_copy_rev(ref_head, branch->ref->id);
5707 string_copy_rev(ref_branch, branch->ref->name);
5710 static struct view_ops branch_ops = {
5711 "branch",
5712 { "branch" },
5713 VIEW_NO_FLAGS,
5714 sizeof(struct branch_state),
5715 branch_open,
5716 branch_read,
5717 branch_draw,
5718 branch_request,
5719 branch_grep,
5720 branch_select,
5724 * Status backend
5727 struct status {
5728 char status;
5729 struct {
5730 mode_t mode;
5731 char rev[SIZEOF_REV];
5732 char name[SIZEOF_STR];
5733 } old;
5734 struct {
5735 mode_t mode;
5736 char rev[SIZEOF_REV];
5737 char name[SIZEOF_STR];
5738 } new;
5741 static char status_onbranch[SIZEOF_STR];
5742 static struct status stage_status;
5743 static enum line_type stage_line_type;
5745 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5747 /* This should work even for the "On branch" line. */
5748 static inline bool
5749 status_has_none(struct view *view, struct line *line)
5751 return view_has_line(view, line) && !line[1].data;
5754 /* Get fields from the diff line:
5755 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5757 static inline bool
5758 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5760 const char *old_mode = buf + 1;
5761 const char *new_mode = buf + 8;
5762 const char *old_rev = buf + 15;
5763 const char *new_rev = buf + 56;
5764 const char *status = buf + 97;
5766 if (bufsize < 98 ||
5767 old_mode[-1] != ':' ||
5768 new_mode[-1] != ' ' ||
5769 old_rev[-1] != ' ' ||
5770 new_rev[-1] != ' ' ||
5771 status[-1] != ' ')
5772 return FALSE;
5774 file->status = *status;
5776 string_copy_rev(file->old.rev, old_rev);
5777 string_copy_rev(file->new.rev, new_rev);
5779 file->old.mode = strtoul(old_mode, NULL, 8);
5780 file->new.mode = strtoul(new_mode, NULL, 8);
5782 file->old.name[0] = file->new.name[0] = 0;
5784 return TRUE;
5787 static bool
5788 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5790 struct status *unmerged = NULL;
5791 char *buf;
5792 struct io io;
5794 if (!io_run(&io, IO_RD, opt_cdup, argv))
5795 return FALSE;
5797 add_line_nodata(view, type);
5799 while ((buf = io_get(&io, 0, TRUE))) {
5800 struct status *file = unmerged;
5802 if (!file) {
5803 if (!add_line_alloc(view, &file, type, 0, FALSE))
5804 goto error_out;
5807 /* Parse diff info part. */
5808 if (status) {
5809 file->status = status;
5810 if (status == 'A')
5811 string_copy(file->old.rev, NULL_ID);
5813 } else if (!file->status || file == unmerged) {
5814 if (!status_get_diff(file, buf, strlen(buf)))
5815 goto error_out;
5817 buf = io_get(&io, 0, TRUE);
5818 if (!buf)
5819 break;
5821 /* Collapse all modified entries that follow an
5822 * associated unmerged entry. */
5823 if (unmerged == file) {
5824 unmerged->status = 'U';
5825 unmerged = NULL;
5826 } else if (file->status == 'U') {
5827 unmerged = file;
5831 /* Grab the old name for rename/copy. */
5832 if (!*file->old.name &&
5833 (file->status == 'R' || file->status == 'C')) {
5834 string_ncopy(file->old.name, buf, strlen(buf));
5836 buf = io_get(&io, 0, TRUE);
5837 if (!buf)
5838 break;
5841 /* git-ls-files just delivers a NUL separated list of
5842 * file names similar to the second half of the
5843 * git-diff-* output. */
5844 string_ncopy(file->new.name, buf, strlen(buf));
5845 if (!*file->old.name)
5846 string_copy(file->old.name, file->new.name);
5847 file = NULL;
5850 if (io_error(&io)) {
5851 error_out:
5852 io_done(&io);
5853 return FALSE;
5856 if (!view->line[view->lines - 1].data)
5857 add_line_nodata(view, LINE_STAT_NONE);
5859 io_done(&io);
5860 return TRUE;
5863 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5864 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5866 static const char *status_list_other_argv[] = {
5867 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5870 static const char *status_list_no_head_argv[] = {
5871 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5874 static const char *update_index_argv[] = {
5875 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5878 /* Restore the previous line number to stay in the context or select a
5879 * line with something that can be updated. */
5880 static void
5881 status_restore(struct view *view)
5883 if (!check_position(&view->prev_pos))
5884 return;
5886 if (view->prev_pos.lineno >= view->lines)
5887 view->prev_pos.lineno = view->lines - 1;
5888 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5889 view->prev_pos.lineno++;
5890 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5891 view->prev_pos.lineno--;
5893 /* If the above fails, always skip the "On branch" line. */
5894 if (view->prev_pos.lineno < view->lines)
5895 view->pos.lineno = view->prev_pos.lineno;
5896 else
5897 view->pos.lineno = 1;
5899 if (view->prev_pos.offset > view->pos.lineno)
5900 view->pos.offset = view->pos.lineno;
5901 else if (view->prev_pos.offset < view->lines)
5902 view->pos.offset = view->prev_pos.offset;
5904 clear_position(&view->prev_pos);
5907 static void
5908 status_update_onbranch(void)
5910 static const char *paths[][2] = {
5911 { "rebase-apply/rebasing", "Rebasing" },
5912 { "rebase-apply/applying", "Applying mailbox" },
5913 { "rebase-apply/", "Rebasing mailbox" },
5914 { "rebase-merge/interactive", "Interactive rebase" },
5915 { "rebase-merge/", "Rebase merge" },
5916 { "MERGE_HEAD", "Merging" },
5917 { "BISECT_LOG", "Bisecting" },
5918 { "HEAD", "On branch" },
5920 char buf[SIZEOF_STR];
5921 struct stat stat;
5922 int i;
5924 if (is_initial_commit()) {
5925 string_copy(status_onbranch, "Initial commit");
5926 return;
5929 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5930 char *head = opt_head;
5932 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5933 lstat(buf, &stat) < 0)
5934 continue;
5936 if (!*opt_head) {
5937 struct io io;
5939 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5940 io_read_buf(&io, buf, sizeof(buf))) {
5941 head = buf;
5942 if (!prefixcmp(head, "refs/heads/"))
5943 head += STRING_SIZE("refs/heads/");
5947 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5948 string_copy(status_onbranch, opt_head);
5949 return;
5952 string_copy(status_onbranch, "Not currently on any branch");
5955 /* First parse staged info using git-diff-index(1), then parse unstaged
5956 * info using git-diff-files(1), and finally untracked files using
5957 * git-ls-files(1). */
5958 static bool
5959 status_open(struct view *view, enum open_flags flags)
5961 const char **staged_argv = is_initial_commit() ?
5962 status_list_no_head_argv : status_diff_index_argv;
5963 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
5965 if (opt_is_inside_work_tree == FALSE) {
5966 report("The status view requires a working tree");
5967 return FALSE;
5970 reset_view(view);
5972 add_line_nodata(view, LINE_STAT_HEAD);
5973 status_update_onbranch();
5975 io_run_bg(update_index_argv);
5977 if (!opt_untracked_dirs_content)
5978 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5980 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
5981 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5982 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
5983 report("Failed to load status data");
5984 return FALSE;
5987 /* Restore the exact position or use the specialized restore
5988 * mode? */
5989 status_restore(view);
5990 return TRUE;
5993 static bool
5994 status_draw(struct view *view, struct line *line, unsigned int lineno)
5996 struct status *status = line->data;
5997 enum line_type type;
5998 const char *text;
6000 if (!status) {
6001 switch (line->type) {
6002 case LINE_STAT_STAGED:
6003 type = LINE_STAT_SECTION;
6004 text = "Changes to be committed:";
6005 break;
6007 case LINE_STAT_UNSTAGED:
6008 type = LINE_STAT_SECTION;
6009 text = "Changed but not updated:";
6010 break;
6012 case LINE_STAT_UNTRACKED:
6013 type = LINE_STAT_SECTION;
6014 text = "Untracked files:";
6015 break;
6017 case LINE_STAT_NONE:
6018 type = LINE_DEFAULT;
6019 text = " (no files)";
6020 break;
6022 case LINE_STAT_HEAD:
6023 type = LINE_STAT_HEAD;
6024 text = status_onbranch;
6025 break;
6027 default:
6028 return FALSE;
6030 } else {
6031 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6033 buf[0] = status->status;
6034 if (draw_text(view, line->type, buf))
6035 return TRUE;
6036 type = LINE_DEFAULT;
6037 text = status->new.name;
6040 draw_text(view, type, text);
6041 return TRUE;
6044 static enum request
6045 status_enter(struct view *view, struct line *line)
6047 struct status *status = line->data;
6048 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6050 if (line->type == LINE_STAT_NONE ||
6051 (!status && line[1].type == LINE_STAT_NONE)) {
6052 report("No file to diff");
6053 return REQ_NONE;
6056 switch (line->type) {
6057 case LINE_STAT_STAGED:
6058 case LINE_STAT_UNSTAGED:
6059 break;
6061 case LINE_STAT_UNTRACKED:
6062 if (!status) {
6063 report("No file to show");
6064 return REQ_NONE;
6067 if (!suffixcmp(status->new.name, -1, "/")) {
6068 report("Cannot display a directory");
6069 return REQ_NONE;
6071 break;
6073 case LINE_STAT_HEAD:
6074 return REQ_NONE;
6076 default:
6077 die("line type %d not handled in switch", line->type);
6080 if (status) {
6081 stage_status = *status;
6082 } else {
6083 memset(&stage_status, 0, sizeof(stage_status));
6086 stage_line_type = line->type;
6088 open_view(view, REQ_VIEW_STAGE, flags);
6089 return REQ_NONE;
6092 static bool
6093 status_exists(struct view *view, struct status *status, enum line_type type)
6095 unsigned long lineno;
6097 for (lineno = 0; lineno < view->lines; lineno++) {
6098 struct line *line = &view->line[lineno];
6099 struct status *pos = line->data;
6101 if (line->type != type)
6102 continue;
6103 if (!pos && (!status || !status->status) && line[1].data) {
6104 select_view_line(view, lineno);
6105 return TRUE;
6107 if (pos && !strcmp(status->new.name, pos->new.name)) {
6108 select_view_line(view, lineno);
6109 return TRUE;
6113 return FALSE;
6117 static bool
6118 status_update_prepare(struct io *io, enum line_type type)
6120 const char *staged_argv[] = {
6121 "git", "update-index", "-z", "--index-info", NULL
6123 const char *others_argv[] = {
6124 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6127 switch (type) {
6128 case LINE_STAT_STAGED:
6129 return io_run(io, IO_WR, opt_cdup, staged_argv);
6131 case LINE_STAT_UNSTAGED:
6132 case LINE_STAT_UNTRACKED:
6133 return io_run(io, IO_WR, opt_cdup, others_argv);
6135 default:
6136 die("line type %d not handled in switch", type);
6137 return FALSE;
6141 static bool
6142 status_update_write(struct io *io, struct status *status, enum line_type type)
6144 switch (type) {
6145 case LINE_STAT_STAGED:
6146 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6147 status->old.rev, status->old.name, 0);
6149 case LINE_STAT_UNSTAGED:
6150 case LINE_STAT_UNTRACKED:
6151 return io_printf(io, "%s%c", status->new.name, 0);
6153 default:
6154 die("line type %d not handled in switch", type);
6155 return FALSE;
6159 static bool
6160 status_update_file(struct status *status, enum line_type type)
6162 struct io io;
6163 bool result;
6165 if (!status_update_prepare(&io, type))
6166 return FALSE;
6168 result = status_update_write(&io, status, type);
6169 return io_done(&io) && result;
6172 static bool
6173 status_update_files(struct view *view, struct line *line)
6175 char buf[sizeof(view->ref)];
6176 struct io io;
6177 bool result = TRUE;
6178 struct line *pos;
6179 int files = 0;
6180 int file, done;
6181 int cursor_y = -1, cursor_x = -1;
6183 if (!status_update_prepare(&io, line->type))
6184 return FALSE;
6186 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6187 files++;
6189 string_copy(buf, view->ref);
6190 getsyx(cursor_y, cursor_x);
6191 for (file = 0, done = 5; result && file < files; line++, file++) {
6192 int almost_done = file * 100 / files;
6194 if (almost_done > done) {
6195 done = almost_done;
6196 string_format(view->ref, "updating file %u of %u (%d%% done)",
6197 file, files, done);
6198 update_view_title(view);
6199 setsyx(cursor_y, cursor_x);
6200 doupdate();
6202 result = status_update_write(&io, line->data, line->type);
6204 string_copy(view->ref, buf);
6206 return io_done(&io) && result;
6209 static bool
6210 status_update(struct view *view)
6212 struct line *line = &view->line[view->pos.lineno];
6214 assert(view->lines);
6216 if (!line->data) {
6217 if (status_has_none(view, line)) {
6218 report("Nothing to update");
6219 return FALSE;
6222 if (!status_update_files(view, line + 1)) {
6223 report("Failed to update file status");
6224 return FALSE;
6227 } else if (!status_update_file(line->data, line->type)) {
6228 report("Failed to update file status");
6229 return FALSE;
6232 return TRUE;
6235 static bool
6236 status_revert(struct status *status, enum line_type type, bool has_none)
6238 if (!status || type != LINE_STAT_UNSTAGED) {
6239 if (type == LINE_STAT_STAGED) {
6240 report("Cannot revert changes to staged files");
6241 } else if (type == LINE_STAT_UNTRACKED) {
6242 report("Cannot revert changes to untracked files");
6243 } else if (has_none) {
6244 report("Nothing to revert");
6245 } else {
6246 report("Cannot revert changes to multiple files");
6249 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6250 char mode[10] = "100644";
6251 const char *reset_argv[] = {
6252 "git", "update-index", "--cacheinfo", mode,
6253 status->old.rev, status->old.name, NULL
6255 const char *checkout_argv[] = {
6256 "git", "checkout", "--", status->old.name, NULL
6259 if (status->status == 'U') {
6260 string_format(mode, "%5o", status->old.mode);
6262 if (status->old.mode == 0 && status->new.mode == 0) {
6263 reset_argv[2] = "--force-remove";
6264 reset_argv[3] = status->old.name;
6265 reset_argv[4] = NULL;
6268 if (!io_run_fg(reset_argv, opt_cdup))
6269 return FALSE;
6270 if (status->old.mode == 0 && status->new.mode == 0)
6271 return TRUE;
6274 return io_run_fg(checkout_argv, opt_cdup);
6277 return FALSE;
6280 static enum request
6281 status_request(struct view *view, enum request request, struct line *line)
6283 struct status *status = line->data;
6285 switch (request) {
6286 case REQ_STATUS_UPDATE:
6287 if (!status_update(view))
6288 return REQ_NONE;
6289 break;
6291 case REQ_STATUS_REVERT:
6292 if (!status_revert(status, line->type, status_has_none(view, line)))
6293 return REQ_NONE;
6294 break;
6296 case REQ_STATUS_MERGE:
6297 if (!status || status->status != 'U') {
6298 report("Merging only possible for files with unmerged status ('U').");
6299 return REQ_NONE;
6301 open_mergetool(status->new.name);
6302 break;
6304 case REQ_EDIT:
6305 if (!status)
6306 return request;
6307 if (status->status == 'D') {
6308 report("File has been deleted.");
6309 return REQ_NONE;
6312 open_editor(status->new.name);
6313 break;
6315 case REQ_VIEW_BLAME:
6316 if (status)
6317 opt_ref[0] = 0;
6318 return request;
6320 case REQ_ENTER:
6321 /* After returning the status view has been split to
6322 * show the stage view. No further reloading is
6323 * necessary. */
6324 return status_enter(view, line);
6326 case REQ_REFRESH:
6327 /* Simply reload the view. */
6328 break;
6330 default:
6331 return request;
6334 refresh_view(view);
6336 return REQ_NONE;
6339 static void
6340 status_select(struct view *view, struct line *line)
6342 struct status *status = line->data;
6343 char file[SIZEOF_STR] = "all files";
6344 const char *text;
6345 const char *key;
6347 if (status && !string_format(file, "'%s'", status->new.name))
6348 return;
6350 if (!status && line[1].type == LINE_STAT_NONE)
6351 line++;
6353 switch (line->type) {
6354 case LINE_STAT_STAGED:
6355 text = "Press %s to unstage %s for commit";
6356 break;
6358 case LINE_STAT_UNSTAGED:
6359 text = "Press %s to stage %s for commit";
6360 break;
6362 case LINE_STAT_UNTRACKED:
6363 text = "Press %s to stage %s for addition";
6364 break;
6366 case LINE_STAT_HEAD:
6367 case LINE_STAT_NONE:
6368 text = "Nothing to update";
6369 break;
6371 default:
6372 die("line type %d not handled in switch", line->type);
6375 if (status && status->status == 'U') {
6376 text = "Press %s to resolve conflict in %s";
6377 key = get_view_key(view, REQ_STATUS_MERGE);
6379 } else {
6380 key = get_view_key(view, REQ_STATUS_UPDATE);
6383 string_format(view->ref, text, key, file);
6384 if (status)
6385 string_copy(opt_file, status->new.name);
6388 static bool
6389 status_grep(struct view *view, struct line *line)
6391 struct status *status = line->data;
6393 if (status) {
6394 const char buf[2] = { status->status, 0 };
6395 const char *text[] = { status->new.name, buf, NULL };
6397 return grep_text(view, text);
6400 return FALSE;
6403 static struct view_ops status_ops = {
6404 "file",
6405 { "status" },
6406 VIEW_CUSTOM_STATUS,
6408 status_open,
6409 NULL,
6410 status_draw,
6411 status_request,
6412 status_grep,
6413 status_select,
6417 struct stage_state {
6418 struct diff_state diff;
6419 size_t chunks;
6420 int *chunk;
6423 static bool
6424 stage_diff_write(struct io *io, struct line *line, struct line *end)
6426 while (line < end) {
6427 if (!io_write(io, line->data, strlen(line->data)) ||
6428 !io_write(io, "\n", 1))
6429 return FALSE;
6430 line++;
6431 if (line->type == LINE_DIFF_CHUNK ||
6432 line->type == LINE_DIFF_HEADER)
6433 break;
6436 return TRUE;
6439 static bool
6440 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6442 const char *apply_argv[SIZEOF_ARG] = {
6443 "git", "apply", "--whitespace=nowarn", NULL
6445 struct line *diff_hdr;
6446 struct io io;
6447 int argc = 3;
6449 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6450 if (!diff_hdr)
6451 return FALSE;
6453 if (!revert)
6454 apply_argv[argc++] = "--cached";
6455 if (line != NULL)
6456 apply_argv[argc++] = "--unidiff-zero";
6457 if (revert || stage_line_type == LINE_STAT_STAGED)
6458 apply_argv[argc++] = "-R";
6459 apply_argv[argc++] = "-";
6460 apply_argv[argc++] = NULL;
6461 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6462 return FALSE;
6464 if (line != NULL) {
6465 int lineno = 0;
6466 struct line *context = chunk + 1;
6467 const char *markers[] = {
6468 line->type == LINE_DIFF_DEL ? "" : ",0",
6469 line->type == LINE_DIFF_DEL ? ",0" : "",
6472 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6474 while (context < line) {
6475 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6476 break;
6477 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6478 lineno++;
6480 context++;
6483 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6484 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6485 lineno, markers[0], lineno, markers[1]) ||
6486 !stage_diff_write(&io, line, line + 1)) {
6487 chunk = NULL;
6489 } else {
6490 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6491 !stage_diff_write(&io, chunk, view->line + view->lines))
6492 chunk = NULL;
6495 io_done(&io);
6496 io_run_bg(update_index_argv);
6498 return chunk ? TRUE : FALSE;
6501 static bool
6502 stage_update(struct view *view, struct line *line, bool single)
6504 struct line *chunk = NULL;
6506 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6507 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6509 if (chunk) {
6510 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6511 report("Failed to apply chunk");
6512 return FALSE;
6515 } else if (!stage_status.status) {
6516 view = view->parent;
6518 for (line = view->line; view_has_line(view, line); line++)
6519 if (line->type == stage_line_type)
6520 break;
6522 if (!status_update_files(view, line + 1)) {
6523 report("Failed to update files");
6524 return FALSE;
6527 } else if (!status_update_file(&stage_status, stage_line_type)) {
6528 report("Failed to update file");
6529 return FALSE;
6532 return TRUE;
6535 static bool
6536 stage_revert(struct view *view, struct line *line)
6538 struct line *chunk = NULL;
6540 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6541 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6543 if (chunk) {
6544 if (!prompt_yesno("Are you sure you want to revert changes?"))
6545 return FALSE;
6547 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6548 report("Failed to revert chunk");
6549 return FALSE;
6551 return TRUE;
6553 } else {
6554 return status_revert(stage_status.status ? &stage_status : NULL,
6555 stage_line_type, FALSE);
6560 static void
6561 stage_next(struct view *view, struct line *line)
6563 struct stage_state *state = view->private;
6564 int i;
6566 if (!state->chunks) {
6567 for (line = view->line; view_has_line(view, line); line++) {
6568 if (line->type != LINE_DIFF_CHUNK)
6569 continue;
6571 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6572 report("Allocation failure");
6573 return;
6576 state->chunk[state->chunks++] = line - view->line;
6580 for (i = 0; i < state->chunks; i++) {
6581 if (state->chunk[i] > view->pos.lineno) {
6582 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6583 report("Chunk %d of %d", i + 1, state->chunks);
6584 return;
6588 report("No next chunk found");
6591 static enum request
6592 stage_request(struct view *view, enum request request, struct line *line)
6594 switch (request) {
6595 case REQ_STATUS_UPDATE:
6596 if (!stage_update(view, line, FALSE))
6597 return REQ_NONE;
6598 break;
6600 case REQ_STATUS_REVERT:
6601 if (!stage_revert(view, line))
6602 return REQ_NONE;
6603 break;
6605 case REQ_STAGE_UPDATE_LINE:
6606 if (stage_line_type == LINE_STAT_UNTRACKED ||
6607 stage_status.status == 'A') {
6608 report("Staging single lines is not supported for new files");
6609 return REQ_NONE;
6611 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6612 report("Please select a change to stage");
6613 return REQ_NONE;
6615 if (!stage_update(view, line, TRUE))
6616 return REQ_NONE;
6617 break;
6619 case REQ_STAGE_NEXT:
6620 if (stage_line_type == LINE_STAT_UNTRACKED) {
6621 report("File is untracked; press %s to add",
6622 get_view_key(view, REQ_STATUS_UPDATE));
6623 return REQ_NONE;
6625 stage_next(view, line);
6626 return REQ_NONE;
6628 case REQ_EDIT:
6629 if (!stage_status.new.name[0])
6630 return request;
6631 if (stage_status.status == 'D') {
6632 report("File has been deleted.");
6633 return REQ_NONE;
6636 open_editor(stage_status.new.name);
6637 break;
6639 case REQ_REFRESH:
6640 /* Reload everything ... */
6641 break;
6643 case REQ_VIEW_BLAME:
6644 if (stage_status.new.name[0]) {
6645 string_copy(opt_file, stage_status.new.name);
6646 opt_ref[0] = 0;
6648 return request;
6650 case REQ_ENTER:
6651 return diff_common_enter(view, request, line);
6653 case REQ_DIFF_CONTEXT_UP:
6654 case REQ_DIFF_CONTEXT_DOWN:
6655 if (!update_diff_context(request))
6656 return REQ_NONE;
6657 break;
6659 default:
6660 return request;
6663 refresh_view(view->parent);
6665 /* Check whether the staged entry still exists, and close the
6666 * stage view if it doesn't. */
6667 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6668 status_restore(view->parent);
6669 return REQ_VIEW_CLOSE;
6672 refresh_view(view);
6674 return REQ_NONE;
6677 static bool
6678 stage_open(struct view *view, enum open_flags flags)
6680 static const char *no_head_diff_argv[] = {
6681 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6682 stage_status.new.name)
6684 static const char *index_show_argv[] = {
6685 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6686 stage_status.old.name, stage_status.new.name)
6688 static const char *files_show_argv[] = {
6689 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6690 stage_status.old.name, stage_status.new.name)
6692 /* Diffs for unmerged entries are empty when passing the new
6693 * path, so leave out the new path. */
6694 static const char *files_unmerged_argv[] = {
6695 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6696 opt_diff_context_arg, opt_ignore_space_arg, "--",
6697 stage_status.old.name, NULL
6699 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6700 const char **argv = NULL;
6701 const char *info;
6703 if (!stage_line_type) {
6704 report("No stage content, press %s to open the status view and choose file",
6705 get_view_key(view, REQ_VIEW_STATUS));
6706 return FALSE;
6709 view->encoding = NULL;
6711 switch (stage_line_type) {
6712 case LINE_STAT_STAGED:
6713 if (is_initial_commit()) {
6714 argv = no_head_diff_argv;
6715 } else {
6716 argv = index_show_argv;
6718 if (stage_status.status)
6719 info = "Staged changes to %s";
6720 else
6721 info = "Staged changes";
6722 break;
6724 case LINE_STAT_UNSTAGED:
6725 if (stage_status.status != 'U')
6726 argv = files_show_argv;
6727 else
6728 argv = files_unmerged_argv;
6729 if (stage_status.status)
6730 info = "Unstaged changes to %s";
6731 else
6732 info = "Unstaged changes";
6733 break;
6735 case LINE_STAT_UNTRACKED:
6736 info = "Untracked file %s";
6737 argv = file_argv;
6738 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6739 break;
6741 case LINE_STAT_HEAD:
6742 default:
6743 die("line type %d not handled in switch", stage_line_type);
6746 if (!string_format(view->ref, info, stage_status.new.name)
6747 || !argv_copy(&view->argv, argv)) {
6748 report("Failed to open staged view");
6749 return FALSE;
6752 view->vid[0] = 0;
6753 view->dir = opt_cdup;
6754 return begin_update(view, NULL, NULL, flags);
6757 static bool
6758 stage_read(struct view *view, char *data)
6760 struct stage_state *state = view->private;
6762 if (data && diff_common_read(view, data, &state->diff))
6763 return TRUE;
6765 return pager_read(view, data);
6768 static struct view_ops stage_ops = {
6769 "line",
6770 { "stage" },
6771 VIEW_DIFF_LIKE,
6772 sizeof(struct stage_state),
6773 stage_open,
6774 stage_read,
6775 diff_common_draw,
6776 stage_request,
6777 pager_grep,
6778 pager_select,
6783 * Revision graph
6786 static const enum line_type graph_colors[] = {
6787 LINE_PALETTE_0,
6788 LINE_PALETTE_1,
6789 LINE_PALETTE_2,
6790 LINE_PALETTE_3,
6791 LINE_PALETTE_4,
6792 LINE_PALETTE_5,
6793 LINE_PALETTE_6,
6796 static enum line_type get_graph_color(struct graph_symbol *symbol)
6798 if (symbol->commit)
6799 return LINE_GRAPH_COMMIT;
6800 assert(symbol->color < ARRAY_SIZE(graph_colors));
6801 return graph_colors[symbol->color];
6804 static bool
6805 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6807 const char *chars = graph_symbol_to_utf8(symbol);
6809 return draw_text(view, color, chars + !!first);
6812 static bool
6813 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6815 const char *chars = graph_symbol_to_ascii(symbol);
6817 return draw_text(view, color, chars + !!first);
6820 static bool
6821 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6823 const chtype *chars = graph_symbol_to_chtype(symbol);
6825 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6828 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6830 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6832 static const draw_graph_fn fns[] = {
6833 draw_graph_ascii,
6834 draw_graph_chtype,
6835 draw_graph_utf8
6837 draw_graph_fn fn = fns[opt_line_graphics];
6838 int i;
6840 for (i = 0; i < canvas->size; i++) {
6841 struct graph_symbol *symbol = &canvas->symbols[i];
6842 enum line_type color = get_graph_color(symbol);
6844 if (fn(view, symbol, color, i == 0))
6845 return TRUE;
6848 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6852 * Main view backend
6855 struct commit {
6856 char id[SIZEOF_REV]; /* SHA1 ID. */
6857 char title[128]; /* First line of the commit message. */
6858 const char *author; /* Author of the commit. */
6859 struct time time; /* Date from the author ident. */
6860 struct ref_list *refs; /* Repository references. */
6861 struct graph_canvas graph; /* Ancestry chain graphics. */
6864 struct main_state {
6865 struct graph graph;
6866 struct commit *current;
6867 bool in_header;
6870 static struct commit *
6871 main_add_commit(struct view *view, enum line_type type, const char *ids,
6872 bool is_boundary, bool custom)
6874 struct main_state *state = view->private;
6875 struct commit *commit;
6877 if (!add_line_alloc(view, &commit, type, 0, custom))
6878 return NULL;
6880 string_copy_rev(commit->id, ids);
6881 commit->refs = get_ref_list(commit->id);
6882 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
6883 return commit;
6886 bool
6887 main_has_changes(const char *argv[])
6889 struct io io;
6891 if (!io_run(&io, IO_BG, NULL, argv, -1))
6892 return FALSE;
6893 io_done(&io);
6894 return io.status == 1;
6897 static void
6898 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6900 char ids[SIZEOF_STR] = NULL_ID " ";
6901 struct main_state *state = view->private;
6902 struct commit *commit;
6903 struct timeval now;
6904 struct timezone tz;
6906 if (!parent)
6907 return;
6909 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6911 commit = main_add_commit(view, type, ids, FALSE, TRUE);
6912 if (!commit)
6913 return;
6915 if (!gettimeofday(&now, &tz)) {
6916 commit->time.tz = tz.tz_minuteswest * 60;
6917 commit->time.sec = now.tv_sec - commit->time.tz;
6920 commit->author = "";
6921 string_ncopy(commit->title, title, strlen(title));
6922 graph_render_parents(&state->graph);
6925 static void
6926 main_add_changes_commits(struct view *view, const char *parent)
6928 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6929 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6930 const char *staged_parent = NULL_ID;
6931 const char *unstaged_parent = parent;
6933 io_run_bg(update_index_argv);
6935 if (!main_has_changes(unstaged_argv)) {
6936 unstaged_parent = NULL;
6937 staged_parent = parent;
6940 if (!main_has_changes(staged_argv)) {
6941 staged_parent = NULL;
6944 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6945 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6948 static bool
6949 main_open(struct view *view, enum open_flags flags)
6951 static const char *main_argv[] = {
6952 GIT_MAIN_LOG("%(diffargs)", "%(revargs)", "%(fileargs)")
6955 return begin_update(view, NULL, main_argv, flags);
6958 static bool
6959 main_draw(struct view *view, struct line *line, unsigned int lineno)
6961 struct commit *commit = line->data;
6963 if (!commit->author)
6964 return FALSE;
6966 if (draw_lineno(view, lineno))
6967 return TRUE;
6969 if (draw_date(view, &commit->time))
6970 return TRUE;
6972 if (draw_author(view, commit->author))
6973 return TRUE;
6975 if (opt_rev_graph && draw_graph(view, &commit->graph))
6976 return TRUE;
6978 if (draw_refs(view, commit->refs))
6979 return TRUE;
6981 draw_text(view, LINE_DEFAULT, commit->title);
6982 return TRUE;
6985 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6986 static bool
6987 main_read(struct view *view, char *line)
6989 struct main_state *state = view->private;
6990 struct graph *graph = &state->graph;
6991 enum line_type type;
6992 struct commit *commit = state->current;
6994 if (!line) {
6995 if (!view->lines && !view->prev)
6996 die("No revisions match the given arguments.");
6997 if (view->lines > 0) {
6998 commit = view->line[view->lines - 1].data;
6999 view->line[view->lines - 1].dirty = 1;
7000 if (!commit->author) {
7001 view->lines--;
7002 free(commit);
7006 done_graph(graph);
7007 return TRUE;
7010 type = get_line_type(line);
7011 if (type == LINE_COMMIT) {
7012 bool is_boundary;
7014 state->in_header = TRUE;
7015 line += STRING_SIZE("commit ");
7016 is_boundary = *line == '-';
7017 if (is_boundary || !isalnum(*line))
7018 line++;
7020 if (!view->lines && opt_show_changes && opt_is_inside_work_tree)
7021 main_add_changes_commits(view, line);
7023 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7024 return state->current != NULL;
7027 if (!view->lines || !commit)
7028 return TRUE;
7030 /* Empty line separates the commit header from the log itself. */
7031 if (*line == '\0')
7032 state->in_header = FALSE;
7034 switch (type) {
7035 case LINE_PARENT:
7036 if (!graph->has_parents)
7037 graph_add_parent(graph, line + STRING_SIZE("parent "));
7038 break;
7040 case LINE_AUTHOR:
7041 parse_author_line(line + STRING_SIZE("author "),
7042 &commit->author, &commit->time);
7043 graph_render_parents(graph);
7044 break;
7046 default:
7047 /* Fill in the commit title if it has not already been set. */
7048 if (commit->title[0])
7049 break;
7051 /* Skip lines in the commit header. */
7052 if (state->in_header)
7053 break;
7055 /* Require titles to start with a non-space character at the
7056 * offset used by git log. */
7057 if (strncmp(line, " ", 4))
7058 break;
7059 line += 4;
7060 /* Well, if the title starts with a whitespace character,
7061 * try to be forgiving. Otherwise we end up with no title. */
7062 while (isspace(*line))
7063 line++;
7064 if (*line == '\0')
7065 break;
7066 /* FIXME: More graceful handling of titles; append "..." to
7067 * shortened titles, etc. */
7069 string_expand(commit->title, sizeof(commit->title), line, 1);
7070 view->line[view->lines - 1].dirty = 1;
7073 return TRUE;
7076 static enum request
7077 main_request(struct view *view, enum request request, struct line *line)
7079 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7081 switch (request) {
7082 case REQ_NEXT:
7083 case REQ_PREVIOUS:
7084 if (view_is_displayed(view) && display[0] != view)
7085 return request;
7086 /* Do not pass navigation requests to the branch view
7087 * when the main view is maximized. (GH #38) */
7088 move_view(view, request);
7089 break;
7091 case REQ_ENTER:
7092 if (view_is_displayed(view) && display[0] != view)
7093 maximize_view(view, TRUE);
7095 if (line->type == LINE_STAT_UNSTAGED
7096 || line->type == LINE_STAT_STAGED) {
7097 struct view *diff = VIEW(REQ_VIEW_DIFF);
7098 const char *diff_staged_argv[] = {
7099 GIT_DIFF_STAGED(opt_diff_context_arg,
7100 opt_ignore_space_arg, NULL, NULL)
7102 const char *diff_unstaged_argv[] = {
7103 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
7104 opt_ignore_space_arg, NULL, NULL)
7106 const char **diff_argv = line->type == LINE_STAT_STAGED
7107 ? diff_staged_argv : diff_unstaged_argv;
7109 open_argv(view, diff, diff_argv, NULL, flags);
7110 break;
7113 open_view(view, REQ_VIEW_DIFF, flags);
7114 break;
7115 case REQ_REFRESH:
7116 load_refs();
7117 refresh_view(view);
7118 break;
7120 case REQ_JUMP_COMMIT:
7122 int lineno;
7124 for (lineno = 0; lineno < view->lines; lineno++) {
7125 struct commit *commit = view->line[lineno].data;
7127 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7128 select_view_line(view, lineno);
7129 report("");
7130 return REQ_NONE;
7134 report("Unable to find commit '%s'", opt_search);
7135 break;
7137 default:
7138 return request;
7141 return REQ_NONE;
7144 static bool
7145 grep_refs(struct ref_list *list, regex_t *regex)
7147 regmatch_t pmatch;
7148 size_t i;
7150 if (!opt_show_refs || !list)
7151 return FALSE;
7153 for (i = 0; i < list->size; i++) {
7154 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7155 return TRUE;
7158 return FALSE;
7161 static bool
7162 main_grep(struct view *view, struct line *line)
7164 struct commit *commit = line->data;
7165 const char *text[] = {
7166 commit->title,
7167 mkauthor(commit->author, opt_author_cols, opt_author),
7168 mkdate(&commit->time, opt_date),
7169 NULL
7172 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7175 static void
7176 main_select(struct view *view, struct line *line)
7178 struct commit *commit = line->data;
7180 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7181 string_copy(view->ref, commit->title);
7182 else
7183 string_copy_rev(view->ref, commit->id);
7184 string_copy_rev(ref_commit, commit->id);
7187 static struct view_ops main_ops = {
7188 "commit",
7189 { "main" },
7190 VIEW_NO_FLAGS,
7191 sizeof(struct main_state),
7192 main_open,
7193 main_read,
7194 main_draw,
7195 main_request,
7196 main_grep,
7197 main_select,
7202 * Status management
7205 /* Whether or not the curses interface has been initialized. */
7206 static bool cursed = FALSE;
7208 /* Terminal hacks and workarounds. */
7209 static bool use_scroll_redrawwin;
7210 static bool use_scroll_status_wclear;
7212 /* The status window is used for polling keystrokes. */
7213 static WINDOW *status_win;
7215 /* Reading from the prompt? */
7216 static bool input_mode = FALSE;
7218 static bool status_empty = FALSE;
7220 /* Update status and title window. */
7221 static void
7222 report(const char *msg, ...)
7224 struct view *view = display[current_view];
7226 if (input_mode)
7227 return;
7229 if (!view) {
7230 char buf[SIZEOF_STR];
7231 int retval;
7233 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7234 die("%s", buf);
7237 if (!status_empty || *msg) {
7238 va_list args;
7240 va_start(args, msg);
7242 wmove(status_win, 0, 0);
7243 if (view->has_scrolled && use_scroll_status_wclear)
7244 wclear(status_win);
7245 if (*msg) {
7246 vwprintw(status_win, msg, args);
7247 status_empty = FALSE;
7248 } else {
7249 status_empty = TRUE;
7251 wclrtoeol(status_win);
7252 wnoutrefresh(status_win);
7254 va_end(args);
7257 update_view_title(view);
7260 static void
7261 init_display(void)
7263 const char *term;
7264 int x, y;
7266 /* Initialize the curses library */
7267 if (isatty(STDIN_FILENO)) {
7268 cursed = !!initscr();
7269 opt_tty = stdin;
7270 } else {
7271 /* Leave stdin and stdout alone when acting as a pager. */
7272 opt_tty = fopen("/dev/tty", "r+");
7273 if (!opt_tty)
7274 die("Failed to open /dev/tty");
7275 cursed = !!newterm(NULL, opt_tty, opt_tty);
7278 if (!cursed)
7279 die("Failed to initialize curses");
7281 nonl(); /* Disable conversion and detect newlines from input. */
7282 cbreak(); /* Take input chars one at a time, no wait for \n */
7283 noecho(); /* Don't echo input */
7284 leaveok(stdscr, FALSE);
7286 if (has_colors())
7287 init_colors();
7289 getmaxyx(stdscr, y, x);
7290 status_win = newwin(1, x, y - 1, 0);
7291 if (!status_win)
7292 die("Failed to create status window");
7294 /* Enable keyboard mapping */
7295 keypad(status_win, TRUE);
7296 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7298 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7299 set_tabsize(opt_tab_size);
7300 #else
7301 TABSIZE = opt_tab_size;
7302 #endif
7304 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7305 if (term && !strcmp(term, "gnome-terminal")) {
7306 /* In the gnome-terminal-emulator, the message from
7307 * scrolling up one line when impossible followed by
7308 * scrolling down one line causes corruption of the
7309 * status line. This is fixed by calling wclear. */
7310 use_scroll_status_wclear = TRUE;
7311 use_scroll_redrawwin = FALSE;
7313 } else if (term && !strcmp(term, "xrvt-xpm")) {
7314 /* No problems with full optimizations in xrvt-(unicode)
7315 * and aterm. */
7316 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7318 } else {
7319 /* When scrolling in (u)xterm the last line in the
7320 * scrolling direction will update slowly. */
7321 use_scroll_redrawwin = TRUE;
7322 use_scroll_status_wclear = FALSE;
7326 static int
7327 get_input(int prompt_position)
7329 struct view *view;
7330 int i, key, cursor_y, cursor_x;
7332 if (prompt_position)
7333 input_mode = TRUE;
7335 while (TRUE) {
7336 bool loading = FALSE;
7338 foreach_view (view, i) {
7339 update_view(view);
7340 if (view_is_displayed(view) && view->has_scrolled &&
7341 use_scroll_redrawwin)
7342 redrawwin(view->win);
7343 view->has_scrolled = FALSE;
7344 if (view->pipe)
7345 loading = TRUE;
7348 /* Update the cursor position. */
7349 if (prompt_position) {
7350 getbegyx(status_win, cursor_y, cursor_x);
7351 cursor_x = prompt_position;
7352 } else {
7353 view = display[current_view];
7354 getbegyx(view->win, cursor_y, cursor_x);
7355 cursor_x = view->width - 1;
7356 cursor_y += view->pos.lineno - view->pos.offset;
7358 setsyx(cursor_y, cursor_x);
7360 /* Refresh, accept single keystroke of input */
7361 doupdate();
7362 nodelay(status_win, loading);
7363 key = wgetch(status_win);
7365 /* wgetch() with nodelay() enabled returns ERR when
7366 * there's no input. */
7367 if (key == ERR) {
7369 } else if (key == KEY_RESIZE) {
7370 int height, width;
7372 getmaxyx(stdscr, height, width);
7374 wresize(status_win, 1, width);
7375 mvwin(status_win, height - 1, 0);
7376 wnoutrefresh(status_win);
7377 resize_display();
7378 redraw_display(TRUE);
7380 } else {
7381 input_mode = FALSE;
7382 if (key == erasechar())
7383 key = KEY_BACKSPACE;
7384 return key;
7389 static char *
7390 prompt_input(const char *prompt, input_handler handler, void *data)
7392 enum input_status status = INPUT_OK;
7393 static char buf[SIZEOF_STR];
7394 size_t pos = 0;
7396 buf[pos] = 0;
7398 while (status == INPUT_OK || status == INPUT_SKIP) {
7399 int key;
7401 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7402 wclrtoeol(status_win);
7404 key = get_input(pos + 1);
7405 switch (key) {
7406 case KEY_RETURN:
7407 case KEY_ENTER:
7408 case '\n':
7409 status = pos ? INPUT_STOP : INPUT_CANCEL;
7410 break;
7412 case KEY_BACKSPACE:
7413 if (pos > 0)
7414 buf[--pos] = 0;
7415 else
7416 status = INPUT_CANCEL;
7417 break;
7419 case KEY_ESC:
7420 status = INPUT_CANCEL;
7421 break;
7423 default:
7424 if (pos >= sizeof(buf)) {
7425 report("Input string too long");
7426 return NULL;
7429 status = handler(data, buf, key);
7430 if (status == INPUT_OK)
7431 buf[pos++] = (char) key;
7435 /* Clear the status window */
7436 status_empty = FALSE;
7437 report("");
7439 if (status == INPUT_CANCEL)
7440 return NULL;
7442 buf[pos++] = 0;
7444 return buf;
7447 static enum input_status
7448 prompt_yesno_handler(void *data, char *buf, int c)
7450 if (c == 'y' || c == 'Y')
7451 return INPUT_STOP;
7452 if (c == 'n' || c == 'N')
7453 return INPUT_CANCEL;
7454 return INPUT_SKIP;
7457 static bool
7458 prompt_yesno(const char *prompt)
7460 char prompt2[SIZEOF_STR];
7462 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7463 return FALSE;
7465 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7468 static enum input_status
7469 read_prompt_handler(void *data, char *buf, int c)
7471 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7474 static char *
7475 read_prompt(const char *prompt)
7477 return prompt_input(prompt, read_prompt_handler, NULL);
7480 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7482 enum input_status status = INPUT_OK;
7483 int size = 0;
7485 while (items[size].text)
7486 size++;
7488 assert(size > 0);
7490 while (status == INPUT_OK) {
7491 const struct menu_item *item = &items[*selected];
7492 int key;
7493 int i;
7495 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7496 prompt, *selected + 1, size);
7497 if (item->hotkey)
7498 wprintw(status_win, "[%c] ", (char) item->hotkey);
7499 wprintw(status_win, "%s", item->text);
7500 wclrtoeol(status_win);
7502 key = get_input(COLS - 1);
7503 switch (key) {
7504 case KEY_RETURN:
7505 case KEY_ENTER:
7506 case '\n':
7507 status = INPUT_STOP;
7508 break;
7510 case KEY_LEFT:
7511 case KEY_UP:
7512 *selected = *selected - 1;
7513 if (*selected < 0)
7514 *selected = size - 1;
7515 break;
7517 case KEY_RIGHT:
7518 case KEY_DOWN:
7519 *selected = (*selected + 1) % size;
7520 break;
7522 case KEY_ESC:
7523 status = INPUT_CANCEL;
7524 break;
7526 default:
7527 for (i = 0; items[i].text; i++)
7528 if (items[i].hotkey == key) {
7529 *selected = i;
7530 status = INPUT_STOP;
7531 break;
7536 /* Clear the status window */
7537 status_empty = FALSE;
7538 report("");
7540 return status != INPUT_CANCEL;
7544 * Repository properties
7548 static void
7549 set_remote_branch(const char *name, const char *value, size_t valuelen)
7551 if (!strcmp(name, ".remote")) {
7552 string_ncopy(opt_remote, value, valuelen);
7554 } else if (*opt_remote && !strcmp(name, ".merge")) {
7555 size_t from = strlen(opt_remote);
7557 if (!prefixcmp(value, "refs/heads/"))
7558 value += STRING_SIZE("refs/heads/");
7560 if (!string_format_from(opt_remote, &from, "/%s", value))
7561 opt_remote[0] = 0;
7565 static void
7566 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7568 const char *argv[SIZEOF_ARG] = { name, "=" };
7569 int argc = 1 + (cmd == option_set_command);
7570 enum option_code error;
7572 if (!argv_from_string(argv, &argc, value))
7573 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7574 else
7575 error = cmd(argc, argv);
7577 if (error != OPT_OK)
7578 warn("Option 'tig.%s': %s", name, option_errors[error]);
7581 static bool
7582 set_environment_variable(const char *name, const char *value)
7584 size_t len = strlen(name) + 1 + strlen(value) + 1;
7585 char *env = malloc(len);
7587 if (env &&
7588 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7589 putenv(env) == 0)
7590 return TRUE;
7591 free(env);
7592 return FALSE;
7595 static void
7596 set_work_tree(const char *value)
7598 char cwd[SIZEOF_STR];
7600 if (!getcwd(cwd, sizeof(cwd)))
7601 die("Failed to get cwd path: %s", strerror(errno));
7602 if (chdir(opt_git_dir) < 0)
7603 die("Failed to chdir(%s): %s", strerror(errno));
7604 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7605 die("Failed to get git path: %s", strerror(errno));
7606 if (chdir(cwd) < 0)
7607 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7608 if (chdir(value) < 0)
7609 die("Failed to chdir(%s): %s", value, strerror(errno));
7610 if (!getcwd(cwd, sizeof(cwd)))
7611 die("Failed to get cwd path: %s", strerror(errno));
7612 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7613 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7614 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7615 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7616 opt_is_inside_work_tree = TRUE;
7619 static void
7620 parse_git_color_option(enum line_type type, char *value)
7622 struct line_info *info = &line_info[type];
7623 const char *argv[SIZEOF_ARG];
7624 int argc = 0;
7625 bool first_color = TRUE;
7626 int i;
7628 if (!argv_from_string(argv, &argc, value))
7629 return;
7631 info->fg = COLOR_DEFAULT;
7632 info->bg = COLOR_DEFAULT;
7633 info->attr = 0;
7635 for (i = 0; i < argc; i++) {
7636 int attr = 0;
7638 if (set_attribute(&attr, argv[i])) {
7639 info->attr |= attr;
7641 } else if (set_color(&attr, argv[i])) {
7642 if (first_color)
7643 info->fg = attr;
7644 else
7645 info->bg = attr;
7646 first_color = FALSE;
7651 static void
7652 set_git_color_option(const char *name, char *value)
7654 static const struct enum_map color_option_map[] = {
7655 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7656 ENUM_MAP("branch.local", LINE_MAIN_REF),
7657 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7658 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7660 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7661 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7662 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7663 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7664 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7665 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7666 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7668 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7670 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7671 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7672 ENUM_MAP("status.added", LINE_STAT_STAGED),
7673 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7674 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7675 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7678 int type = LINE_NONE;
7680 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7681 parse_git_color_option(type, value);
7685 static int
7686 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7688 if (!strcmp(name, "gui.encoding"))
7689 parse_encoding(&opt_encoding, value, TRUE);
7691 else if (!strcmp(name, "core.editor"))
7692 string_ncopy(opt_editor, value, valuelen);
7694 else if (!strcmp(name, "core.worktree"))
7695 set_work_tree(value);
7697 else if (!prefixcmp(name, "tig.color."))
7698 set_repo_config_option(name + 10, value, option_color_command);
7700 else if (!prefixcmp(name, "tig.bind."))
7701 set_repo_config_option(name + 9, value, option_bind_command);
7703 else if (!prefixcmp(name, "tig."))
7704 set_repo_config_option(name + 4, value, option_set_command);
7706 else if (!prefixcmp(name, "color."))
7707 set_git_color_option(name + STRING_SIZE("color."), value);
7709 else if (*opt_head && !prefixcmp(name, "branch.") &&
7710 !strncmp(name + 7, opt_head, strlen(opt_head)))
7711 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7713 return OK;
7716 static int
7717 load_git_config(void)
7719 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7721 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7724 static int
7725 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7727 if (!opt_git_dir[0]) {
7728 string_ncopy(opt_git_dir, name, namelen);
7730 } else if (opt_is_inside_work_tree == -1) {
7731 /* This can be 3 different values depending on the
7732 * version of git being used. If git-rev-parse does not
7733 * understand --is-inside-work-tree it will simply echo
7734 * the option else either "true" or "false" is printed.
7735 * Default to true for the unknown case. */
7736 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7738 } else if (*name == '.') {
7739 string_ncopy(opt_cdup, name, namelen);
7741 } else {
7742 string_ncopy(opt_prefix, name, namelen);
7745 return OK;
7748 static int
7749 load_repo_info(void)
7751 const char *rev_parse_argv[] = {
7752 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7753 "--show-cdup", "--show-prefix", NULL
7756 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7761 * Main
7764 static const char usage[] =
7765 "tig " TIG_VERSION " (" __DATE__ ")\n"
7766 "\n"
7767 "Usage: tig [options] [revs] [--] [paths]\n"
7768 " or: tig show [options] [revs] [--] [paths]\n"
7769 " or: tig blame [options] [rev] [--] path\n"
7770 " or: tig status\n"
7771 " or: tig < [git command output]\n"
7772 "\n"
7773 "Options:\n"
7774 " +<number> Select line <number> in the first view\n"
7775 " -v, --version Show version and exit\n"
7776 " -h, --help Show help message and exit";
7778 static void __NORETURN
7779 quit(int sig)
7781 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7782 if (cursed)
7783 endwin();
7784 exit(0);
7787 static void __NORETURN
7788 die(const char *err, ...)
7790 va_list args;
7792 endwin();
7794 va_start(args, err);
7795 fputs("tig: ", stderr);
7796 vfprintf(stderr, err, args);
7797 fputs("\n", stderr);
7798 va_end(args);
7800 exit(1);
7803 static void
7804 warn(const char *msg, ...)
7806 va_list args;
7808 va_start(args, msg);
7809 fputs("tig warning: ", stderr);
7810 vfprintf(stderr, msg, args);
7811 fputs("\n", stderr);
7812 va_end(args);
7815 static int
7816 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7818 const char ***filter_args = data;
7820 return argv_append(filter_args, name) ? OK : ERR;
7823 static void
7824 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7826 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7827 const char **all_argv = NULL;
7829 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7830 !argv_append_array(&all_argv, argv) ||
7831 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7832 die("Failed to split arguments");
7833 argv_free(all_argv);
7834 free(all_argv);
7837 static void
7838 filter_options(const char *argv[], bool blame)
7840 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7842 if (blame)
7843 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7844 else
7845 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7847 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7850 static enum request
7851 parse_options(int argc, const char *argv[])
7853 enum request request = REQ_VIEW_MAIN;
7854 const char *subcommand;
7855 bool seen_dashdash = FALSE;
7856 const char **filter_argv = NULL;
7857 int i;
7859 if (!isatty(STDIN_FILENO))
7860 return REQ_VIEW_PAGER;
7862 if (argc <= 1)
7863 return REQ_VIEW_MAIN;
7865 subcommand = argv[1];
7866 if (!strcmp(subcommand, "status")) {
7867 if (argc > 2)
7868 warn("ignoring arguments after `%s'", subcommand);
7869 return REQ_VIEW_STATUS;
7871 } else if (!strcmp(subcommand, "blame")) {
7872 request = REQ_VIEW_BLAME;
7874 } else if (!strcmp(subcommand, "show")) {
7875 request = REQ_VIEW_DIFF;
7877 } else {
7878 subcommand = NULL;
7881 for (i = 1 + !!subcommand; i < argc; i++) {
7882 const char *opt = argv[i];
7884 // stop parsing our options after -- and let rev-parse handle the rest
7885 if (!seen_dashdash) {
7886 if (!strcmp(opt, "--")) {
7887 seen_dashdash = TRUE;
7888 continue;
7890 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7891 printf("tig version %s\n", TIG_VERSION);
7892 quit(0);
7894 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7895 printf("%s\n", usage);
7896 quit(0);
7898 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7899 opt_lineno = atoi(opt + 1);
7900 continue;
7905 if (!argv_append(&filter_argv, opt))
7906 die("command too long");
7909 if (filter_argv)
7910 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7912 /* Finish validating and setting up blame options */
7913 if (request == REQ_VIEW_BLAME) {
7914 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7915 die("invalid number of options to blame\n\n%s", usage);
7917 if (opt_rev_argv) {
7918 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7921 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7924 return request;
7928 main(int argc, const char *argv[])
7930 const char *codeset = ENCODING_UTF8;
7931 enum request request = parse_options(argc, argv);
7932 struct view *view;
7933 int i;
7935 signal(SIGINT, quit);
7936 signal(SIGPIPE, SIG_IGN);
7938 if (setlocale(LC_ALL, "")) {
7939 codeset = nl_langinfo(CODESET);
7942 foreach_view(view, i) {
7943 add_keymap(&view->ops->keymap);
7946 if (load_repo_info() == ERR)
7947 die("Failed to load repo info.");
7949 if (load_options() == ERR)
7950 die("Failed to load user config.");
7952 if (load_git_config() == ERR)
7953 die("Failed to load repo config.");
7955 /* Require a git repository unless when running in pager mode. */
7956 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7957 die("Not a git repository");
7959 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7960 char translit[SIZEOF_STR];
7962 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7963 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7964 else
7965 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7966 if (opt_iconv_out == ICONV_NONE)
7967 die("Failed to initialize character set conversion");
7970 if (load_refs() == ERR)
7971 die("Failed to load refs.");
7973 init_display();
7975 while (view_driver(display[current_view], request)) {
7976 int key = get_input(0);
7978 view = display[current_view];
7979 request = get_keybinding(&view->ops->keymap, key);
7981 /* Some low-level request handling. This keeps access to
7982 * status_win restricted. */
7983 switch (request) {
7984 case REQ_NONE:
7985 report("Unknown key, press %s for help",
7986 get_view_key(view, REQ_VIEW_HELP));
7987 break;
7988 case REQ_PROMPT:
7990 char *cmd = read_prompt(":");
7992 if (cmd && string_isnumber(cmd)) {
7993 int lineno = view->pos.lineno + 1;
7995 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7996 select_view_line(view, lineno - 1);
7997 report("");
7998 } else {
7999 report("Unable to parse '%s' as a line number", cmd);
8001 } else if (cmd && iscommit(cmd)) {
8002 string_ncopy(opt_search, cmd, strlen(cmd));
8004 request = view_request(view, REQ_JUMP_COMMIT);
8005 if (request == REQ_JUMP_COMMIT) {
8006 report("Jumping to commits is not supported by the '%s' view", view->name);
8009 } else if (cmd) {
8010 struct view *next = VIEW(REQ_VIEW_PAGER);
8011 const char *argv[SIZEOF_ARG] = { "git" };
8012 int argc = 1;
8014 /* When running random commands, initially show the
8015 * command in the title. However, it maybe later be
8016 * overwritten if a commit line is selected. */
8017 string_ncopy(next->ref, cmd, strlen(cmd));
8019 if (!argv_from_string(argv, &argc, cmd)) {
8020 report("Too many arguments");
8021 } else if (!format_argv(&next->argv, argv, FALSE)) {
8022 report("Argument formatting failed");
8023 } else {
8024 next->dir = NULL;
8025 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8029 request = REQ_NONE;
8030 break;
8032 case REQ_SEARCH:
8033 case REQ_SEARCH_BACK:
8035 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8036 char *search = read_prompt(prompt);
8038 if (search)
8039 string_ncopy(opt_search, search, strlen(search));
8040 else if (*opt_search)
8041 request = request == REQ_SEARCH ?
8042 REQ_FIND_NEXT :
8043 REQ_FIND_PREV;
8044 else
8045 request = REQ_NONE;
8046 break;
8048 default:
8049 break;
8053 quit(0);
8055 return 0;