[GH #53] Revert 73bee5e which breaks the graph when path spec is specified
[tig.git] / tig.c
blob3b26ba1a14ff2f6ce36860c0168d985eef0c93e3
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 int opt_diff_context = 3;
404 static char opt_diff_context_arg[9] = "";
405 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
406 static char opt_ignore_space_arg[22] = "";
407 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
408 static char opt_commit_order_arg[22] = "";
409 static bool opt_notes = TRUE;
410 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
411 static int opt_num_interval = 5;
412 static double opt_hscroll = 0.50;
413 static double opt_scale_split_view = 2.0 / 3.0;
414 static int opt_tab_size = 8;
415 static int opt_author_cols = AUTHOR_COLS;
416 static int opt_filename_cols = FILENAME_COLS;
417 static char opt_path[SIZEOF_STR] = "";
418 static char opt_file[SIZEOF_STR] = "";
419 static char opt_ref[SIZEOF_REF] = "";
420 static unsigned long opt_goto_line = 0;
421 static char opt_head[SIZEOF_REF] = "";
422 static char opt_remote[SIZEOF_REF] = "";
423 static struct encoding *opt_encoding = NULL;
424 static iconv_t opt_iconv_out = ICONV_NONE;
425 static char opt_search[SIZEOF_STR] = "";
426 static char opt_cdup[SIZEOF_STR] = "";
427 static char opt_prefix[SIZEOF_STR] = "";
428 static char opt_git_dir[SIZEOF_STR] = "";
429 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
430 static char opt_editor[SIZEOF_STR] = "";
431 static FILE *opt_tty = NULL;
432 static const char **opt_diff_argv = NULL;
433 static const char **opt_rev_argv = NULL;
434 static const char **opt_file_argv = NULL;
435 static const char **opt_blame_argv = NULL;
436 static int opt_lineno = 0;
438 #define is_initial_commit() (!get_ref_head())
439 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
440 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
442 static inline void
443 update_diff_context_arg(int diff_context)
445 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
446 string_ncopy(opt_diff_context_arg, "-U3", 3);
449 static inline void
450 update_ignore_space_arg()
452 if (opt_ignore_space == IGNORE_SPACE_ALL) {
453 string_copy(opt_ignore_space_arg, "--ignore-all-space");
454 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
455 string_copy(opt_ignore_space_arg, "--ignore-space-change");
456 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
457 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
458 } else {
459 string_copy(opt_ignore_space_arg, "");
463 static inline void
464 update_commit_order_arg()
466 if (opt_commit_order == COMMIT_ORDER_TOPO) {
467 string_copy(opt_commit_order_arg, "--topo-order");
468 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
469 string_copy(opt_commit_order_arg, "--date-order");
470 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
471 string_copy(opt_commit_order_arg, "--reverse");
472 } else {
473 string_copy(opt_commit_order_arg, "");
477 static inline void
478 update_notes_arg()
480 if (opt_notes) {
481 string_copy(opt_notes_arg, "--show-notes");
482 } else {
483 /* Notes are disabled by default when passing --pretty args. */
484 string_copy(opt_notes_arg, "");
489 * Line-oriented content detection.
492 #define LINE_INFO \
493 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
494 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
495 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
496 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
497 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
498 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
499 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
500 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
506 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
507 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
508 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
509 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
510 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
511 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
512 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
515 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
516 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
517 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
518 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
519 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
520 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
521 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
526 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
527 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
528 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
529 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
530 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
531 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
532 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
533 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
534 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
535 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
536 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
537 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
538 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
539 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
540 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
541 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
542 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
543 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
544 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
545 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
546 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
547 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
548 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
549 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
550 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
551 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
553 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
554 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
555 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
556 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
557 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
558 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
559 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
560 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
561 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
562 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
563 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
564 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
566 enum line_type {
567 #define LINE(type, line, fg, bg, attr) \
568 LINE_##type
569 LINE_INFO,
570 LINE_NONE
571 #undef LINE
574 struct line_info {
575 const char *name; /* Option name. */
576 int namelen; /* Size of option name. */
577 const char *line; /* The start of line to match. */
578 int linelen; /* Size of string to match. */
579 int fg, bg, attr; /* Color and text attributes for the lines. */
580 int color_pair;
583 static struct line_info line_info[] = {
584 #define LINE(type, line, fg, bg, attr) \
585 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
586 LINE_INFO
587 #undef LINE
590 static struct line_info **color_pair;
591 static size_t color_pairs;
593 static struct line_info *custom_color;
594 static size_t custom_colors;
596 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
597 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
599 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
600 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
602 /* Color IDs must be 1 or higher. [GH #15] */
603 #define COLOR_ID(line_type) ((line_type) + 1)
605 static enum line_type
606 get_line_type(const char *line)
608 int linelen = strlen(line);
609 enum line_type type;
611 for (type = 0; type < custom_colors; type++)
612 /* Case insensitive search matches Signed-off-by lines better. */
613 if (linelen >= custom_color[type].linelen &&
614 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
615 return TO_CUSTOM_COLOR_TYPE(type);
617 for (type = 0; type < ARRAY_SIZE(line_info); type++)
618 /* Case insensitive search matches Signed-off-by lines better. */
619 if (linelen >= line_info[type].linelen &&
620 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
621 return type;
623 return LINE_DEFAULT;
626 static enum line_type
627 get_line_type_from_ref(const struct ref *ref)
629 if (ref->head)
630 return LINE_MAIN_HEAD;
631 else if (ref->ltag)
632 return LINE_MAIN_LOCAL_TAG;
633 else if (ref->tag)
634 return LINE_MAIN_TAG;
635 else if (ref->tracked)
636 return LINE_MAIN_TRACKED;
637 else if (ref->remote)
638 return LINE_MAIN_REMOTE;
639 else if (ref->replace)
640 return LINE_MAIN_REPLACE;
642 return LINE_MAIN_REF;
645 static inline struct line_info *
646 get_line(enum line_type type)
648 if (type > LINE_NONE) {
649 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
650 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
651 } else {
652 assert(type < ARRAY_SIZE(line_info));
653 return &line_info[type];
657 static inline int
658 get_line_color(enum line_type type)
660 return COLOR_ID(get_line(type)->color_pair);
663 static inline int
664 get_line_attr(enum line_type type)
666 struct line_info *info = get_line(type);
668 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
671 static struct line_info *
672 get_line_info(const char *name)
674 size_t namelen = strlen(name);
675 enum line_type type;
677 for (type = 0; type < ARRAY_SIZE(line_info); type++)
678 if (enum_equals(line_info[type], name, namelen))
679 return &line_info[type];
681 return NULL;
684 static struct line_info *
685 add_custom_color(const char *quoted_line)
687 struct line_info *info;
688 char *line;
689 size_t linelen;
691 if (!realloc_custom_color(&custom_color, custom_colors, 1))
692 die("Failed to alloc custom line info");
694 linelen = strlen(quoted_line) - 1;
695 line = malloc(linelen);
696 if (!line)
697 return NULL;
699 strncpy(line, quoted_line + 1, linelen);
700 line[linelen - 1] = 0;
702 info = &custom_color[custom_colors++];
703 info->name = info->line = line;
704 info->namelen = info->linelen = strlen(line);
706 return info;
709 static void
710 init_line_info_color_pair(struct line_info *info, enum line_type type,
711 int default_bg, int default_fg)
713 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
714 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
715 int i;
717 for (i = 0; i < color_pairs; i++) {
718 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
719 info->color_pair = i;
720 return;
724 if (!realloc_color_pair(&color_pair, color_pairs, 1))
725 die("Failed to alloc color pair");
727 color_pair[color_pairs] = info;
728 info->color_pair = color_pairs++;
729 init_pair(COLOR_ID(info->color_pair), fg, bg);
732 static void
733 init_colors(void)
735 int default_bg = line_info[LINE_DEFAULT].bg;
736 int default_fg = line_info[LINE_DEFAULT].fg;
737 enum line_type type;
739 start_color();
741 if (assume_default_colors(default_fg, default_bg) == ERR) {
742 default_bg = COLOR_BLACK;
743 default_fg = COLOR_WHITE;
746 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
747 struct line_info *info = &line_info[type];
749 init_line_info_color_pair(info, type, default_bg, default_fg);
752 for (type = 0; type < custom_colors; type++) {
753 struct line_info *info = &custom_color[type];
755 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
756 default_bg, default_fg);
760 struct line {
761 enum line_type type;
763 /* State flags */
764 unsigned int selected:1;
765 unsigned int dirty:1;
766 unsigned int cleareol:1;
767 unsigned int dont_free:1;
768 unsigned int other:16;
770 void *data; /* User data */
775 * Keys
778 struct keybinding {
779 int alias;
780 enum request request;
783 static struct keybinding default_keybindings[] = {
784 /* View switching */
785 { 'm', REQ_VIEW_MAIN },
786 { 'd', REQ_VIEW_DIFF },
787 { 'l', REQ_VIEW_LOG },
788 { 't', REQ_VIEW_TREE },
789 { 'f', REQ_VIEW_BLOB },
790 { 'B', REQ_VIEW_BLAME },
791 { 'H', REQ_VIEW_BRANCH },
792 { 'p', REQ_VIEW_PAGER },
793 { 'h', REQ_VIEW_HELP },
794 { 'S', REQ_VIEW_STATUS },
795 { 'c', REQ_VIEW_STAGE },
797 /* View manipulation */
798 { 'q', REQ_VIEW_CLOSE },
799 { KEY_TAB, REQ_VIEW_NEXT },
800 { KEY_RETURN, REQ_ENTER },
801 { KEY_UP, REQ_PREVIOUS },
802 { KEY_CTL('P'), REQ_PREVIOUS },
803 { KEY_DOWN, REQ_NEXT },
804 { KEY_CTL('N'), REQ_NEXT },
805 { 'R', REQ_REFRESH },
806 { KEY_F(5), REQ_REFRESH },
807 { 'O', REQ_MAXIMIZE },
808 { ',', REQ_PARENT },
810 /* View specific */
811 { 'u', REQ_STATUS_UPDATE },
812 { '!', REQ_STATUS_REVERT },
813 { 'M', REQ_STATUS_MERGE },
814 { '1', REQ_STAGE_UPDATE_LINE },
815 { '@', REQ_STAGE_NEXT },
816 { '[', REQ_DIFF_CONTEXT_DOWN },
817 { ']', REQ_DIFF_CONTEXT_UP },
819 /* Cursor navigation */
820 { 'k', REQ_MOVE_UP },
821 { 'j', REQ_MOVE_DOWN },
822 { KEY_HOME, REQ_MOVE_FIRST_LINE },
823 { KEY_END, REQ_MOVE_LAST_LINE },
824 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
825 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
826 { ' ', REQ_MOVE_PAGE_DOWN },
827 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
828 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
829 { 'b', REQ_MOVE_PAGE_UP },
830 { '-', REQ_MOVE_PAGE_UP },
832 /* Scrolling */
833 { '|', REQ_SCROLL_FIRST_COL },
834 { KEY_LEFT, REQ_SCROLL_LEFT },
835 { KEY_RIGHT, REQ_SCROLL_RIGHT },
836 { KEY_IC, REQ_SCROLL_LINE_UP },
837 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
838 { KEY_DC, REQ_SCROLL_LINE_DOWN },
839 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
840 { 'w', REQ_SCROLL_PAGE_UP },
841 { 's', REQ_SCROLL_PAGE_DOWN },
843 /* Searching */
844 { '/', REQ_SEARCH },
845 { '?', REQ_SEARCH_BACK },
846 { 'n', REQ_FIND_NEXT },
847 { 'N', REQ_FIND_PREV },
849 /* Misc */
850 { 'Q', REQ_QUIT },
851 { 'z', REQ_STOP_LOADING },
852 { 'v', REQ_SHOW_VERSION },
853 { 'r', REQ_SCREEN_REDRAW },
854 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
855 { 'o', REQ_OPTIONS },
856 { '.', REQ_TOGGLE_LINENO },
857 { 'D', REQ_TOGGLE_DATE },
858 { 'A', REQ_TOGGLE_AUTHOR },
859 { 'g', REQ_TOGGLE_REV_GRAPH },
860 { '~', REQ_TOGGLE_GRAPHIC },
861 { '#', REQ_TOGGLE_FILENAME },
862 { 'F', REQ_TOGGLE_REFS },
863 { 'I', REQ_TOGGLE_SORT_ORDER },
864 { 'i', REQ_TOGGLE_SORT_FIELD },
865 { 'W', REQ_TOGGLE_IGNORE_SPACE },
866 { ':', REQ_PROMPT },
867 { 'e', REQ_EDIT },
870 struct keymap {
871 const char *name;
872 struct keymap *next;
873 struct keybinding *data;
874 size_t size;
875 bool hidden;
878 static struct keymap generic_keymap = { "generic" };
879 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
881 static struct keymap *keymaps = &generic_keymap;
883 static void
884 add_keymap(struct keymap *keymap)
886 keymap->next = keymaps;
887 keymaps = keymap;
890 static struct keymap *
891 get_keymap(const char *name)
893 struct keymap *keymap = keymaps;
895 while (keymap) {
896 if (!strcasecmp(keymap->name, name))
897 return keymap;
898 keymap = keymap->next;
901 return NULL;
905 static void
906 add_keybinding(struct keymap *table, enum request request, int key)
908 size_t i;
910 for (i = 0; i < table->size; i++) {
911 if (table->data[i].alias == key) {
912 table->data[i].request = request;
913 return;
917 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
918 if (!table->data)
919 die("Failed to allocate keybinding");
920 table->data[table->size].alias = key;
921 table->data[table->size++].request = request;
923 if (request == REQ_NONE && is_generic_keymap(table)) {
924 int i;
926 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
927 if (default_keybindings[i].alias == key)
928 default_keybindings[i].request = REQ_NONE;
932 /* Looks for a key binding first in the given map, then in the generic map, and
933 * lastly in the default keybindings. */
934 static enum request
935 get_keybinding(struct keymap *keymap, int key)
937 size_t i;
939 for (i = 0; i < keymap->size; i++)
940 if (keymap->data[i].alias == key)
941 return keymap->data[i].request;
943 for (i = 0; i < generic_keymap.size; i++)
944 if (generic_keymap.data[i].alias == key)
945 return generic_keymap.data[i].request;
947 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
948 if (default_keybindings[i].alias == key)
949 return default_keybindings[i].request;
951 return (enum request) key;
955 struct key {
956 const char *name;
957 int value;
960 static const struct key key_table[] = {
961 { "Enter", KEY_RETURN },
962 { "Space", ' ' },
963 { "Backspace", KEY_BACKSPACE },
964 { "Tab", KEY_TAB },
965 { "Escape", KEY_ESC },
966 { "Left", KEY_LEFT },
967 { "Right", KEY_RIGHT },
968 { "Up", KEY_UP },
969 { "Down", KEY_DOWN },
970 { "Insert", KEY_IC },
971 { "Delete", KEY_DC },
972 { "Hash", '#' },
973 { "Home", KEY_HOME },
974 { "End", KEY_END },
975 { "PageUp", KEY_PPAGE },
976 { "PageDown", KEY_NPAGE },
977 { "F1", KEY_F(1) },
978 { "F2", KEY_F(2) },
979 { "F3", KEY_F(3) },
980 { "F4", KEY_F(4) },
981 { "F5", KEY_F(5) },
982 { "F6", KEY_F(6) },
983 { "F7", KEY_F(7) },
984 { "F8", KEY_F(8) },
985 { "F9", KEY_F(9) },
986 { "F10", KEY_F(10) },
987 { "F11", KEY_F(11) },
988 { "F12", KEY_F(12) },
991 static int
992 get_key_value(const char *name)
994 int i;
996 for (i = 0; i < ARRAY_SIZE(key_table); i++)
997 if (!strcasecmp(key_table[i].name, name))
998 return key_table[i].value;
1000 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1001 return (int)name[1] & 0x1f;
1002 if (strlen(name) == 1 && isprint(*name))
1003 return (int) *name;
1004 return ERR;
1007 static const char *
1008 get_key_name(int key_value)
1010 static char key_char[] = "'X'\0";
1011 const char *seq = NULL;
1012 int key;
1014 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1015 if (key_table[key].value == key_value)
1016 seq = key_table[key].name;
1018 if (seq == NULL && key_value < 0x7f) {
1019 char *s = key_char + 1;
1021 if (key_value >= 0x20) {
1022 *s++ = key_value;
1023 } else {
1024 *s++ = '^';
1025 *s++ = 0x40 | (key_value & 0x1f);
1027 *s++ = '\'';
1028 *s++ = '\0';
1029 seq = key_char;
1032 return seq ? seq : "(no key)";
1035 static bool
1036 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1038 const char *sep = *pos > 0 ? ", " : "";
1039 const char *keyname = get_key_name(keybinding->alias);
1041 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1044 static bool
1045 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1046 struct keymap *keymap, bool all)
1048 int i;
1050 for (i = 0; i < keymap->size; i++) {
1051 if (keymap->data[i].request == request) {
1052 if (!append_key(buf, pos, &keymap->data[i]))
1053 return FALSE;
1054 if (!all)
1055 break;
1059 return TRUE;
1062 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1064 static const char *
1065 get_keys(struct keymap *keymap, enum request request, bool all)
1067 static char buf[BUFSIZ];
1068 size_t pos = 0;
1069 int i;
1071 buf[pos] = 0;
1073 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1074 return "Too many keybindings!";
1075 if (pos > 0 && !all)
1076 return buf;
1078 if (!is_generic_keymap(keymap)) {
1079 /* Only the generic keymap includes the default keybindings when
1080 * listing all keys. */
1081 if (all)
1082 return buf;
1084 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1085 return "Too many keybindings!";
1086 if (pos)
1087 return buf;
1090 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1091 if (default_keybindings[i].request == request) {
1092 if (!append_key(buf, &pos, &default_keybindings[i]))
1093 return "Too many keybindings!";
1094 if (!all)
1095 return buf;
1099 return buf;
1102 enum run_request_flag {
1103 RUN_REQUEST_DEFAULT = 0,
1104 RUN_REQUEST_FORCE = 1,
1105 RUN_REQUEST_SILENT = 2,
1106 RUN_REQUEST_CONFIRM = 4,
1109 struct run_request {
1110 struct keymap *keymap;
1111 int key;
1112 const char **argv;
1113 bool silent;
1114 bool confirm;
1117 static struct run_request *run_request;
1118 static size_t run_requests;
1120 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1122 static bool
1123 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1125 bool force = flags & RUN_REQUEST_FORCE;
1126 struct run_request *req;
1128 if (!force && get_keybinding(keymap, key) != key)
1129 return TRUE;
1131 if (!realloc_run_requests(&run_request, run_requests, 1))
1132 return FALSE;
1134 if (!argv_copy(&run_request[run_requests].argv, argv))
1135 return FALSE;
1137 req = &run_request[run_requests++];
1138 req->silent = flags & RUN_REQUEST_SILENT;
1139 req->confirm = flags & RUN_REQUEST_CONFIRM;
1140 req->keymap = keymap;
1141 req->key = key;
1143 add_keybinding(keymap, REQ_NONE + run_requests, key);
1144 return TRUE;
1147 static struct run_request *
1148 get_run_request(enum request request)
1150 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1151 return NULL;
1152 return &run_request[request - REQ_NONE - 1];
1155 static void
1156 add_builtin_run_requests(void)
1158 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1159 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1160 const char *commit[] = { "git", "commit", NULL };
1161 const char *gc[] = { "git", "gc", NULL };
1163 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1164 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1165 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1166 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1170 * User config file handling.
1173 #define OPT_ERR_INFO \
1174 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1175 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1176 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1177 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1178 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1179 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1180 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1181 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1182 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1183 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1184 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1185 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1186 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1187 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1188 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1189 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1190 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1191 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1192 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1194 enum option_code {
1195 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1196 OPT_ERR_INFO
1197 #undef OPT_ERR_
1198 OPT_OK
1201 static const char *option_errors[] = {
1202 #define OPT_ERR_(name, msg) msg
1203 OPT_ERR_INFO
1204 #undef OPT_ERR_
1207 static const struct enum_map color_map[] = {
1208 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1209 COLOR_MAP(DEFAULT),
1210 COLOR_MAP(BLACK),
1211 COLOR_MAP(BLUE),
1212 COLOR_MAP(CYAN),
1213 COLOR_MAP(GREEN),
1214 COLOR_MAP(MAGENTA),
1215 COLOR_MAP(RED),
1216 COLOR_MAP(WHITE),
1217 COLOR_MAP(YELLOW),
1220 static const struct enum_map attr_map[] = {
1221 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1222 ATTR_MAP(NORMAL),
1223 ATTR_MAP(BLINK),
1224 ATTR_MAP(BOLD),
1225 ATTR_MAP(DIM),
1226 ATTR_MAP(REVERSE),
1227 ATTR_MAP(STANDOUT),
1228 ATTR_MAP(UNDERLINE),
1231 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1233 static enum option_code
1234 parse_step(double *opt, const char *arg)
1236 *opt = atoi(arg);
1237 if (!strchr(arg, '%'))
1238 return OPT_OK;
1240 /* "Shift down" so 100% and 1 does not conflict. */
1241 *opt = (*opt - 1) / 100;
1242 if (*opt >= 1.0) {
1243 *opt = 0.99;
1244 return OPT_ERR_INVALID_STEP_VALUE;
1246 if (*opt < 0.0) {
1247 *opt = 1;
1248 return OPT_ERR_INVALID_STEP_VALUE;
1250 return OPT_OK;
1253 static enum option_code
1254 parse_int(int *opt, const char *arg, int min, int max)
1256 int value = atoi(arg);
1258 if (min <= value && value <= max) {
1259 *opt = value;
1260 return OPT_OK;
1263 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1266 static bool
1267 set_color(int *color, const char *name)
1269 if (map_enum(color, color_map, name))
1270 return TRUE;
1271 if (!prefixcmp(name, "color"))
1272 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1273 return FALSE;
1276 /* Wants: object fgcolor bgcolor [attribute] */
1277 static enum option_code
1278 option_color_command(int argc, const char *argv[])
1280 struct line_info *info;
1282 if (argc < 3)
1283 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1285 if (*argv[0] == '"' || *argv[0] == '\'') {
1286 info = add_custom_color(argv[0]);
1287 } else {
1288 info = get_line_info(argv[0]);
1290 if (!info) {
1291 static const struct enum_map obsolete[] = {
1292 ENUM_MAP("main-delim", LINE_DELIMITER),
1293 ENUM_MAP("main-date", LINE_DATE),
1294 ENUM_MAP("main-author", LINE_AUTHOR),
1296 int index;
1298 if (!map_enum(&index, obsolete, argv[0]))
1299 return OPT_ERR_UNKNOWN_COLOR_NAME;
1300 info = &line_info[index];
1303 if (!set_color(&info->fg, argv[1]) ||
1304 !set_color(&info->bg, argv[2]))
1305 return OPT_ERR_UNKNOWN_COLOR;
1307 info->attr = 0;
1308 while (argc-- > 3) {
1309 int attr;
1311 if (!set_attribute(&attr, argv[argc]))
1312 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1313 info->attr |= attr;
1316 return OPT_OK;
1319 static enum option_code
1320 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1322 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1323 ? TRUE : FALSE;
1324 if (matched)
1325 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1326 return OPT_OK;
1329 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1331 static enum option_code
1332 parse_enum_do(unsigned int *opt, const char *arg,
1333 const struct enum_map *map, size_t map_size)
1335 bool is_true;
1337 assert(map_size > 1);
1339 if (map_enum_do(map, map_size, (int *) opt, arg))
1340 return OPT_OK;
1342 parse_bool(&is_true, arg);
1343 *opt = is_true ? map[1].value : map[0].value;
1344 return OPT_OK;
1347 #define parse_enum(opt, arg, map) \
1348 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1350 static enum option_code
1351 parse_string(char *opt, const char *arg, size_t optsize)
1353 int arglen = strlen(arg);
1355 switch (arg[0]) {
1356 case '\"':
1357 case '\'':
1358 if (arglen == 1 || arg[arglen - 1] != arg[0])
1359 return OPT_ERR_UNMATCHED_QUOTATION;
1360 arg += 1; arglen -= 2;
1361 default:
1362 string_ncopy_do(opt, optsize, arg, arglen);
1363 return OPT_OK;
1367 static enum option_code
1368 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1370 char buf[SIZEOF_STR];
1371 enum option_code code = parse_string(buf, arg, sizeof(buf));
1373 if (code == OPT_OK) {
1374 struct encoding *encoding = *encoding_ref;
1376 if (encoding && !priority)
1377 return code;
1378 encoding = encoding_open(buf);
1379 if (encoding)
1380 *encoding_ref = encoding;
1383 return code;
1386 static enum option_code
1387 parse_args(const char ***args, const char *argv[])
1389 if (*args == NULL && !argv_copy(args, argv))
1390 return OPT_ERR_OUT_OF_MEMORY;
1391 return OPT_OK;
1394 /* Wants: name = value */
1395 static enum option_code
1396 option_set_command(int argc, const char *argv[])
1398 if (argc < 3)
1399 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1401 if (strcmp(argv[1], "="))
1402 return OPT_ERR_NO_VALUE_ASSIGNED;
1404 if (!strcmp(argv[0], "blame-options"))
1405 return parse_args(&opt_blame_argv, argv + 2);
1407 if (argc != 3)
1408 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1410 if (!strcmp(argv[0], "show-author"))
1411 return parse_enum(&opt_author, argv[2], author_map);
1413 if (!strcmp(argv[0], "show-date"))
1414 return parse_enum(&opt_date, argv[2], date_map);
1416 if (!strcmp(argv[0], "show-rev-graph"))
1417 return parse_bool(&opt_rev_graph, argv[2]);
1419 if (!strcmp(argv[0], "show-refs"))
1420 return parse_bool(&opt_show_refs, argv[2]);
1422 if (!strcmp(argv[0], "show-changes"))
1423 return parse_bool(&opt_show_changes, argv[2]);
1425 if (!strcmp(argv[0], "show-notes")) {
1426 bool matched = FALSE;
1427 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1429 if (res == OPT_OK && matched) {
1430 update_notes_arg();
1431 return res;
1434 opt_notes = TRUE;
1435 strcpy(opt_notes_arg, "--show-notes=");
1436 res = parse_string(opt_notes_arg + 8, argv[2],
1437 sizeof(opt_notes_arg) - 8);
1438 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1439 opt_notes_arg[7] = '\0';
1440 return res;
1443 if (!strcmp(argv[0], "show-line-numbers"))
1444 return parse_bool(&opt_line_number, argv[2]);
1446 if (!strcmp(argv[0], "line-graphics"))
1447 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1449 if (!strcmp(argv[0], "line-number-interval"))
1450 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1452 if (!strcmp(argv[0], "author-width"))
1453 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1455 if (!strcmp(argv[0], "filename-width"))
1456 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1458 if (!strcmp(argv[0], "show-filename"))
1459 return parse_enum(&opt_filename, argv[2], filename_map);
1461 if (!strcmp(argv[0], "horizontal-scroll"))
1462 return parse_step(&opt_hscroll, argv[2]);
1464 if (!strcmp(argv[0], "split-view-height"))
1465 return parse_step(&opt_scale_split_view, argv[2]);
1467 if (!strcmp(argv[0], "tab-size"))
1468 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1470 if (!strcmp(argv[0], "diff-context")) {
1471 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1473 if (code == OPT_OK)
1474 update_diff_context_arg(opt_diff_context);
1475 return code;
1478 if (!strcmp(argv[0], "ignore-space")) {
1479 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1481 if (code == OPT_OK)
1482 update_ignore_space_arg();
1483 return code;
1486 if (!strcmp(argv[0], "commit-order")) {
1487 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1489 if (code == OPT_OK)
1490 update_commit_order_arg();
1491 return code;
1494 if (!strcmp(argv[0], "status-untracked-dirs"))
1495 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1497 if (!strcmp(argv[0], "use-git-colors"))
1498 return parse_bool(&opt_read_git_colors, argv[2]);
1500 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1503 /* Wants: mode request key */
1504 static enum option_code
1505 option_bind_command(int argc, const char *argv[])
1507 enum request request;
1508 struct keymap *keymap;
1509 int key;
1511 if (argc < 3)
1512 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1514 if (!(keymap = get_keymap(argv[0])))
1515 return OPT_ERR_UNKNOWN_KEY_MAP;
1517 key = get_key_value(argv[1]);
1518 if (key == ERR)
1519 return OPT_ERR_UNKNOWN_KEY;
1521 request = get_request(argv[2]);
1522 if (request == REQ_UNKNOWN) {
1523 static const struct enum_map obsolete[] = {
1524 ENUM_MAP("cherry-pick", REQ_NONE),
1525 ENUM_MAP("screen-resize", REQ_NONE),
1526 ENUM_MAP("tree-parent", REQ_PARENT),
1528 int alias;
1530 if (map_enum(&alias, obsolete, argv[2])) {
1531 if (alias != REQ_NONE)
1532 add_keybinding(keymap, alias, key);
1533 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1536 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1537 enum run_request_flag flags = RUN_REQUEST_FORCE;
1539 while (*argv[2]) {
1540 if (*argv[2] == '@') {
1541 flags |= RUN_REQUEST_SILENT;
1542 } else if (*argv[2] == '?') {
1543 flags |= RUN_REQUEST_CONFIRM;
1544 } else {
1545 break;
1547 argv[2]++;
1550 return add_run_request(keymap, key, argv + 2, flags)
1551 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1553 if (request == REQ_UNKNOWN)
1554 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1556 add_keybinding(keymap, request, key);
1558 return OPT_OK;
1562 static enum option_code load_option_file(const char *path);
1564 static enum option_code
1565 option_source_command(int argc, const char *argv[])
1567 if (argc < 1)
1568 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1570 return load_option_file(argv[0]);
1573 static enum option_code
1574 set_option(const char *opt, char *value)
1576 const char *argv[SIZEOF_ARG];
1577 int argc = 0;
1579 if (!argv_from_string(argv, &argc, value))
1580 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1582 if (!strcmp(opt, "color"))
1583 return option_color_command(argc, argv);
1585 if (!strcmp(opt, "set"))
1586 return option_set_command(argc, argv);
1588 if (!strcmp(opt, "bind"))
1589 return option_bind_command(argc, argv);
1591 if (!strcmp(opt, "source"))
1592 return option_source_command(argc, argv);
1594 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1597 struct config_state {
1598 const char *path;
1599 int lineno;
1600 bool errors;
1603 static int
1604 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1606 struct config_state *config = data;
1607 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1609 config->lineno++;
1611 /* Check for comment markers, since read_properties() will
1612 * only ensure opt and value are split at first " \t". */
1613 optlen = strcspn(opt, "#");
1614 if (optlen == 0)
1615 return OK;
1617 if (opt[optlen] == 0) {
1618 /* Look for comment endings in the value. */
1619 size_t len = strcspn(value, "#");
1621 if (len < valuelen) {
1622 valuelen = len;
1623 value[valuelen] = 0;
1626 status = set_option(opt, value);
1629 if (status != OPT_OK) {
1630 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1631 option_errors[status], (int) optlen, opt);
1632 config->errors = TRUE;
1635 /* Always keep going if errors are encountered. */
1636 return OK;
1639 static enum option_code
1640 load_option_file(const char *path)
1642 struct config_state config = { path, 0, FALSE };
1643 struct io io;
1645 /* Do not read configuration from stdin if set to "" */
1646 if (!path || !strlen(path))
1647 return OPT_OK;
1649 /* It's OK that the file doesn't exist. */
1650 if (!io_open(&io, "%s", path))
1651 return OPT_ERR_FILE_DOES_NOT_EXIST;
1653 if (io_load(&io, " \t", read_option, &config) == ERR ||
1654 config.errors == TRUE)
1655 warn("Errors while loading %s.", path);
1656 return OPT_OK;
1659 static int
1660 load_options(void)
1662 const char *home = getenv("HOME");
1663 const char *tigrc_user = getenv("TIGRC_USER");
1664 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1665 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1666 char buf[SIZEOF_STR];
1668 if (!tigrc_system)
1669 tigrc_system = SYSCONFDIR "/tigrc";
1670 load_option_file(tigrc_system);
1672 if (!tigrc_user) {
1673 if (!home || !string_format(buf, "%s/.tigrc", home))
1674 return ERR;
1675 tigrc_user = buf;
1677 load_option_file(tigrc_user);
1679 /* Add _after_ loading config files to avoid adding run requests
1680 * that conflict with keybindings. */
1681 add_builtin_run_requests();
1683 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1684 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1685 int argc = 0;
1687 if (!string_format(buf, "%s", tig_diff_opts) ||
1688 !argv_from_string(diff_opts, &argc, buf))
1689 die("TIG_DIFF_OPTS contains too many arguments");
1690 else if (!argv_copy(&opt_diff_argv, diff_opts))
1691 die("Failed to format TIG_DIFF_OPTS arguments");
1694 return OK;
1699 * The viewer
1702 struct view;
1703 struct view_ops;
1705 /* The display array of active views and the index of the current view. */
1706 static struct view *display[2];
1707 static WINDOW *display_win[2];
1708 static WINDOW *display_title[2];
1709 static unsigned int current_view;
1711 #define foreach_displayed_view(view, i) \
1712 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1714 #define displayed_views() (display[1] != NULL ? 2 : 1)
1716 /* Current head and commit ID */
1717 static char ref_blob[SIZEOF_REF] = "";
1718 static char ref_commit[SIZEOF_REF] = "HEAD";
1719 static char ref_head[SIZEOF_REF] = "HEAD";
1720 static char ref_branch[SIZEOF_REF] = "";
1722 enum view_flag {
1723 VIEW_NO_FLAGS = 0,
1724 VIEW_ALWAYS_LINENO = 1 << 0,
1725 VIEW_CUSTOM_STATUS = 1 << 1,
1726 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1727 VIEW_ADD_PAGER_REFS = 1 << 3,
1728 VIEW_OPEN_DIFF = 1 << 4,
1729 VIEW_NO_REF = 1 << 5,
1730 VIEW_NO_GIT_DIR = 1 << 6,
1731 VIEW_DIFF_LIKE = 1 << 7,
1734 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1736 struct position {
1737 unsigned long offset; /* Offset of the window top */
1738 unsigned long col; /* Offset from the window side. */
1739 unsigned long lineno; /* Current line number */
1742 struct view {
1743 const char *name; /* View name */
1744 const char *id; /* Points to either of ref_{head,commit,blob} */
1746 struct view_ops *ops; /* View operations */
1748 char ref[SIZEOF_REF]; /* Hovered commit reference */
1749 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1751 int height, width; /* The width and height of the main window */
1752 WINDOW *win; /* The main window */
1754 /* Navigation */
1755 struct position pos; /* Current position. */
1756 struct position prev_pos; /* Previous position. */
1758 /* Searching */
1759 char grep[SIZEOF_STR]; /* Search string */
1760 regex_t *regex; /* Pre-compiled regexp */
1762 /* If non-NULL, points to the view that opened this view. If this view
1763 * is closed tig will switch back to the parent view. */
1764 struct view *parent;
1765 struct view *prev;
1767 /* Buffering */
1768 size_t lines; /* Total number of lines */
1769 struct line *line; /* Line index */
1770 unsigned int digits; /* Number of digits in the lines member. */
1771 unsigned int lineoffset;/* Offset from where to count line objects. */
1773 /* Drawing */
1774 struct line *curline; /* Line currently being drawn. */
1775 enum line_type curtype; /* Attribute currently used for drawing. */
1776 unsigned long col; /* Column when drawing. */
1777 bool has_scrolled; /* View was scrolled. */
1779 /* Loading */
1780 const char **argv; /* Shell command arguments. */
1781 const char *dir; /* Directory from which to execute. */
1782 struct io io;
1783 struct io *pipe;
1784 time_t start_time;
1785 time_t update_secs;
1786 struct encoding *encoding;
1788 /* Private data */
1789 void *private;
1792 enum open_flags {
1793 OPEN_DEFAULT = 0, /* Use default view switching. */
1794 OPEN_SPLIT = 1, /* Split current view. */
1795 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1796 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1797 OPEN_PREPARED = 32, /* Open already prepared command. */
1798 OPEN_EXTRA = 64, /* Open extra data from command. */
1801 struct view_ops {
1802 /* What type of content being displayed. Used in the title bar. */
1803 const char *type;
1804 /* What keymap does this view have */
1805 struct keymap keymap;
1806 /* Flags to control the view behavior. */
1807 enum view_flag flags;
1808 /* Size of private data. */
1809 size_t private_size;
1810 /* Open and reads in all view content. */
1811 bool (*open)(struct view *view, enum open_flags flags);
1812 /* Read one line; updates view->line. */
1813 bool (*read)(struct view *view, char *data);
1814 /* Draw one line; @lineno must be < view->height. */
1815 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1816 /* Depending on view handle a special requests. */
1817 enum request (*request)(struct view *view, enum request request, struct line *line);
1818 /* Search for regexp in a line. */
1819 bool (*grep)(struct view *view, struct line *line);
1820 /* Select line */
1821 void (*select)(struct view *view, struct line *line);
1824 #define VIEW_OPS(id, name, ref) name##_ops
1825 static struct view_ops VIEW_INFO(VIEW_OPS);
1827 static struct view views[] = {
1828 #define VIEW_DATA(id, name, ref) \
1829 { #name, ref, &name##_ops }
1830 VIEW_INFO(VIEW_DATA)
1833 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1835 #define foreach_view(view, i) \
1836 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1838 #define view_is_displayed(view) \
1839 (view == display[0] || view == display[1])
1841 #define view_has_line(view, line_) \
1842 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1844 static enum request
1845 view_request(struct view *view, enum request request)
1847 if (!view || !view->lines)
1848 return request;
1849 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1853 * View drawing.
1856 static inline void
1857 set_view_attr(struct view *view, enum line_type type)
1859 if (!view->curline->selected && view->curtype != type) {
1860 (void) wattrset(view->win, get_line_attr(type));
1861 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1862 view->curtype = type;
1866 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1868 static bool
1869 draw_chars(struct view *view, enum line_type type, const char *string,
1870 int max_len, bool use_tilde)
1872 static char out_buffer[BUFSIZ * 2];
1873 int len = 0;
1874 int col = 0;
1875 int trimmed = FALSE;
1876 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1878 if (max_len <= 0)
1879 return VIEW_MAX_LEN(view) <= 0;
1881 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1883 set_view_attr(view, type);
1884 if (len > 0) {
1885 if (opt_iconv_out != ICONV_NONE) {
1886 size_t inlen = len + 1;
1887 char *instr = calloc(1, inlen);
1888 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1889 if (!instr)
1890 return VIEW_MAX_LEN(view) <= 0;
1892 strncpy(instr, string, len);
1894 char *outbuf = out_buffer;
1895 size_t outlen = sizeof(out_buffer);
1897 size_t ret;
1899 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1900 if (ret != (size_t) -1) {
1901 string = out_buffer;
1902 len = sizeof(out_buffer) - outlen;
1904 free(instr);
1907 waddnstr(view->win, string, len);
1909 if (trimmed && use_tilde) {
1910 set_view_attr(view, LINE_DELIMITER);
1911 waddch(view->win, '~');
1912 col++;
1916 view->col += col;
1917 return VIEW_MAX_LEN(view) <= 0;
1920 static bool
1921 draw_space(struct view *view, enum line_type type, int max, int spaces)
1923 static char space[] = " ";
1925 spaces = MIN(max, spaces);
1927 while (spaces > 0) {
1928 int len = MIN(spaces, sizeof(space) - 1);
1930 if (draw_chars(view, type, space, len, FALSE))
1931 return TRUE;
1932 spaces -= len;
1935 return VIEW_MAX_LEN(view) <= 0;
1938 static bool
1939 draw_text(struct view *view, enum line_type type, const char *string)
1941 static char text[SIZEOF_STR];
1943 do {
1944 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1946 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1947 return TRUE;
1948 string += pos;
1949 } while (*string);
1951 return VIEW_MAX_LEN(view) <= 0;
1954 static bool
1955 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1957 char text[SIZEOF_STR];
1958 int retval;
1960 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1961 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1964 static bool
1965 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1967 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1968 int max = VIEW_MAX_LEN(view);
1969 int i;
1971 if (max < size)
1972 size = max;
1974 set_view_attr(view, type);
1975 /* Using waddch() instead of waddnstr() ensures that
1976 * they'll be rendered correctly for the cursor line. */
1977 for (i = skip; i < size; i++)
1978 waddch(view->win, graphic[i]);
1980 view->col += size;
1981 if (separator) {
1982 if (size < max && skip <= size)
1983 waddch(view->win, ' ');
1984 view->col++;
1987 return VIEW_MAX_LEN(view) <= 0;
1990 static bool
1991 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1993 int max = MIN(VIEW_MAX_LEN(view), len);
1994 int col = view->col;
1996 if (!text)
1997 return draw_space(view, type, max, max);
1999 return draw_chars(view, type, text, max - 1, trim)
2000 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2003 static bool
2004 draw_date(struct view *view, struct time *time)
2006 const char *date = mkdate(time, opt_date);
2007 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
2009 if (opt_date == DATE_NO)
2010 return FALSE;
2012 return draw_field(view, LINE_DATE, date, cols, FALSE);
2015 static bool
2016 draw_author(struct view *view, const char *author)
2018 bool trim = author_trim(opt_author_cols);
2019 const char *text = mkauthor(author, opt_author_cols, opt_author);
2021 if (opt_author == AUTHOR_NO)
2022 return FALSE;
2024 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2027 static bool
2028 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2030 bool trim = filename && strlen(filename) >= opt_filename_cols;
2032 if (opt_filename == FILENAME_NO)
2033 return FALSE;
2035 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2036 return FALSE;
2038 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2041 static bool
2042 draw_mode(struct view *view, mode_t mode)
2044 const char *str = mkmode(mode);
2046 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2049 static bool
2050 draw_lineno(struct view *view, unsigned int lineno)
2052 char number[10];
2053 int digits3 = view->digits < 3 ? 3 : view->digits;
2054 int max = MIN(VIEW_MAX_LEN(view), digits3);
2055 char *text = NULL;
2056 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2058 if (!opt_line_number)
2059 return FALSE;
2061 lineno += view->pos.offset + 1;
2062 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2063 static char fmt[] = "%1ld";
2065 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2066 if (string_format(number, fmt, lineno))
2067 text = number;
2069 if (text)
2070 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2071 else
2072 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2073 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2076 static bool
2077 draw_refs(struct view *view, struct ref_list *refs)
2079 size_t i;
2081 if (!opt_show_refs || !refs)
2082 return FALSE;
2084 for (i = 0; i < refs->size; i++) {
2085 struct ref *ref = refs->refs[i];
2086 enum line_type type = get_line_type_from_ref(ref);
2088 if (draw_formatted(view, type, "[%s]", ref->name))
2089 return TRUE;
2091 if (draw_text(view, LINE_DEFAULT, " "))
2092 return TRUE;
2095 return FALSE;
2098 static bool
2099 draw_view_line(struct view *view, unsigned int lineno)
2101 struct line *line;
2102 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2104 assert(view_is_displayed(view));
2106 if (view->pos.offset + lineno >= view->lines)
2107 return FALSE;
2109 line = &view->line[view->pos.offset + lineno];
2111 wmove(view->win, lineno, 0);
2112 if (line->cleareol)
2113 wclrtoeol(view->win);
2114 view->col = 0;
2115 view->curline = line;
2116 view->curtype = LINE_NONE;
2117 line->selected = FALSE;
2118 line->dirty = line->cleareol = 0;
2120 if (selected) {
2121 set_view_attr(view, LINE_CURSOR);
2122 line->selected = TRUE;
2123 view->ops->select(view, line);
2126 return view->ops->draw(view, line, lineno);
2129 static void
2130 redraw_view_dirty(struct view *view)
2132 bool dirty = FALSE;
2133 int lineno;
2135 for (lineno = 0; lineno < view->height; lineno++) {
2136 if (view->pos.offset + lineno >= view->lines)
2137 break;
2138 if (!view->line[view->pos.offset + lineno].dirty)
2139 continue;
2140 dirty = TRUE;
2141 if (!draw_view_line(view, lineno))
2142 break;
2145 if (!dirty)
2146 return;
2147 wnoutrefresh(view->win);
2150 static void
2151 redraw_view_from(struct view *view, int lineno)
2153 assert(0 <= lineno && lineno < view->height);
2155 for (; lineno < view->height; lineno++) {
2156 if (!draw_view_line(view, lineno))
2157 break;
2160 wnoutrefresh(view->win);
2163 static void
2164 redraw_view(struct view *view)
2166 werase(view->win);
2167 redraw_view_from(view, 0);
2171 static void
2172 update_view_title(struct view *view)
2174 char buf[SIZEOF_STR];
2175 char state[SIZEOF_STR];
2176 size_t bufpos = 0, statelen = 0;
2177 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2179 assert(view_is_displayed(view));
2181 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines &&
2182 view->pos.lineno >= view->lineoffset) {
2183 unsigned int view_lines = view->pos.offset + view->height;
2184 unsigned int lines = view->lines
2185 ? MIN(view_lines, view->lines) * 100 / view->lines
2186 : 0;
2188 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2189 view->ops->type,
2190 view->pos.lineno + 1 - view->lineoffset,
2191 view->lines - view->lineoffset,
2192 lines);
2196 if (view->pipe) {
2197 time_t secs = time(NULL) - view->start_time;
2199 /* Three git seconds are a long time ... */
2200 if (secs > 2)
2201 string_format_from(state, &statelen, " loading %lds", secs);
2204 string_format_from(buf, &bufpos, "[%s]", view->name);
2205 if (*view->ref && bufpos < view->width) {
2206 size_t refsize = strlen(view->ref);
2207 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2209 if (minsize < view->width)
2210 refsize = view->width - minsize + 7;
2211 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2214 if (statelen && bufpos < view->width) {
2215 string_format_from(buf, &bufpos, "%s", state);
2218 if (view == display[current_view])
2219 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2220 else
2221 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2223 mvwaddnstr(window, 0, 0, buf, bufpos);
2224 wclrtoeol(window);
2225 wnoutrefresh(window);
2228 static int
2229 apply_step(double step, int value)
2231 if (step >= 1)
2232 return (int) step;
2233 value *= step + 0.01;
2234 return value ? value : 1;
2237 static void
2238 resize_display(void)
2240 int offset, i;
2241 struct view *base = display[0];
2242 struct view *view = display[1] ? display[1] : display[0];
2244 /* Setup window dimensions */
2246 getmaxyx(stdscr, base->height, base->width);
2248 /* Make room for the status window. */
2249 base->height -= 1;
2251 if (view != base) {
2252 /* Horizontal split. */
2253 view->width = base->width;
2254 view->height = apply_step(opt_scale_split_view, base->height);
2255 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2256 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2257 base->height -= view->height;
2259 /* Make room for the title bar. */
2260 view->height -= 1;
2263 /* Make room for the title bar. */
2264 base->height -= 1;
2266 offset = 0;
2268 foreach_displayed_view (view, i) {
2269 if (!display_win[i]) {
2270 display_win[i] = newwin(view->height, view->width, offset, 0);
2271 if (!display_win[i])
2272 die("Failed to create %s view", view->name);
2274 scrollok(display_win[i], FALSE);
2276 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2277 if (!display_title[i])
2278 die("Failed to create title window");
2280 } else {
2281 wresize(display_win[i], view->height, view->width);
2282 mvwin(display_win[i], offset, 0);
2283 mvwin(display_title[i], offset + view->height, 0);
2286 view->win = display_win[i];
2288 offset += view->height + 1;
2292 static void
2293 redraw_display(bool clear)
2295 struct view *view;
2296 int i;
2298 foreach_displayed_view (view, i) {
2299 if (clear)
2300 wclear(view->win);
2301 redraw_view(view);
2302 update_view_title(view);
2308 * Option management
2311 #define TOGGLE_MENU \
2312 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2313 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2314 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2315 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2316 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2317 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2318 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2319 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2320 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2321 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2323 static bool
2324 toggle_option(enum request request)
2326 const struct {
2327 enum request request;
2328 const struct enum_map *map;
2329 size_t map_size;
2330 } data[] = {
2331 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2332 TOGGLE_MENU
2333 #undef TOGGLE_
2335 const struct menu_item menu[] = {
2336 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2337 TOGGLE_MENU
2338 #undef TOGGLE_
2339 { 0 }
2341 int i = 0;
2343 if (request == REQ_OPTIONS) {
2344 if (!prompt_menu("Toggle option", menu, &i))
2345 return FALSE;
2346 } else {
2347 while (i < ARRAY_SIZE(data) && data[i].request != request)
2348 i++;
2349 if (i >= ARRAY_SIZE(data))
2350 die("Invalid request (%d)", request);
2353 if (data[i].map != NULL) {
2354 unsigned int *opt = menu[i].data;
2356 *opt = (*opt + 1) % data[i].map_size;
2357 if (data[i].map == ignore_space_map) {
2358 update_ignore_space_arg();
2359 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2360 return TRUE;
2362 } else if (data[i].map == commit_order_map) {
2363 update_commit_order_arg();
2364 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2365 return TRUE;
2368 redraw_display(FALSE);
2369 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2371 } else {
2372 bool *option = menu[i].data;
2374 *option = !*option;
2375 redraw_display(FALSE);
2376 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2379 return FALSE;
2384 * Navigation
2387 static bool
2388 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2390 if (lineno >= view->lines)
2391 lineno = view->lines > 0 ? view->lines - 1 : 0;
2393 if (offset > lineno || offset + view->height <= lineno) {
2394 unsigned long half = view->height / 2;
2396 if (lineno > half)
2397 offset = lineno - half;
2398 else
2399 offset = 0;
2402 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2403 view->pos.offset = offset;
2404 view->pos.lineno = lineno;
2405 return TRUE;
2408 return FALSE;
2411 /* Scrolling backend */
2412 static void
2413 do_scroll_view(struct view *view, int lines)
2415 bool redraw_current_line = FALSE;
2417 /* The rendering expects the new offset. */
2418 view->pos.offset += lines;
2420 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2421 assert(lines);
2423 /* Move current line into the view. */
2424 if (view->pos.lineno < view->pos.offset) {
2425 view->pos.lineno = view->pos.offset;
2426 redraw_current_line = TRUE;
2427 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2428 view->pos.lineno = view->pos.offset + view->height - 1;
2429 redraw_current_line = TRUE;
2432 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2434 /* Redraw the whole screen if scrolling is pointless. */
2435 if (view->height < ABS(lines)) {
2436 redraw_view(view);
2438 } else {
2439 int line = lines > 0 ? view->height - lines : 0;
2440 int end = line + ABS(lines);
2442 scrollok(view->win, TRUE);
2443 wscrl(view->win, lines);
2444 scrollok(view->win, FALSE);
2446 while (line < end && draw_view_line(view, line))
2447 line++;
2449 if (redraw_current_line)
2450 draw_view_line(view, view->pos.lineno - view->pos.offset);
2451 wnoutrefresh(view->win);
2454 view->has_scrolled = TRUE;
2455 report("");
2458 /* Scroll frontend */
2459 static void
2460 scroll_view(struct view *view, enum request request)
2462 int lines = 1;
2464 assert(view_is_displayed(view));
2466 switch (request) {
2467 case REQ_SCROLL_FIRST_COL:
2468 view->pos.col = 0;
2469 redraw_view_from(view, 0);
2470 report("");
2471 return;
2472 case REQ_SCROLL_LEFT:
2473 if (view->pos.col == 0) {
2474 report("Cannot scroll beyond the first column");
2475 return;
2477 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2478 view->pos.col = 0;
2479 else
2480 view->pos.col -= apply_step(opt_hscroll, view->width);
2481 redraw_view_from(view, 0);
2482 report("");
2483 return;
2484 case REQ_SCROLL_RIGHT:
2485 view->pos.col += apply_step(opt_hscroll, view->width);
2486 redraw_view(view);
2487 report("");
2488 return;
2489 case REQ_SCROLL_PAGE_DOWN:
2490 lines = view->height;
2491 case REQ_SCROLL_LINE_DOWN:
2492 if (view->pos.offset + lines > view->lines)
2493 lines = view->lines - view->pos.offset;
2495 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2496 report("Cannot scroll beyond the last line");
2497 return;
2499 break;
2501 case REQ_SCROLL_PAGE_UP:
2502 lines = view->height;
2503 case REQ_SCROLL_LINE_UP:
2504 if (lines > view->pos.offset)
2505 lines = view->pos.offset;
2507 if (lines == 0) {
2508 report("Cannot scroll beyond the first line");
2509 return;
2512 lines = -lines;
2513 break;
2515 default:
2516 die("request %d not handled in switch", request);
2519 do_scroll_view(view, lines);
2522 /* Cursor moving */
2523 static void
2524 move_view(struct view *view, enum request request)
2526 int scroll_steps = 0;
2527 int steps;
2529 switch (request) {
2530 case REQ_MOVE_FIRST_LINE:
2531 steps = -view->pos.lineno;
2532 break;
2534 case REQ_MOVE_LAST_LINE:
2535 steps = view->lines - view->pos.lineno - 1;
2536 break;
2538 case REQ_MOVE_PAGE_UP:
2539 steps = view->height > view->pos.lineno
2540 ? -view->pos.lineno : -view->height;
2541 break;
2543 case REQ_MOVE_PAGE_DOWN:
2544 steps = view->pos.lineno + view->height >= view->lines
2545 ? view->lines - view->pos.lineno - 1 : view->height;
2546 break;
2548 case REQ_MOVE_UP:
2549 case REQ_PREVIOUS:
2550 steps = -1;
2551 break;
2553 case REQ_MOVE_DOWN:
2554 case REQ_NEXT:
2555 steps = 1;
2556 break;
2558 default:
2559 die("request %d not handled in switch", request);
2562 if (steps <= 0 && view->pos.lineno == 0) {
2563 report("Cannot move beyond the first line");
2564 return;
2566 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2567 report("Cannot move beyond the last line");
2568 return;
2571 /* Move the current line */
2572 view->pos.lineno += steps;
2573 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2575 /* Check whether the view needs to be scrolled */
2576 if (view->pos.lineno < view->pos.offset ||
2577 view->pos.lineno >= view->pos.offset + view->height) {
2578 scroll_steps = steps;
2579 if (steps < 0 && -steps > view->pos.offset) {
2580 scroll_steps = -view->pos.offset;
2582 } else if (steps > 0) {
2583 if (view->pos.lineno == view->lines - 1 &&
2584 view->lines > view->height) {
2585 scroll_steps = view->lines - view->pos.offset - 1;
2586 if (scroll_steps >= view->height)
2587 scroll_steps -= view->height - 1;
2592 if (!view_is_displayed(view)) {
2593 view->pos.offset += scroll_steps;
2594 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2595 view->ops->select(view, &view->line[view->pos.lineno]);
2596 return;
2599 /* Repaint the old "current" line if we be scrolling */
2600 if (ABS(steps) < view->height)
2601 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2603 if (scroll_steps) {
2604 do_scroll_view(view, scroll_steps);
2605 return;
2608 /* Draw the current line */
2609 draw_view_line(view, view->pos.lineno - view->pos.offset);
2611 wnoutrefresh(view->win);
2612 report("");
2617 * Searching
2620 static void search_view(struct view *view, enum request request);
2622 static bool
2623 grep_text(struct view *view, const char *text[])
2625 regmatch_t pmatch;
2626 size_t i;
2628 for (i = 0; text[i]; i++)
2629 if (*text[i] &&
2630 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2631 return TRUE;
2632 return FALSE;
2635 static void
2636 select_view_line(struct view *view, unsigned long lineno)
2638 struct position old = view->pos;
2640 if (goto_view_line(view, view->pos.offset, lineno)) {
2641 if (view_is_displayed(view)) {
2642 if (old.offset != view->pos.offset) {
2643 redraw_view(view);
2644 } else {
2645 draw_view_line(view, old.lineno - view->pos.offset);
2646 draw_view_line(view, view->pos.lineno - view->pos.offset);
2647 wnoutrefresh(view->win);
2649 } else {
2650 view->ops->select(view, &view->line[view->pos.lineno]);
2655 static void
2656 find_next(struct view *view, enum request request)
2658 unsigned long lineno = view->pos.lineno;
2659 int direction;
2661 if (!*view->grep) {
2662 if (!*opt_search)
2663 report("No previous search");
2664 else
2665 search_view(view, request);
2666 return;
2669 switch (request) {
2670 case REQ_SEARCH:
2671 case REQ_FIND_NEXT:
2672 direction = 1;
2673 break;
2675 case REQ_SEARCH_BACK:
2676 case REQ_FIND_PREV:
2677 direction = -1;
2678 break;
2680 default:
2681 return;
2684 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2685 lineno += direction;
2687 /* Note, lineno is unsigned long so will wrap around in which case it
2688 * will become bigger than view->lines. */
2689 for (; lineno < view->lines; lineno += direction) {
2690 if (view->ops->grep(view, &view->line[lineno])) {
2691 select_view_line(view, lineno);
2692 report("Line %ld matches '%s'", lineno + 1, view->grep);
2693 return;
2697 report("No match found for '%s'", view->grep);
2700 static void
2701 search_view(struct view *view, enum request request)
2703 int regex_err;
2705 if (view->regex) {
2706 regfree(view->regex);
2707 *view->grep = 0;
2708 } else {
2709 view->regex = calloc(1, sizeof(*view->regex));
2710 if (!view->regex)
2711 return;
2714 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2715 if (regex_err != 0) {
2716 char buf[SIZEOF_STR] = "unknown error";
2718 regerror(regex_err, view->regex, buf, sizeof(buf));
2719 report("Search failed: %s", buf);
2720 return;
2723 string_copy(view->grep, opt_search);
2725 find_next(view, request);
2729 * Incremental updating
2732 static inline bool
2733 check_position(struct position *pos)
2735 return pos->lineno || pos->col || pos->offset;
2738 static inline void
2739 clear_position(struct position *pos)
2741 memset(pos, 0, sizeof(*pos));
2744 static void
2745 reset_view(struct view *view)
2747 int i;
2749 for (i = 0; i < view->lines; i++)
2750 if (!view->line[i].dont_free)
2751 free(view->line[i].data);
2752 free(view->line);
2754 view->prev_pos = view->pos;
2755 clear_position(&view->pos);
2757 view->line = NULL;
2758 view->lines = 0;
2759 view->vid[0] = 0;
2760 view->lineoffset = 0;
2761 view->update_secs = 0;
2764 static const char *
2765 format_arg(const char *name)
2767 static struct {
2768 const char *name;
2769 size_t namelen;
2770 const char *value;
2771 const char *value_if_empty;
2772 } vars[] = {
2773 #define FORMAT_VAR(name, value, value_if_empty) \
2774 { name, STRING_SIZE(name), value, value_if_empty }
2775 FORMAT_VAR("%(directory)", opt_path, "."),
2776 FORMAT_VAR("%(file)", opt_file, ""),
2777 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2778 FORMAT_VAR("%(head)", ref_head, ""),
2779 FORMAT_VAR("%(commit)", ref_commit, ""),
2780 FORMAT_VAR("%(blob)", ref_blob, ""),
2781 FORMAT_VAR("%(branch)", ref_branch, ""),
2783 int i;
2785 if (!prefixcmp(name, "%(prompt"))
2786 return read_prompt("Command argument: ");
2788 for (i = 0; i < ARRAY_SIZE(vars); i++)
2789 if (!strncmp(name, vars[i].name, vars[i].namelen))
2790 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2792 report("Unknown replacement: `%s`", name);
2793 return NULL;
2796 static bool
2797 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2799 char buf[SIZEOF_STR];
2800 int argc;
2802 argv_free(*dst_argv);
2804 for (argc = 0; src_argv[argc]; argc++) {
2805 const char *arg = src_argv[argc];
2806 size_t bufpos = 0;
2808 if (!strcmp(arg, "%(fileargs)")) {
2809 if (!argv_append_array(dst_argv, opt_file_argv))
2810 break;
2811 continue;
2813 } else if (!strcmp(arg, "%(diffargs)")) {
2814 if (!argv_append_array(dst_argv, opt_diff_argv))
2815 break;
2816 continue;
2818 } else if (!strcmp(arg, "%(blameargs)")) {
2819 if (!argv_append_array(dst_argv, opt_blame_argv))
2820 break;
2821 continue;
2823 } else if (!strcmp(arg, "%(revargs)") ||
2824 (first && !strcmp(arg, "%(commit)"))) {
2825 if (!argv_append_array(dst_argv, opt_rev_argv))
2826 break;
2827 continue;
2830 while (arg) {
2831 char *next = strstr(arg, "%(");
2832 int len = next - arg;
2833 const char *value;
2835 if (!next) {
2836 len = strlen(arg);
2837 value = "";
2839 } else {
2840 value = format_arg(next);
2842 if (!value) {
2843 return FALSE;
2847 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2848 return FALSE;
2850 arg = next ? strchr(next, ')') + 1 : NULL;
2853 if (!argv_append(dst_argv, buf))
2854 break;
2857 return src_argv[argc] == NULL;
2860 static bool
2861 restore_view_position(struct view *view)
2863 /* A view without a previous view is the first view */
2864 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2865 select_view_line(view, opt_lineno - 1);
2866 opt_lineno = 0;
2869 /* Ensure that the view position is in a valid state. */
2870 if (!check_position(&view->prev_pos) ||
2871 (view->pipe && view->lines <= view->prev_pos.lineno))
2872 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2874 /* Changing the view position cancels the restoring. */
2875 /* FIXME: Changing back to the first line is not detected. */
2876 if (check_position(&view->pos)) {
2877 clear_position(&view->prev_pos);
2878 return FALSE;
2881 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2882 view_is_displayed(view))
2883 werase(view->win);
2885 view->pos.col = view->prev_pos.col;
2886 clear_position(&view->prev_pos);
2888 return TRUE;
2891 static void
2892 end_update(struct view *view, bool force)
2894 if (!view->pipe)
2895 return;
2896 while (!view->ops->read(view, NULL))
2897 if (!force)
2898 return;
2899 if (force)
2900 io_kill(view->pipe);
2901 io_done(view->pipe);
2902 view->pipe = NULL;
2905 static void
2906 setup_update(struct view *view, const char *vid)
2908 reset_view(view);
2909 string_copy_rev(view->vid, vid);
2910 view->pipe = &view->io;
2911 view->start_time = time(NULL);
2914 static bool
2915 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2917 bool extra = !!(flags & (OPEN_EXTRA));
2918 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2919 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2921 if (!reload && !strcmp(view->vid, view->id))
2922 return TRUE;
2924 if (view->pipe) {
2925 if (extra)
2926 io_done(view->pipe);
2927 else
2928 end_update(view, TRUE);
2931 if (!refresh && argv) {
2932 view->dir = dir;
2933 if (!format_argv(&view->argv, argv, !view->prev)) {
2934 report("Failed to format %s arguments", view->name);
2935 return FALSE;
2938 /* Put the current ref_* value to the view title ref
2939 * member. This is needed by the blob view. Most other
2940 * views sets it automatically after loading because the
2941 * first line is a commit line. */
2942 string_copy_rev(view->ref, view->id);
2945 if (view->argv && view->argv[0] &&
2946 !io_run(&view->io, IO_RD, view->dir, view->argv)) {
2947 report("Failed to open %s view", view->name);
2948 return FALSE;
2951 if (!extra)
2952 setup_update(view, view->id);
2954 return TRUE;
2957 static bool
2958 update_view(struct view *view)
2960 char *line;
2961 /* Clear the view and redraw everything since the tree sorting
2962 * might have rearranged things. */
2963 bool redraw = view->lines == 0;
2964 bool can_read = TRUE;
2966 if (!view->pipe)
2967 return TRUE;
2969 if (!io_can_read(view->pipe, FALSE)) {
2970 if (view->lines == 0 && view_is_displayed(view)) {
2971 time_t secs = time(NULL) - view->start_time;
2973 if (secs > 1 && secs > view->update_secs) {
2974 if (view->update_secs == 0)
2975 redraw_view(view);
2976 update_view_title(view);
2977 view->update_secs = secs;
2980 return TRUE;
2983 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2984 if (view->encoding) {
2985 line = encoding_convert(view->encoding, line);
2988 if (!view->ops->read(view, line)) {
2989 report("Allocation failure");
2990 end_update(view, TRUE);
2991 return FALSE;
2996 unsigned long lines = view->lines;
2997 int digits;
2999 for (digits = 0; lines; digits++)
3000 lines /= 10;
3002 /* Keep the displayed view in sync with line number scaling. */
3003 if (digits != view->digits) {
3004 view->digits = digits;
3005 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3006 redraw = TRUE;
3010 if (io_error(view->pipe)) {
3011 report("Failed to read: %s", io_strerror(view->pipe));
3012 end_update(view, TRUE);
3014 } else if (io_eof(view->pipe)) {
3015 if (view_is_displayed(view))
3016 report("");
3017 end_update(view, FALSE);
3020 if (restore_view_position(view))
3021 redraw = TRUE;
3023 if (!view_is_displayed(view))
3024 return TRUE;
3026 if (redraw)
3027 redraw_view_from(view, 0);
3028 else
3029 redraw_view_dirty(view);
3031 /* Update the title _after_ the redraw so that if the redraw picks up a
3032 * commit reference in view->ref it'll be available here. */
3033 update_view_title(view);
3034 return TRUE;
3037 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3039 static struct line *
3040 add_line_data(struct view *view, void *data, enum line_type type)
3042 struct line *line;
3044 if (!realloc_lines(&view->line, view->lines, 1))
3045 return NULL;
3047 line = &view->line[view->lines++];
3048 memset(line, 0, sizeof(*line));
3049 line->type = type;
3050 line->data = data;
3051 line->dirty = 1;
3053 return line;
3056 static struct line *
3057 add_line_static_data(struct view *view, void *data, enum line_type type)
3059 struct line *line = add_line_data(view, data, type);
3061 if (line)
3062 line->dont_free = TRUE;
3063 return line;
3066 static struct line *
3067 add_line_text(struct view *view, const char *text, enum line_type type)
3069 char *data = text ? strdup(text) : NULL;
3071 return data ? add_line_data(view, data, type) : NULL;
3074 static struct line *
3075 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3077 char buf[SIZEOF_STR];
3078 int retval;
3080 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3081 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3085 * View opening
3088 static void
3089 split_view(struct view *prev, struct view *view)
3091 display[1] = view;
3092 current_view = 1;
3093 view->parent = prev;
3094 resize_display();
3096 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3097 /* Take the title line into account. */
3098 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3100 /* Scroll the view that was split if the current line is
3101 * outside the new limited view. */
3102 do_scroll_view(prev, lines);
3105 if (view != prev && view_is_displayed(prev)) {
3106 /* "Blur" the previous view. */
3107 update_view_title(prev);
3111 static void
3112 maximize_view(struct view *view, bool redraw)
3114 memset(display, 0, sizeof(display));
3115 current_view = 0;
3116 display[current_view] = view;
3117 resize_display();
3118 if (redraw) {
3119 redraw_display(FALSE);
3120 report("");
3124 static void
3125 load_view(struct view *view, struct view *prev, enum open_flags flags)
3127 if (view->pipe)
3128 end_update(view, TRUE);
3129 if (view->ops->private_size) {
3130 if (!view->private)
3131 view->private = calloc(1, view->ops->private_size);
3132 else
3133 memset(view->private, 0, view->ops->private_size);
3136 /* When prev == view it means this is the first loaded view. */
3137 if (prev && view != prev) {
3138 view->prev = prev;
3141 if (!view->ops->open(view, flags))
3142 return;
3144 if (prev) {
3145 bool split = !!(flags & OPEN_SPLIT);
3147 if (split) {
3148 split_view(prev, view);
3149 } else {
3150 maximize_view(view, FALSE);
3154 restore_view_position(view);
3156 if (view->pipe && view->lines == 0) {
3157 /* Clear the old view and let the incremental updating refill
3158 * the screen. */
3159 werase(view->win);
3160 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3161 clear_position(&view->prev_pos);
3162 report("");
3163 } else if (view_is_displayed(view)) {
3164 redraw_view(view);
3165 report("");
3169 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3170 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3172 static void
3173 open_view(struct view *prev, enum request request, enum open_flags flags)
3175 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3176 struct view *view = VIEW(request);
3177 int nviews = displayed_views();
3179 assert(flags ^ OPEN_REFRESH);
3181 if (view == prev && nviews == 1 && !reload) {
3182 report("Already in %s view", view->name);
3183 return;
3186 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3187 report("The %s view is disabled in pager view", view->name);
3188 return;
3191 load_view(view, prev ? prev : view, flags);
3194 static void
3195 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3197 enum request request = view - views + REQ_OFFSET + 1;
3199 if (view->pipe)
3200 end_update(view, TRUE);
3201 view->dir = dir;
3203 if (!argv_copy(&view->argv, argv)) {
3204 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3205 } else {
3206 open_view(prev, request, flags | OPEN_PREPARED);
3210 static void
3211 open_external_viewer(const char *argv[], const char *dir)
3213 def_prog_mode(); /* save current tty modes */
3214 endwin(); /* restore original tty modes */
3215 io_run_fg(argv, dir);
3216 fprintf(stderr, "Press Enter to continue");
3217 getc(opt_tty);
3218 reset_prog_mode();
3219 redraw_display(TRUE);
3222 static void
3223 open_mergetool(const char *file)
3225 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3227 open_external_viewer(mergetool_argv, opt_cdup);
3230 static void
3231 open_editor(const char *file)
3233 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3234 char editor_cmd[SIZEOF_STR];
3235 const char *editor;
3236 int argc = 0;
3238 editor = getenv("GIT_EDITOR");
3239 if (!editor && *opt_editor)
3240 editor = opt_editor;
3241 if (!editor)
3242 editor = getenv("VISUAL");
3243 if (!editor)
3244 editor = getenv("EDITOR");
3245 if (!editor)
3246 editor = "vi";
3248 string_ncopy(editor_cmd, editor, strlen(editor));
3249 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3250 report("Failed to read editor command");
3251 return;
3254 editor_argv[argc] = file;
3255 open_external_viewer(editor_argv, opt_cdup);
3258 static void
3259 open_run_request(enum request request)
3261 struct run_request *req = get_run_request(request);
3262 const char **argv = NULL;
3264 if (!req) {
3265 report("Unknown run request");
3266 return;
3269 if (format_argv(&argv, req->argv, FALSE)) {
3270 bool confirmed = !req->confirm;
3272 if (req->confirm) {
3273 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3275 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3276 string_format(prompt, "Run `%s`?", cmd) &&
3277 prompt_yesno(prompt)) {
3278 confirmed = TRUE;
3282 if (!confirmed)
3283 ; /* Nothing */
3284 else if (req->silent)
3285 io_run_bg(argv);
3286 else
3287 open_external_viewer(argv, NULL);
3289 if (argv)
3290 argv_free(argv);
3291 free(argv);
3295 * User request switch noodle
3298 static int
3299 view_driver(struct view *view, enum request request)
3301 int i;
3303 if (request == REQ_NONE)
3304 return TRUE;
3306 if (request > REQ_NONE) {
3307 open_run_request(request);
3308 view_request(view, REQ_REFRESH);
3309 return TRUE;
3312 request = view_request(view, request);
3313 if (request == REQ_NONE)
3314 return TRUE;
3316 switch (request) {
3317 case REQ_MOVE_UP:
3318 case REQ_MOVE_DOWN:
3319 case REQ_MOVE_PAGE_UP:
3320 case REQ_MOVE_PAGE_DOWN:
3321 case REQ_MOVE_FIRST_LINE:
3322 case REQ_MOVE_LAST_LINE:
3323 move_view(view, request);
3324 break;
3326 case REQ_SCROLL_FIRST_COL:
3327 case REQ_SCROLL_LEFT:
3328 case REQ_SCROLL_RIGHT:
3329 case REQ_SCROLL_LINE_DOWN:
3330 case REQ_SCROLL_LINE_UP:
3331 case REQ_SCROLL_PAGE_DOWN:
3332 case REQ_SCROLL_PAGE_UP:
3333 scroll_view(view, request);
3334 break;
3336 case REQ_VIEW_MAIN:
3337 case REQ_VIEW_DIFF:
3338 case REQ_VIEW_LOG:
3339 case REQ_VIEW_TREE:
3340 case REQ_VIEW_HELP:
3341 case REQ_VIEW_BRANCH:
3342 case REQ_VIEW_BLAME:
3343 case REQ_VIEW_BLOB:
3344 case REQ_VIEW_STATUS:
3345 case REQ_VIEW_STAGE:
3346 case REQ_VIEW_PAGER:
3347 open_view(view, request, OPEN_DEFAULT);
3348 break;
3350 case REQ_NEXT:
3351 case REQ_PREVIOUS:
3352 if (view->parent) {
3353 int line;
3355 view = view->parent;
3356 line = view->pos.lineno;
3357 move_view(view, request);
3358 if (view_is_displayed(view))
3359 update_view_title(view);
3360 if (line != view->pos.lineno)
3361 view_request(view, REQ_ENTER);
3362 } else {
3363 move_view(view, request);
3365 break;
3367 case REQ_VIEW_NEXT:
3369 int nviews = displayed_views();
3370 int next_view = (current_view + 1) % nviews;
3372 if (next_view == current_view) {
3373 report("Only one view is displayed");
3374 break;
3377 current_view = next_view;
3378 /* Blur out the title of the previous view. */
3379 update_view_title(view);
3380 report("");
3381 break;
3383 case REQ_REFRESH:
3384 report("Refreshing is not yet supported for the %s view", view->name);
3385 break;
3387 case REQ_MAXIMIZE:
3388 if (displayed_views() == 2)
3389 maximize_view(view, TRUE);
3390 break;
3392 case REQ_OPTIONS:
3393 case REQ_TOGGLE_LINENO:
3394 case REQ_TOGGLE_DATE:
3395 case REQ_TOGGLE_AUTHOR:
3396 case REQ_TOGGLE_FILENAME:
3397 case REQ_TOGGLE_GRAPHIC:
3398 case REQ_TOGGLE_REV_GRAPH:
3399 case REQ_TOGGLE_REFS:
3400 case REQ_TOGGLE_CHANGES:
3401 case REQ_TOGGLE_IGNORE_SPACE:
3402 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3403 reload_view(view);
3404 break;
3406 case REQ_TOGGLE_SORT_FIELD:
3407 case REQ_TOGGLE_SORT_ORDER:
3408 report("Sorting is not yet supported for the %s view", view->name);
3409 break;
3411 case REQ_DIFF_CONTEXT_UP:
3412 case REQ_DIFF_CONTEXT_DOWN:
3413 report("Changing the diff context is not yet supported for the %s view", view->name);
3414 break;
3416 case REQ_SEARCH:
3417 case REQ_SEARCH_BACK:
3418 search_view(view, request);
3419 break;
3421 case REQ_FIND_NEXT:
3422 case REQ_FIND_PREV:
3423 find_next(view, request);
3424 break;
3426 case REQ_STOP_LOADING:
3427 foreach_view(view, i) {
3428 if (view->pipe)
3429 report("Stopped loading the %s view", view->name),
3430 end_update(view, TRUE);
3432 break;
3434 case REQ_SHOW_VERSION:
3435 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3436 return TRUE;
3438 case REQ_SCREEN_REDRAW:
3439 redraw_display(TRUE);
3440 break;
3442 case REQ_EDIT:
3443 report("Nothing to edit");
3444 break;
3446 case REQ_ENTER:
3447 report("Nothing to enter");
3448 break;
3450 case REQ_VIEW_CLOSE:
3451 /* XXX: Mark closed views by letting view->prev point to the
3452 * view itself. Parents to closed view should never be
3453 * followed. */
3454 if (view->prev && view->prev != view) {
3455 maximize_view(view->prev, TRUE);
3456 view->prev = view;
3457 break;
3459 /* Fall-through */
3460 case REQ_QUIT:
3461 return FALSE;
3463 default:
3464 report("Unknown key, press %s for help",
3465 get_view_key(view, REQ_VIEW_HELP));
3466 return TRUE;
3469 return TRUE;
3474 * View backend utilities
3477 enum sort_field {
3478 ORDERBY_NAME,
3479 ORDERBY_DATE,
3480 ORDERBY_AUTHOR,
3483 struct sort_state {
3484 const enum sort_field *fields;
3485 size_t size, current;
3486 bool reverse;
3489 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3490 #define get_sort_field(state) ((state).fields[(state).current])
3491 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3493 static void
3494 sort_view(struct view *view, enum request request, struct sort_state *state,
3495 int (*compare)(const void *, const void *))
3497 switch (request) {
3498 case REQ_TOGGLE_SORT_FIELD:
3499 state->current = (state->current + 1) % state->size;
3500 break;
3502 case REQ_TOGGLE_SORT_ORDER:
3503 state->reverse = !state->reverse;
3504 break;
3505 default:
3506 die("Not a sort request");
3509 qsort(view->line, view->lines, sizeof(*view->line), compare);
3510 redraw_view(view);
3513 static bool
3514 update_diff_context(enum request request)
3516 int diff_context = opt_diff_context;
3518 switch (request) {
3519 case REQ_DIFF_CONTEXT_UP:
3520 opt_diff_context += 1;
3521 update_diff_context_arg(opt_diff_context);
3522 break;
3524 case REQ_DIFF_CONTEXT_DOWN:
3525 if (opt_diff_context == 0) {
3526 report("Diff context cannot be less than zero");
3527 break;
3529 opt_diff_context -= 1;
3530 update_diff_context_arg(opt_diff_context);
3531 break;
3533 default:
3534 die("Not a diff context request");
3537 return diff_context != opt_diff_context;
3540 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3542 /* Small author cache to reduce memory consumption. It uses binary
3543 * search to lookup or find place to position new entries. No entries
3544 * are ever freed. */
3545 static const char *
3546 get_author(const char *name)
3548 static const char **authors;
3549 static size_t authors_size;
3550 int from = 0, to = authors_size - 1;
3552 while (from <= to) {
3553 size_t pos = (to + from) / 2;
3554 int cmp = strcmp(name, authors[pos]);
3556 if (!cmp)
3557 return authors[pos];
3559 if (cmp < 0)
3560 to = pos - 1;
3561 else
3562 from = pos + 1;
3565 if (!realloc_authors(&authors, authors_size, 1))
3566 return NULL;
3567 name = strdup(name);
3568 if (!name)
3569 return NULL;
3571 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3572 authors[from] = name;
3573 authors_size++;
3575 return name;
3578 static void
3579 parse_timesec(struct time *time, const char *sec)
3581 time->sec = (time_t) atol(sec);
3584 static void
3585 parse_timezone(struct time *time, const char *zone)
3587 long tz;
3589 tz = ('0' - zone[1]) * 60 * 60 * 10;
3590 tz += ('0' - zone[2]) * 60 * 60;
3591 tz += ('0' - zone[3]) * 60 * 10;
3592 tz += ('0' - zone[4]) * 60;
3594 if (zone[0] == '-')
3595 tz = -tz;
3597 time->tz = tz;
3598 time->sec -= tz;
3601 /* Parse author lines where the name may be empty:
3602 * author <email@address.tld> 1138474660 +0100
3604 static void
3605 parse_author_line(char *ident, const char **author, struct time *time)
3607 char *nameend = strchr(ident, '<');
3608 char *emailend = strchr(ident, '>');
3610 if (nameend && emailend)
3611 *nameend = *emailend = 0;
3612 ident = chomp_string(ident);
3613 if (!*ident) {
3614 if (nameend)
3615 ident = chomp_string(nameend + 1);
3616 if (!*ident)
3617 ident = "Unknown";
3620 *author = get_author(ident);
3622 /* Parse epoch and timezone */
3623 if (emailend && emailend[1] == ' ') {
3624 char *secs = emailend + 2;
3625 char *zone = strchr(secs, ' ');
3627 parse_timesec(time, secs);
3629 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3630 parse_timezone(time, zone + 1);
3634 static struct line *
3635 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3637 for (; view_has_line(view, line); line += direction)
3638 if (line->type == type)
3639 return line;
3641 return NULL;
3644 #define find_prev_line_by_type(view, line, type) \
3645 find_line_by_type(view, line, type, -1)
3647 #define find_next_line_by_type(view, line, type) \
3648 find_line_by_type(view, line, type, 1)
3651 * Blame
3654 struct blame_commit {
3655 char id[SIZEOF_REV]; /* SHA1 ID. */
3656 char title[128]; /* First line of the commit message. */
3657 const char *author; /* Author of the commit. */
3658 struct time time; /* Date from the author ident. */
3659 char filename[128]; /* Name of file. */
3660 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3661 char parent_filename[128]; /* Parent/previous name of file. */
3664 struct blame_header {
3665 char id[SIZEOF_REV]; /* SHA1 ID. */
3666 size_t orig_lineno;
3667 size_t lineno;
3668 size_t group;
3671 static bool
3672 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3674 const char *pos = *posref;
3676 *posref = NULL;
3677 pos = strchr(pos + 1, ' ');
3678 if (!pos || !isdigit(pos[1]))
3679 return FALSE;
3680 *number = atoi(pos + 1);
3681 if (*number < min || *number > max)
3682 return FALSE;
3684 *posref = pos;
3685 return TRUE;
3688 static bool
3689 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3691 const char *pos = text + SIZEOF_REV - 2;
3693 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3694 return FALSE;
3696 string_ncopy(header->id, text, SIZEOF_REV);
3698 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3699 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3700 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3701 return FALSE;
3703 return TRUE;
3706 static bool
3707 match_blame_header(const char *name, char **line)
3709 size_t namelen = strlen(name);
3710 bool matched = !strncmp(name, *line, namelen);
3712 if (matched)
3713 *line += namelen;
3715 return matched;
3718 static bool
3719 parse_blame_info(struct blame_commit *commit, char *line)
3721 if (match_blame_header("author ", &line)) {
3722 commit->author = get_author(line);
3724 } else if (match_blame_header("author-time ", &line)) {
3725 parse_timesec(&commit->time, line);
3727 } else if (match_blame_header("author-tz ", &line)) {
3728 parse_timezone(&commit->time, line);
3730 } else if (match_blame_header("summary ", &line)) {
3731 string_ncopy(commit->title, line, strlen(line));
3733 } else if (match_blame_header("previous ", &line)) {
3734 if (strlen(line) <= SIZEOF_REV)
3735 return FALSE;
3736 string_copy_rev(commit->parent_id, line);
3737 line += SIZEOF_REV;
3738 string_ncopy(commit->parent_filename, line, strlen(line));
3740 } else if (match_blame_header("filename ", &line)) {
3741 string_ncopy(commit->filename, line, strlen(line));
3742 return TRUE;
3745 return FALSE;
3749 * Pager backend
3752 static bool
3753 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3755 if (draw_lineno(view, lineno))
3756 return TRUE;
3758 draw_text(view, line->type, line->data);
3759 return TRUE;
3762 static bool
3763 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3765 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3766 char ref[SIZEOF_STR];
3768 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3769 return TRUE;
3771 /* This is the only fatal call, since it can "corrupt" the buffer. */
3772 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3773 return FALSE;
3775 return TRUE;
3778 static void
3779 add_pager_refs(struct view *view, const char *commit_id)
3781 char buf[SIZEOF_STR];
3782 struct ref_list *list;
3783 size_t bufpos = 0, i;
3784 const char *sep = "Refs: ";
3785 bool is_tag = FALSE;
3787 list = get_ref_list(commit_id);
3788 if (!list) {
3789 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3790 goto try_add_describe_ref;
3791 return;
3794 for (i = 0; i < list->size; i++) {
3795 struct ref *ref = list->refs[i];
3796 const char *fmt = ref->tag ? "%s[%s]" :
3797 ref->remote ? "%s<%s>" : "%s%s";
3799 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3800 return;
3801 sep = ", ";
3802 if (ref->tag)
3803 is_tag = TRUE;
3806 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3807 try_add_describe_ref:
3808 /* Add <tag>-g<commit_id> "fake" reference. */
3809 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3810 return;
3813 if (bufpos == 0)
3814 return;
3816 add_line_text(view, buf, LINE_PP_REFS);
3819 static bool
3820 pager_common_read(struct view *view, const char *data, enum line_type type)
3822 struct line *line;
3824 if (!data)
3825 return TRUE;
3827 line = add_line_text(view, data, type);
3828 if (!line)
3829 return FALSE;
3831 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3832 add_pager_refs(view, data + STRING_SIZE("commit "));
3834 return TRUE;
3837 static bool
3838 pager_read(struct view *view, char *data)
3840 if (!data)
3841 return TRUE;
3843 return pager_common_read(view, data, get_line_type(data));
3846 static enum request
3847 pager_request(struct view *view, enum request request, struct line *line)
3849 int split = 0;
3851 if (request != REQ_ENTER)
3852 return request;
3854 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3855 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3856 split = 1;
3859 /* Always scroll the view even if it was split. That way
3860 * you can use Enter to scroll through the log view and
3861 * split open each commit diff. */
3862 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3864 /* FIXME: A minor workaround. Scrolling the view will call report("")
3865 * but if we are scrolling a non-current view this won't properly
3866 * update the view title. */
3867 if (split)
3868 update_view_title(view);
3870 return REQ_NONE;
3873 static bool
3874 pager_grep(struct view *view, struct line *line)
3876 const char *text[] = { line->data, NULL };
3878 return grep_text(view, text);
3881 static void
3882 pager_select(struct view *view, struct line *line)
3884 if (line->type == LINE_COMMIT) {
3885 char *text = (char *)line->data + STRING_SIZE("commit ");
3887 if (!view_has_flags(view, VIEW_NO_REF))
3888 string_copy_rev(view->ref, text);
3889 string_copy_rev(ref_commit, text);
3893 static bool
3894 pager_open(struct view *view, enum open_flags flags)
3896 if (display[0] == NULL) {
3897 if (!io_open(&view->io, ""))
3898 die("Failed to open stdin");
3899 flags = OPEN_PREPARED;
3901 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
3902 report("No pager content, press %s to run command from prompt",
3903 get_view_key(view, REQ_PROMPT));
3904 return FALSE;
3907 return begin_update(view, NULL, NULL, flags);
3910 static struct view_ops pager_ops = {
3911 "line",
3912 { "pager" },
3913 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3915 pager_open,
3916 pager_read,
3917 pager_draw,
3918 pager_request,
3919 pager_grep,
3920 pager_select,
3923 static bool
3924 log_open(struct view *view, enum open_flags flags)
3926 static const char *log_argv[] = {
3927 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3930 return begin_update(view, NULL, log_argv, flags);
3933 static enum request
3934 log_request(struct view *view, enum request request, struct line *line)
3936 switch (request) {
3937 case REQ_REFRESH:
3938 load_refs();
3939 refresh_view(view);
3940 return REQ_NONE;
3941 default:
3942 return pager_request(view, request, line);
3946 static struct view_ops log_ops = {
3947 "line",
3948 { "log" },
3949 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3951 log_open,
3952 pager_read,
3953 pager_draw,
3954 log_request,
3955 pager_grep,
3956 pager_select,
3959 struct diff_state {
3960 bool reading_diff_stat;
3961 bool combined_diff;
3964 static bool
3965 diff_open(struct view *view, enum open_flags flags)
3967 static const char *diff_argv[] = {
3968 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3969 "--patch-with-stat", "--find-copies-harder", "-C",
3970 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3971 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3974 return begin_update(view, NULL, diff_argv, flags);
3977 static bool
3978 diff_common_read(struct view *view, const char *data, struct diff_state *state)
3980 enum line_type type = get_line_type(data);
3982 if (!view->lines && type != LINE_COMMIT)
3983 state->reading_diff_stat = TRUE;
3985 if (state->reading_diff_stat) {
3986 size_t len = strlen(data);
3987 char *pipe = strchr(data, '|');
3988 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3989 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3990 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
3992 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
3993 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3994 } else {
3995 state->reading_diff_stat = FALSE;
3998 } else if (!strcmp(data, "---")) {
3999 state->reading_diff_stat = TRUE;
4002 if (type == LINE_DIFF_HEADER) {
4003 const int len = line_info[LINE_DIFF_HEADER].linelen;
4005 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4006 !strncmp(data + len, "cc ", strlen("cc ")))
4007 state->combined_diff = TRUE;
4010 /* ADD2 and DEL2 are only valid in combined diff hunks */
4011 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4012 type = LINE_DEFAULT;
4014 return pager_common_read(view, data, type);
4017 static bool
4018 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4020 struct line *marker = find_next_line_by_type(view, line, type);
4022 return marker &&
4023 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4026 static enum request
4027 diff_common_enter(struct view *view, enum request request, struct line *line)
4029 if (line->type == LINE_DIFF_STAT) {
4030 int file_number = 0;
4032 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4033 file_number++;
4034 line--;
4037 for (line = view->line; view_has_line(view, line); line++) {
4038 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4039 if (!line)
4040 break;
4042 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4043 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4044 if (file_number == 1) {
4045 break;
4047 file_number--;
4051 if (!line) {
4052 report("Failed to find file diff");
4053 return REQ_NONE;
4056 select_view_line(view, line - view->line);
4057 report("");
4058 return REQ_NONE;
4060 } else {
4061 return pager_request(view, request, line);
4065 static bool
4066 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4068 char *sep = strchr(*text, c);
4070 if (sep != NULL) {
4071 *sep = 0;
4072 draw_text(view, *type, *text);
4073 *sep = c;
4074 *text = sep;
4075 *type = next_type;
4078 return sep != NULL;
4081 static bool
4082 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4084 char *text = line->data;
4085 enum line_type type = line->type;
4087 if (draw_lineno(view, lineno))
4088 return TRUE;
4090 if (type == LINE_DIFF_STAT) {
4091 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4092 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4093 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4094 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4095 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4096 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4097 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4099 } else {
4100 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4101 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4105 draw_text(view, type, text);
4106 return TRUE;
4109 static bool
4110 diff_read(struct view *view, char *data)
4112 struct diff_state *state = view->private;
4114 if (!data) {
4115 /* Fall back to retry if no diff will be shown. */
4116 if (view->lines == 0 && opt_file_argv) {
4117 int pos = argv_size(view->argv)
4118 - argv_size(opt_file_argv) - 1;
4120 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4121 for (; view->argv[pos]; pos++) {
4122 free((void *) view->argv[pos]);
4123 view->argv[pos] = NULL;
4126 if (view->pipe)
4127 io_done(view->pipe);
4128 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4129 return FALSE;
4132 return TRUE;
4135 return diff_common_read(view, data, state);
4138 static bool
4139 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4140 struct blame_header *header, struct blame_commit *commit)
4142 char line_arg[SIZEOF_STR];
4143 const char *blame_argv[] = {
4144 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4146 struct io io;
4147 bool ok = FALSE;
4148 char *buf;
4150 if (!string_format(line_arg, "-L%d,+1", lineno))
4151 return FALSE;
4153 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4154 return FALSE;
4156 while ((buf = io_get(&io, '\n', TRUE))) {
4157 if (header) {
4158 if (!parse_blame_header(header, buf, 9999999))
4159 break;
4160 header = NULL;
4162 } else if (parse_blame_info(commit, buf)) {
4163 ok = TRUE;
4164 break;
4168 if (io_error(&io))
4169 ok = FALSE;
4171 io_done(&io);
4172 return ok;
4175 static bool
4176 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4178 return prefixcmp(chunk, "@@ -") ||
4179 !(chunk = strchr(chunk, marker)) ||
4180 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4183 static enum request
4184 diff_trace_origin(struct view *view, struct line *line)
4186 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4187 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4188 const char *chunk_data;
4189 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4190 int lineno = 0;
4191 const char *file = NULL;
4192 char ref[SIZEOF_REF];
4193 struct blame_header header;
4194 struct blame_commit commit;
4196 if (!diff || !chunk || chunk == line) {
4197 report("The line to trace must be inside a diff chunk");
4198 return REQ_NONE;
4201 for (; diff < line && !file; diff++) {
4202 const char *data = diff->data;
4204 if (!prefixcmp(data, "--- a/")) {
4205 file = data + STRING_SIZE("--- a/");
4206 break;
4210 if (diff == line || !file) {
4211 report("Failed to read the file name");
4212 return REQ_NONE;
4215 chunk_data = chunk->data;
4217 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4218 report("Failed to read the line number");
4219 return REQ_NONE;
4222 if (lineno == 0) {
4223 report("This is the origin of the line");
4224 return REQ_NONE;
4227 for (chunk += 1; chunk < line; chunk++) {
4228 if (chunk->type == LINE_DIFF_ADD) {
4229 lineno += chunk_marker == '+';
4230 } else if (chunk->type == LINE_DIFF_DEL) {
4231 lineno += chunk_marker == '-';
4232 } else {
4233 lineno++;
4237 if (chunk_marker == '+')
4238 string_copy(ref, view->vid);
4239 else
4240 string_format(ref, "%s^", view->vid);
4242 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4243 report("Failed to read blame data");
4244 return REQ_NONE;
4247 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4248 string_copy(opt_ref, header.id);
4249 opt_goto_line = header.orig_lineno - 1;
4251 return REQ_VIEW_BLAME;
4254 static enum request
4255 diff_request(struct view *view, enum request request, struct line *line)
4257 switch (request) {
4258 case REQ_VIEW_BLAME:
4259 return diff_trace_origin(view, line);
4261 case REQ_DIFF_CONTEXT_UP:
4262 case REQ_DIFF_CONTEXT_DOWN:
4263 if (!update_diff_context(request))
4264 return REQ_NONE;
4265 reload_view(view);
4266 return REQ_NONE;
4269 case REQ_ENTER:
4270 return diff_common_enter(view, request, line);
4272 default:
4273 return pager_request(view, request, line);
4277 static void
4278 diff_select(struct view *view, struct line *line)
4280 if (line->type == LINE_DIFF_STAT) {
4281 const char *key = get_view_key(view, REQ_ENTER);
4283 string_format(view->ref, "Press '%s' to jump to file diff", key);
4284 } else {
4285 struct line *header = line->type == LINE_DIFF_HEADER ? line :
4286 find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4288 if (header != NULL) {
4289 const char *file_name = NULL;
4291 for (header += 1; view_has_line(view, header); header++) {
4292 if (header->type == LINE_DIFF_RENAME_TO)
4293 file_name = header->data + STRING_SIZE("rename to ");
4294 if (header->type == LINE_DIFF_ADD && !strncmp(header->data, "+++ b/", 6))
4295 file_name = header->data + STRING_SIZE("+++ b/");
4297 /* The diff chunk marks the end of the diff header. */
4298 if (file_name || header->type == LINE_DIFF_CHUNK)
4299 break;
4302 string_format(view->ref, "Diff of '%s'", file_name);
4303 return;
4306 string_ncopy(view->ref, view->id, strlen(view->id));
4307 return pager_select(view, line);
4311 static struct view_ops diff_ops = {
4312 "line",
4313 { "diff" },
4314 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4315 sizeof(struct diff_state),
4316 diff_open,
4317 diff_read,
4318 diff_common_draw,
4319 diff_request,
4320 pager_grep,
4321 diff_select,
4325 * Help backend
4328 static bool
4329 help_draw(struct view *view, struct line *line, unsigned int lineno)
4331 if (line->type == LINE_HELP_KEYMAP) {
4332 struct keymap *keymap = line->data;
4334 draw_formatted(view, line->type, "[%c] %s bindings",
4335 keymap->hidden ? '+' : '-', keymap->name);
4336 return TRUE;
4337 } else {
4338 return pager_draw(view, line, lineno);
4342 static bool
4343 help_open_keymap_title(struct view *view, struct keymap *keymap)
4345 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4346 return keymap->hidden;
4349 static void
4350 help_open_keymap(struct view *view, struct keymap *keymap)
4352 const char *group = NULL;
4353 char buf[SIZEOF_STR];
4354 bool add_title = TRUE;
4355 int i;
4357 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4358 const char *key = NULL;
4360 if (req_info[i].request == REQ_NONE)
4361 continue;
4363 if (!req_info[i].request) {
4364 group = req_info[i].help;
4365 continue;
4368 key = get_keys(keymap, req_info[i].request, TRUE);
4369 if (!key || !*key)
4370 continue;
4372 if (add_title && help_open_keymap_title(view, keymap))
4373 return;
4374 add_title = FALSE;
4376 if (group) {
4377 add_line_text(view, group, LINE_HELP_GROUP);
4378 group = NULL;
4381 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4382 enum_name(req_info[i]), req_info[i].help);
4385 group = "External commands:";
4387 for (i = 0; i < run_requests; i++) {
4388 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4389 const char *key;
4391 if (!req || req->keymap != keymap)
4392 continue;
4394 key = get_key_name(req->key);
4395 if (!*key)
4396 key = "(no key defined)";
4398 if (add_title && help_open_keymap_title(view, keymap))
4399 return;
4400 add_title = FALSE;
4402 if (group) {
4403 add_line_text(view, group, LINE_HELP_GROUP);
4404 group = NULL;
4407 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4408 return;
4410 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4414 static bool
4415 help_open(struct view *view, enum open_flags flags)
4417 struct keymap *keymap;
4419 reset_view(view);
4420 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4421 add_line_text(view, "", LINE_DEFAULT);
4423 for (keymap = keymaps; keymap; keymap = keymap->next)
4424 help_open_keymap(view, keymap);
4426 return TRUE;
4429 static enum request
4430 help_request(struct view *view, enum request request, struct line *line)
4432 switch (request) {
4433 case REQ_ENTER:
4434 if (line->type == LINE_HELP_KEYMAP) {
4435 struct keymap *keymap = line->data;
4437 keymap->hidden = !keymap->hidden;
4438 refresh_view(view);
4441 return REQ_NONE;
4442 default:
4443 return pager_request(view, request, line);
4447 static struct view_ops help_ops = {
4448 "line",
4449 { "help" },
4450 VIEW_NO_GIT_DIR,
4452 help_open,
4453 NULL,
4454 help_draw,
4455 help_request,
4456 pager_grep,
4457 pager_select,
4462 * Tree backend
4465 struct tree_stack_entry {
4466 struct tree_stack_entry *prev; /* Entry below this in the stack */
4467 unsigned long lineno; /* Line number to restore */
4468 char *name; /* Position of name in opt_path */
4471 /* The top of the path stack. */
4472 static struct tree_stack_entry *tree_stack = NULL;
4473 unsigned long tree_lineno = 0;
4475 static void
4476 pop_tree_stack_entry(void)
4478 struct tree_stack_entry *entry = tree_stack;
4480 tree_lineno = entry->lineno;
4481 entry->name[0] = 0;
4482 tree_stack = entry->prev;
4483 free(entry);
4486 static void
4487 push_tree_stack_entry(const char *name, unsigned long lineno)
4489 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4490 size_t pathlen = strlen(opt_path);
4492 if (!entry)
4493 return;
4495 entry->prev = tree_stack;
4496 entry->name = opt_path + pathlen;
4497 tree_stack = entry;
4499 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4500 pop_tree_stack_entry();
4501 return;
4504 /* Move the current line to the first tree entry. */
4505 tree_lineno = 1;
4506 entry->lineno = lineno;
4509 /* Parse output from git-ls-tree(1):
4511 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4514 #define SIZEOF_TREE_ATTR \
4515 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4517 #define SIZEOF_TREE_MODE \
4518 STRING_SIZE("100644 ")
4520 #define TREE_ID_OFFSET \
4521 STRING_SIZE("100644 blob ")
4523 #define tree_entry_is_parent(entry) (!strcmp("..", (entry)->name))
4525 struct tree_entry {
4526 char id[SIZEOF_REV];
4527 mode_t mode;
4528 struct time time; /* Date from the author ident. */
4529 const char *author; /* Author of the commit. */
4530 char name[1];
4533 struct tree_state {
4534 const char *author_name;
4535 struct time author_time;
4536 bool read_date;
4539 static const char *
4540 tree_path(const struct line *line)
4542 return ((struct tree_entry *) line->data)->name;
4545 static int
4546 tree_compare_entry(const struct line *line1, const struct line *line2)
4548 if (line1->type != line2->type)
4549 return line1->type == LINE_TREE_DIR ? -1 : 1;
4550 return strcmp(tree_path(line1), tree_path(line2));
4553 static const enum sort_field tree_sort_fields[] = {
4554 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4556 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4558 static int
4559 tree_compare(const void *l1, const void *l2)
4561 const struct line *line1 = (const struct line *) l1;
4562 const struct line *line2 = (const struct line *) l2;
4563 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4564 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4566 if (line1->type == LINE_TREE_HEAD)
4567 return -1;
4568 if (line2->type == LINE_TREE_HEAD)
4569 return 1;
4571 switch (get_sort_field(tree_sort_state)) {
4572 case ORDERBY_DATE:
4573 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4575 case ORDERBY_AUTHOR:
4576 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4578 case ORDERBY_NAME:
4579 default:
4580 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4585 static struct line *
4586 tree_entry(struct view *view, enum line_type type, const char *path,
4587 const char *mode, const char *id)
4589 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4590 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4592 if (!entry || !line) {
4593 free(entry);
4594 return NULL;
4597 strncpy(entry->name, path, strlen(path));
4598 if (mode)
4599 entry->mode = strtoul(mode, NULL, 8);
4600 if (id)
4601 string_copy_rev(entry->id, id);
4602 if (type == LINE_TREE_HEAD || tree_entry_is_parent(entry))
4603 view->lineoffset++;
4605 return line;
4608 static bool
4609 tree_read_date(struct view *view, char *text, struct tree_state *state)
4611 if (!text && state->read_date) {
4612 state->read_date = FALSE;
4613 return TRUE;
4615 } else if (!text) {
4616 /* Find next entry to process */
4617 const char *log_file[] = {
4618 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4619 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4622 if (!view->lines) {
4623 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4624 report("Tree is empty");
4625 return TRUE;
4628 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4629 report("Failed to load tree data");
4630 return TRUE;
4633 state->read_date = TRUE;
4634 return FALSE;
4636 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4637 parse_author_line(text + STRING_SIZE("author "),
4638 &state->author_name, &state->author_time);
4640 } else if (*text == ':') {
4641 char *pos;
4642 size_t annotated = 1;
4643 size_t i;
4645 pos = strchr(text, '\t');
4646 if (!pos)
4647 return TRUE;
4648 text = pos + 1;
4649 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4650 text += strlen(opt_path);
4651 pos = strchr(text, '/');
4652 if (pos)
4653 *pos = 0;
4655 for (i = 1; i < view->lines; i++) {
4656 struct line *line = &view->line[i];
4657 struct tree_entry *entry = line->data;
4659 annotated += !!entry->author;
4660 if (entry->author || strcmp(entry->name, text))
4661 continue;
4663 entry->author = state->author_name;
4664 entry->time = state->author_time;
4665 line->dirty = 1;
4666 break;
4669 if (annotated == view->lines)
4670 io_kill(view->pipe);
4672 return TRUE;
4675 static bool
4676 tree_read(struct view *view, char *text)
4678 struct tree_state *state = view->private;
4679 struct tree_entry *data;
4680 struct line *entry, *line;
4681 enum line_type type;
4682 size_t textlen = text ? strlen(text) : 0;
4683 char *path = text + SIZEOF_TREE_ATTR;
4685 if (state->read_date || !text)
4686 return tree_read_date(view, text, state);
4688 if (textlen <= SIZEOF_TREE_ATTR)
4689 return FALSE;
4690 if (view->lines == 0 &&
4691 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4692 return FALSE;
4694 /* Strip the path part ... */
4695 if (*opt_path) {
4696 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4697 size_t striplen = strlen(opt_path);
4699 if (pathlen > striplen)
4700 memmove(path, path + striplen,
4701 pathlen - striplen + 1);
4703 /* Insert "link" to parent directory. */
4704 if (view->lines == 1 &&
4705 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4706 return FALSE;
4709 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4710 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4711 if (!entry)
4712 return FALSE;
4713 data = entry->data;
4715 /* Skip "Directory ..." and ".." line. */
4716 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4717 if (tree_compare_entry(line, entry) <= 0)
4718 continue;
4720 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4722 line->data = data;
4723 line->type = type;
4724 for (; line <= entry; line++)
4725 line->dirty = line->cleareol = 1;
4726 return TRUE;
4729 if (tree_lineno <= view->pos.lineno)
4730 tree_lineno = view->lineoffset;
4732 if (tree_lineno > view->pos.lineno) {
4733 view->pos.lineno = tree_lineno;
4734 tree_lineno = 0;
4737 return TRUE;
4740 static bool
4741 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4743 struct tree_entry *entry = line->data;
4745 if (line->type == LINE_TREE_HEAD) {
4746 if (draw_text(view, line->type, "Directory path /"))
4747 return TRUE;
4748 } else {
4749 if (draw_mode(view, entry->mode))
4750 return TRUE;
4752 if (draw_author(view, entry->author))
4753 return TRUE;
4755 if (draw_date(view, &entry->time))
4756 return TRUE;
4759 draw_text(view, line->type, entry->name);
4760 return TRUE;
4763 static void
4764 open_blob_editor(const char *id)
4766 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4767 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4768 int fd = mkstemp(file);
4770 if (fd == -1)
4771 report("Failed to create temporary file");
4772 else if (!io_run_append(blob_argv, fd))
4773 report("Failed to save blob data to file");
4774 else
4775 open_editor(file);
4776 if (fd != -1)
4777 unlink(file);
4780 static enum request
4781 tree_request(struct view *view, enum request request, struct line *line)
4783 enum open_flags flags;
4784 struct tree_entry *entry = line->data;
4786 switch (request) {
4787 case REQ_VIEW_BLAME:
4788 if (line->type != LINE_TREE_FILE) {
4789 report("Blame only supported for files");
4790 return REQ_NONE;
4793 string_copy(opt_ref, view->vid);
4794 return request;
4796 case REQ_EDIT:
4797 if (line->type != LINE_TREE_FILE) {
4798 report("Edit only supported for files");
4799 } else if (!is_head_commit(view->vid)) {
4800 open_blob_editor(entry->id);
4801 } else {
4802 open_editor(opt_file);
4804 return REQ_NONE;
4806 case REQ_TOGGLE_SORT_FIELD:
4807 case REQ_TOGGLE_SORT_ORDER:
4808 sort_view(view, request, &tree_sort_state, tree_compare);
4809 return REQ_NONE;
4811 case REQ_PARENT:
4812 if (!*opt_path) {
4813 /* quit view if at top of tree */
4814 return REQ_VIEW_CLOSE;
4816 /* fake 'cd ..' */
4817 line = &view->line[1];
4818 break;
4820 case REQ_ENTER:
4821 break;
4823 default:
4824 return request;
4827 /* Cleanup the stack if the tree view is at a different tree. */
4828 while (!*opt_path && tree_stack)
4829 pop_tree_stack_entry();
4831 switch (line->type) {
4832 case LINE_TREE_DIR:
4833 /* Depending on whether it is a subdirectory or parent link
4834 * mangle the path buffer. */
4835 if (line == &view->line[1] && *opt_path) {
4836 pop_tree_stack_entry();
4838 } else {
4839 const char *basename = tree_path(line);
4841 push_tree_stack_entry(basename, view->pos.lineno);
4844 /* Trees and subtrees share the same ID, so they are not not
4845 * unique like blobs. */
4846 flags = OPEN_RELOAD;
4847 request = REQ_VIEW_TREE;
4848 break;
4850 case LINE_TREE_FILE:
4851 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4852 request = REQ_VIEW_BLOB;
4853 break;
4855 default:
4856 return REQ_NONE;
4859 open_view(view, request, flags);
4860 if (request == REQ_VIEW_TREE)
4861 view->pos.lineno = tree_lineno;
4863 return REQ_NONE;
4866 static bool
4867 tree_grep(struct view *view, struct line *line)
4869 struct tree_entry *entry = line->data;
4870 const char *text[] = {
4871 entry->name,
4872 mkauthor(entry->author, opt_author_cols, opt_author),
4873 mkdate(&entry->time, opt_date),
4874 NULL
4877 return grep_text(view, text);
4880 static void
4881 tree_select(struct view *view, struct line *line)
4883 struct tree_entry *entry = line->data;
4885 if (line->type == LINE_TREE_HEAD) {
4886 string_format(view->ref, "Files in /%s", opt_path);
4887 return;
4890 if (line->type == LINE_TREE_DIR && tree_entry_is_parent(entry)) {
4891 string_copy(view->ref, "Open parent directory");
4892 return;
4895 if (line->type == LINE_TREE_FILE) {
4896 string_copy_rev(ref_blob, entry->id);
4897 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4900 string_copy_rev(view->ref, entry->id);
4903 static bool
4904 tree_open(struct view *view, enum open_flags flags)
4906 static const char *tree_argv[] = {
4907 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4910 if (string_rev_is_null(ref_commit)) {
4911 report("No tree exists for this commit");
4912 return FALSE;
4915 if (view->lines == 0 && opt_prefix[0]) {
4916 char *pos = opt_prefix;
4918 while (pos && *pos) {
4919 char *end = strchr(pos, '/');
4921 if (end)
4922 *end = 0;
4923 push_tree_stack_entry(pos, 0);
4924 pos = end;
4925 if (end) {
4926 *end = '/';
4927 pos++;
4931 } else if (strcmp(view->vid, view->id)) {
4932 opt_path[0] = 0;
4935 return begin_update(view, opt_cdup, tree_argv, flags);
4938 static struct view_ops tree_ops = {
4939 "file",
4940 { "tree" },
4941 VIEW_NO_FLAGS,
4942 sizeof(struct tree_state),
4943 tree_open,
4944 tree_read,
4945 tree_draw,
4946 tree_request,
4947 tree_grep,
4948 tree_select,
4951 static bool
4952 blob_open(struct view *view, enum open_flags flags)
4954 static const char *blob_argv[] = {
4955 "git", "cat-file", "blob", "%(blob)", NULL
4958 if (!ref_blob[0]) {
4959 report("No file chosen, press %s to open tree view",
4960 get_view_key(view, REQ_VIEW_TREE));
4961 return FALSE;
4964 view->encoding = get_path_encoding(opt_file, opt_encoding);
4966 return begin_update(view, NULL, blob_argv, flags);
4969 static bool
4970 blob_read(struct view *view, char *line)
4972 if (!line)
4973 return TRUE;
4974 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4977 static enum request
4978 blob_request(struct view *view, enum request request, struct line *line)
4980 switch (request) {
4981 case REQ_EDIT:
4982 open_blob_editor(view->vid);
4983 return REQ_NONE;
4984 default:
4985 return pager_request(view, request, line);
4989 static struct view_ops blob_ops = {
4990 "line",
4991 { "blob" },
4992 VIEW_NO_FLAGS,
4994 blob_open,
4995 blob_read,
4996 pager_draw,
4997 blob_request,
4998 pager_grep,
4999 pager_select,
5003 * Blame backend
5005 * Loading the blame view is a two phase job:
5007 * 1. File content is read either using opt_file from the
5008 * filesystem or using git-cat-file.
5009 * 2. Then blame information is incrementally added by
5010 * reading output from git-blame.
5013 struct blame {
5014 struct blame_commit *commit;
5015 unsigned long lineno;
5016 char text[1];
5019 struct blame_state {
5020 struct blame_commit *commit;
5021 int blamed;
5022 bool done_reading;
5023 bool auto_filename_display;
5026 static bool
5027 blame_detect_filename_display(struct view *view)
5029 bool show_filenames = FALSE;
5030 const char *filename = NULL;
5031 int i;
5033 if (opt_blame_argv) {
5034 for (i = 0; opt_blame_argv[i]; i++) {
5035 if (prefixcmp(opt_blame_argv[i], "-C"))
5036 continue;
5038 show_filenames = TRUE;
5042 for (i = 0; i < view->lines; i++) {
5043 struct blame *blame = view->line[i].data;
5045 if (blame->commit && blame->commit->id[0]) {
5046 if (!filename)
5047 filename = blame->commit->filename;
5048 else if (strcmp(filename, blame->commit->filename))
5049 show_filenames = TRUE;
5053 return show_filenames;
5056 static bool
5057 blame_open(struct view *view, enum open_flags flags)
5059 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5060 char path[SIZEOF_STR];
5061 size_t i;
5063 if (!opt_file[0]) {
5064 report("No file chosen, press %s to open tree view",
5065 get_view_key(view, REQ_VIEW_TREE));
5066 return FALSE;
5069 if (!view->prev && *opt_prefix) {
5070 string_copy(path, opt_file);
5071 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5072 report("Failed to setup the blame view");
5073 return FALSE;
5077 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5078 const char *blame_cat_file_argv[] = {
5079 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5082 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5083 return FALSE;
5086 /* First pass: remove multiple references to the same commit. */
5087 for (i = 0; i < view->lines; i++) {
5088 struct blame *blame = view->line[i].data;
5090 if (blame->commit && blame->commit->id[0])
5091 blame->commit->id[0] = 0;
5092 else
5093 blame->commit = NULL;
5096 /* Second pass: free existing references. */
5097 for (i = 0; i < view->lines; i++) {
5098 struct blame *blame = view->line[i].data;
5100 if (blame->commit)
5101 free(blame->commit);
5104 string_format(view->vid, "%s", opt_file);
5105 string_format(view->ref, "%s ...", opt_file);
5107 return TRUE;
5110 static struct blame_commit *
5111 get_blame_commit(struct view *view, const char *id)
5113 size_t i;
5115 for (i = 0; i < view->lines; i++) {
5116 struct blame *blame = view->line[i].data;
5118 if (!blame->commit)
5119 continue;
5121 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5122 return blame->commit;
5126 struct blame_commit *commit = calloc(1, sizeof(*commit));
5128 if (commit)
5129 string_ncopy(commit->id, id, SIZEOF_REV);
5130 return commit;
5134 static struct blame_commit *
5135 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5137 struct blame_header header;
5138 struct blame_commit *commit;
5139 struct blame *blame;
5141 if (!parse_blame_header(&header, text, view->lines))
5142 return NULL;
5144 commit = get_blame_commit(view, text);
5145 if (!commit)
5146 return NULL;
5148 state->blamed += header.group;
5149 while (header.group--) {
5150 struct line *line = &view->line[header.lineno + header.group - 1];
5152 blame = line->data;
5153 blame->commit = commit;
5154 blame->lineno = header.orig_lineno + header.group - 1;
5155 line->dirty = 1;
5158 return commit;
5161 static bool
5162 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5164 if (!line) {
5165 const char *blame_argv[] = {
5166 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5167 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5170 if (view->lines == 0 && !view->prev)
5171 die("No blame exist for %s", view->vid);
5173 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5174 report("Failed to load blame data");
5175 return TRUE;
5178 if (opt_goto_line > 0) {
5179 select_view_line(view, opt_goto_line);
5180 opt_goto_line = 0;
5183 state->done_reading = TRUE;
5184 return FALSE;
5186 } else {
5187 size_t linelen = strlen(line);
5188 struct blame *blame = malloc(sizeof(*blame) + linelen);
5190 if (!blame)
5191 return FALSE;
5193 blame->commit = NULL;
5194 strncpy(blame->text, line, linelen);
5195 blame->text[linelen] = 0;
5196 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5200 static bool
5201 blame_read(struct view *view, char *line)
5203 struct blame_state *state = view->private;
5205 if (!state->done_reading)
5206 return blame_read_file(view, line, state);
5208 if (!line) {
5209 state->auto_filename_display = blame_detect_filename_display(view);
5210 string_format(view->ref, "%s", view->vid);
5211 if (view_is_displayed(view)) {
5212 update_view_title(view);
5213 redraw_view_from(view, 0);
5215 return TRUE;
5218 if (!state->commit) {
5219 state->commit = read_blame_commit(view, line, state);
5220 string_format(view->ref, "%s %2d%%", view->vid,
5221 view->lines ? state->blamed * 100 / view->lines : 0);
5223 } else if (parse_blame_info(state->commit, line)) {
5224 state->commit = NULL;
5227 return TRUE;
5230 static bool
5231 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5233 struct blame_state *state = view->private;
5234 struct blame *blame = line->data;
5235 struct time *time = NULL;
5236 const char *id = NULL, *author = NULL, *filename = NULL;
5237 enum line_type id_type = LINE_BLAME_ID;
5238 static const enum line_type blame_colors[] = {
5239 LINE_PALETTE_0,
5240 LINE_PALETTE_1,
5241 LINE_PALETTE_2,
5242 LINE_PALETTE_3,
5243 LINE_PALETTE_4,
5244 LINE_PALETTE_5,
5245 LINE_PALETTE_6,
5248 #define BLAME_COLOR(i) \
5249 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5251 if (blame->commit && *blame->commit->filename) {
5252 id = blame->commit->id;
5253 author = blame->commit->author;
5254 filename = blame->commit->filename;
5255 time = &blame->commit->time;
5256 id_type = BLAME_COLOR((long) blame->commit);
5259 if (draw_date(view, time))
5260 return TRUE;
5262 if (draw_author(view, author))
5263 return TRUE;
5265 if (draw_filename(view, filename, state->auto_filename_display))
5266 return TRUE;
5268 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5269 return TRUE;
5271 if (draw_lineno(view, lineno))
5272 return TRUE;
5274 draw_text(view, LINE_DEFAULT, blame->text);
5275 return TRUE;
5278 static bool
5279 check_blame_commit(struct blame *blame, bool check_null_id)
5281 if (!blame->commit)
5282 report("Commit data not loaded yet");
5283 else if (check_null_id && string_rev_is_null(blame->commit->id))
5284 report("No commit exist for the selected line");
5285 else
5286 return TRUE;
5287 return FALSE;
5290 static void
5291 setup_blame_parent_line(struct view *view, struct blame *blame)
5293 char from[SIZEOF_REF + SIZEOF_STR];
5294 char to[SIZEOF_REF + SIZEOF_STR];
5295 const char *diff_tree_argv[] = {
5296 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5297 "--no-color", "-U0", from, to, "--", NULL
5299 struct io io;
5300 int parent_lineno = -1;
5301 int blamed_lineno = -1;
5302 char *line;
5304 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5305 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5306 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5307 return;
5309 while ((line = io_get(&io, '\n', TRUE))) {
5310 if (*line == '@') {
5311 char *pos = strchr(line, '+');
5313 parent_lineno = atoi(line + 4);
5314 if (pos)
5315 blamed_lineno = atoi(pos + 1);
5317 } else if (*line == '+' && parent_lineno != -1) {
5318 if (blame->lineno == blamed_lineno - 1 &&
5319 !strcmp(blame->text, line + 1)) {
5320 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5321 break;
5323 blamed_lineno++;
5327 io_done(&io);
5330 static enum request
5331 blame_request(struct view *view, enum request request, struct line *line)
5333 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5334 struct blame *blame = line->data;
5336 switch (request) {
5337 case REQ_VIEW_BLAME:
5338 if (check_blame_commit(blame, TRUE)) {
5339 string_copy(opt_ref, blame->commit->id);
5340 string_copy(opt_file, blame->commit->filename);
5341 if (blame->lineno)
5342 view->pos.lineno = blame->lineno;
5343 reload_view(view);
5345 break;
5347 case REQ_PARENT:
5348 if (!check_blame_commit(blame, TRUE))
5349 break;
5350 if (!*blame->commit->parent_id) {
5351 report("The selected commit has no parents");
5352 } else {
5353 string_copy_rev(opt_ref, blame->commit->parent_id);
5354 string_copy(opt_file, blame->commit->parent_filename);
5355 setup_blame_parent_line(view, blame);
5356 opt_goto_line = blame->lineno;
5357 reload_view(view);
5359 break;
5361 case REQ_ENTER:
5362 if (!check_blame_commit(blame, FALSE))
5363 break;
5365 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5366 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5367 break;
5369 if (string_rev_is_null(blame->commit->id)) {
5370 struct view *diff = VIEW(REQ_VIEW_DIFF);
5371 const char *diff_parent_argv[] = {
5372 GIT_DIFF_BLAME(opt_diff_context_arg,
5373 opt_ignore_space_arg, view->vid)
5375 const char *diff_no_parent_argv[] = {
5376 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5377 opt_ignore_space_arg, view->vid)
5379 const char **diff_index_argv = *blame->commit->parent_id
5380 ? diff_parent_argv : diff_no_parent_argv;
5382 open_argv(view, diff, diff_index_argv, NULL, flags);
5383 if (diff->pipe)
5384 string_copy_rev(diff->ref, NULL_ID);
5385 } else {
5386 open_view(view, REQ_VIEW_DIFF, flags);
5388 break;
5390 default:
5391 return request;
5394 return REQ_NONE;
5397 static bool
5398 blame_grep(struct view *view, struct line *line)
5400 struct blame *blame = line->data;
5401 struct blame_commit *commit = blame->commit;
5402 const char *text[] = {
5403 blame->text,
5404 commit ? commit->title : "",
5405 commit ? commit->id : "",
5406 commit && opt_author ? commit->author : "",
5407 commit ? mkdate(&commit->time, opt_date) : "",
5408 NULL
5411 return grep_text(view, text);
5414 static void
5415 blame_select(struct view *view, struct line *line)
5417 struct blame *blame = line->data;
5418 struct blame_commit *commit = blame->commit;
5420 if (!commit)
5421 return;
5423 if (string_rev_is_null(commit->id))
5424 string_ncopy(ref_commit, "HEAD", 4);
5425 else
5426 string_copy_rev(ref_commit, commit->id);
5429 static struct view_ops blame_ops = {
5430 "line",
5431 { "blame" },
5432 VIEW_ALWAYS_LINENO,
5433 sizeof(struct blame_state),
5434 blame_open,
5435 blame_read,
5436 blame_draw,
5437 blame_request,
5438 blame_grep,
5439 blame_select,
5443 * Branch backend
5446 struct branch {
5447 const char *author; /* Author of the last commit. */
5448 struct time time; /* Date of the last activity. */
5449 char title[128]; /* First line of the commit message. */
5450 const struct ref *ref; /* Name and commit ID information. */
5453 static const struct ref branch_all;
5454 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5456 static const enum sort_field branch_sort_fields[] = {
5457 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5459 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5461 struct branch_state {
5462 char id[SIZEOF_REV];
5463 size_t max_ref_length;
5466 static int
5467 branch_compare(const void *l1, const void *l2)
5469 const struct branch *branch1 = ((const struct line *) l1)->data;
5470 const struct branch *branch2 = ((const struct line *) l2)->data;
5472 if (branch_is_all(branch1))
5473 return -1;
5474 else if (branch_is_all(branch2))
5475 return 1;
5477 switch (get_sort_field(branch_sort_state)) {
5478 case ORDERBY_DATE:
5479 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5481 case ORDERBY_AUTHOR:
5482 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5484 case ORDERBY_NAME:
5485 default:
5486 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5490 static bool
5491 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5493 struct branch_state *state = view->private;
5494 struct branch *branch = line->data;
5495 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5496 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5498 if (draw_date(view, &branch->time))
5499 return TRUE;
5501 if (draw_author(view, branch->author))
5502 return TRUE;
5504 if (draw_field(view, type, branch_name, state->max_ref_length + 1, FALSE))
5505 return TRUE;
5507 draw_text(view, LINE_DEFAULT, branch->title);
5508 return TRUE;
5511 static enum request
5512 branch_request(struct view *view, enum request request, struct line *line)
5514 struct branch *branch = line->data;
5516 switch (request) {
5517 case REQ_REFRESH:
5518 load_refs();
5519 refresh_view(view);
5520 return REQ_NONE;
5522 case REQ_TOGGLE_SORT_FIELD:
5523 case REQ_TOGGLE_SORT_ORDER:
5524 sort_view(view, request, &branch_sort_state, branch_compare);
5525 return REQ_NONE;
5527 case REQ_ENTER:
5529 const struct ref *ref = branch->ref;
5530 const char *all_branches_argv[] = {
5531 GIT_MAIN_LOG("", branch_is_all(branch) ? "--all" : ref->name, "")
5533 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5535 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5536 return REQ_NONE;
5538 case REQ_JUMP_COMMIT:
5540 int lineno;
5542 for (lineno = 0; lineno < view->lines; lineno++) {
5543 struct branch *branch = view->line[lineno].data;
5545 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5546 select_view_line(view, lineno);
5547 report("");
5548 return REQ_NONE;
5552 default:
5553 return request;
5557 static bool
5558 branch_read(struct view *view, char *line)
5560 struct branch_state *state = view->private;
5561 const char *title = NULL;
5562 const char *author = NULL;
5563 struct time time = {};
5564 size_t i;
5566 if (!line)
5567 return TRUE;
5569 switch (get_line_type(line)) {
5570 case LINE_COMMIT:
5571 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5572 return TRUE;
5574 case LINE_AUTHOR:
5575 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5577 default:
5578 title = line + STRING_SIZE("title ");
5581 for (i = 0; i < view->lines; i++) {
5582 struct branch *branch = view->line[i].data;
5584 if (strcmp(branch->ref->id, state->id))
5585 continue;
5587 if (author) {
5588 branch->author = author;
5589 branch->time = time;
5592 if (title)
5593 string_expand(branch->title, sizeof(branch->title), title, 1);
5595 view->line[i].dirty = TRUE;
5598 return TRUE;
5601 static bool
5602 branch_open_visitor(void *data, const struct ref *ref)
5604 struct view *view = data;
5605 struct branch_state *state = view->private;
5606 struct branch *branch;
5607 size_t ref_length;
5609 if (ref->tag || ref->ltag)
5610 return TRUE;
5612 branch = calloc(1, sizeof(*branch));
5613 if (!branch)
5614 return FALSE;
5616 ref_length = strlen(ref->name);
5617 if (ref_length > state->max_ref_length)
5618 state->max_ref_length = ref_length;
5620 branch->ref = ref;
5621 return !!add_line_data(view, branch, LINE_DEFAULT);
5624 static bool
5625 branch_open(struct view *view, enum open_flags flags)
5627 const char *branch_log[] = {
5628 "git", "log", ENCODING_ARG, "--no-color", "--date=raw",
5629 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5630 "--all", "--simplify-by-decoration", NULL
5633 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5634 report("Failed to load branch data");
5635 return FALSE;
5638 if (branch_open_visitor(view, &branch_all))
5639 view->lineoffset++;
5640 foreach_ref(branch_open_visitor, view);
5642 return TRUE;
5645 static bool
5646 branch_grep(struct view *view, struct line *line)
5648 struct branch *branch = line->data;
5649 const char *text[] = {
5650 branch->ref->name,
5651 mkauthor(branch->author, opt_author_cols, opt_author),
5652 NULL
5655 return grep_text(view, text);
5658 static void
5659 branch_select(struct view *view, struct line *line)
5661 struct branch *branch = line->data;
5663 if (branch_is_all(branch)) {
5664 string_copy(view->ref, "All branches");
5665 return;
5667 string_copy_rev(view->ref, branch->ref->id);
5668 string_copy_rev(ref_commit, branch->ref->id);
5669 string_copy_rev(ref_head, branch->ref->id);
5670 string_copy_rev(ref_branch, branch->ref->name);
5673 static struct view_ops branch_ops = {
5674 "branch",
5675 { "branch" },
5676 VIEW_NO_FLAGS,
5677 sizeof(struct branch_state),
5678 branch_open,
5679 branch_read,
5680 branch_draw,
5681 branch_request,
5682 branch_grep,
5683 branch_select,
5687 * Status backend
5690 struct status {
5691 char status;
5692 struct {
5693 mode_t mode;
5694 char rev[SIZEOF_REV];
5695 char name[SIZEOF_STR];
5696 } old;
5697 struct {
5698 mode_t mode;
5699 char rev[SIZEOF_REV];
5700 char name[SIZEOF_STR];
5701 } new;
5704 static char status_onbranch[SIZEOF_STR];
5705 static struct status stage_status;
5706 static enum line_type stage_line_type;
5708 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5710 /* This should work even for the "On branch" line. */
5711 static inline bool
5712 status_has_none(struct view *view, struct line *line)
5714 return view_has_line(view, line) && !line[1].data;
5717 /* Get fields from the diff line:
5718 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5720 static inline bool
5721 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5723 const char *old_mode = buf + 1;
5724 const char *new_mode = buf + 8;
5725 const char *old_rev = buf + 15;
5726 const char *new_rev = buf + 56;
5727 const char *status = buf + 97;
5729 if (bufsize < 98 ||
5730 old_mode[-1] != ':' ||
5731 new_mode[-1] != ' ' ||
5732 old_rev[-1] != ' ' ||
5733 new_rev[-1] != ' ' ||
5734 status[-1] != ' ')
5735 return FALSE;
5737 file->status = *status;
5739 string_copy_rev(file->old.rev, old_rev);
5740 string_copy_rev(file->new.rev, new_rev);
5742 file->old.mode = strtoul(old_mode, NULL, 8);
5743 file->new.mode = strtoul(new_mode, NULL, 8);
5745 file->old.name[0] = file->new.name[0] = 0;
5747 return TRUE;
5750 static bool
5751 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5753 struct status *unmerged = NULL;
5754 char *buf;
5755 struct io io;
5757 if (!io_run(&io, IO_RD, opt_cdup, argv))
5758 return FALSE;
5760 add_line_data(view, NULL, type);
5762 while ((buf = io_get(&io, 0, TRUE))) {
5763 struct status *file = unmerged;
5765 if (!file) {
5766 file = calloc(1, sizeof(*file));
5767 if (!file || !add_line_data(view, file, type))
5768 goto error_out;
5771 /* Parse diff info part. */
5772 if (status) {
5773 file->status = status;
5774 if (status == 'A')
5775 string_copy(file->old.rev, NULL_ID);
5777 } else if (!file->status || file == unmerged) {
5778 if (!status_get_diff(file, buf, strlen(buf)))
5779 goto error_out;
5781 buf = io_get(&io, 0, TRUE);
5782 if (!buf)
5783 break;
5785 /* Collapse all modified entries that follow an
5786 * associated unmerged entry. */
5787 if (unmerged == file) {
5788 unmerged->status = 'U';
5789 unmerged = NULL;
5790 } else if (file->status == 'U') {
5791 unmerged = file;
5795 /* Grab the old name for rename/copy. */
5796 if (!*file->old.name &&
5797 (file->status == 'R' || file->status == 'C')) {
5798 string_ncopy(file->old.name, buf, strlen(buf));
5800 buf = io_get(&io, 0, TRUE);
5801 if (!buf)
5802 break;
5805 /* git-ls-files just delivers a NUL separated list of
5806 * file names similar to the second half of the
5807 * git-diff-* output. */
5808 string_ncopy(file->new.name, buf, strlen(buf));
5809 if (!*file->old.name)
5810 string_copy(file->old.name, file->new.name);
5811 file = NULL;
5814 if (io_error(&io)) {
5815 error_out:
5816 io_done(&io);
5817 return FALSE;
5820 if (!view->line[view->lines - 1].data)
5821 add_line_data(view, NULL, LINE_STAT_NONE);
5823 io_done(&io);
5824 return TRUE;
5827 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5828 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5830 static const char *status_list_other_argv[] = {
5831 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5834 static const char *status_list_no_head_argv[] = {
5835 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5838 static const char *update_index_argv[] = {
5839 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5842 /* Restore the previous line number to stay in the context or select a
5843 * line with something that can be updated. */
5844 static void
5845 status_restore(struct view *view)
5847 if (!check_position(&view->prev_pos))
5848 return;
5850 if (view->prev_pos.lineno >= view->lines)
5851 view->prev_pos.lineno = view->lines - 1;
5852 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5853 view->prev_pos.lineno++;
5854 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5855 view->prev_pos.lineno--;
5857 /* If the above fails, always skip the "On branch" line. */
5858 if (view->prev_pos.lineno < view->lines)
5859 view->pos.lineno = view->prev_pos.lineno;
5860 else
5861 view->pos.lineno = 1;
5863 if (view->prev_pos.offset > view->pos.lineno)
5864 view->pos.offset = view->pos.lineno;
5865 else if (view->prev_pos.offset < view->lines)
5866 view->pos.offset = view->prev_pos.offset;
5868 clear_position(&view->prev_pos);
5871 static void
5872 status_update_onbranch(void)
5874 static const char *paths[][2] = {
5875 { "rebase-apply/rebasing", "Rebasing" },
5876 { "rebase-apply/applying", "Applying mailbox" },
5877 { "rebase-apply/", "Rebasing mailbox" },
5878 { "rebase-merge/interactive", "Interactive rebase" },
5879 { "rebase-merge/", "Rebase merge" },
5880 { "MERGE_HEAD", "Merging" },
5881 { "BISECT_LOG", "Bisecting" },
5882 { "HEAD", "On branch" },
5884 char buf[SIZEOF_STR];
5885 struct stat stat;
5886 int i;
5888 if (is_initial_commit()) {
5889 string_copy(status_onbranch, "Initial commit");
5890 return;
5893 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5894 char *head = opt_head;
5896 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5897 lstat(buf, &stat) < 0)
5898 continue;
5900 if (!*opt_head) {
5901 struct io io;
5903 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5904 io_read_buf(&io, buf, sizeof(buf))) {
5905 head = buf;
5906 if (!prefixcmp(head, "refs/heads/"))
5907 head += STRING_SIZE("refs/heads/");
5911 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5912 string_copy(status_onbranch, opt_head);
5913 return;
5916 string_copy(status_onbranch, "Not currently on any branch");
5919 /* First parse staged info using git-diff-index(1), then parse unstaged
5920 * info using git-diff-files(1), and finally untracked files using
5921 * git-ls-files(1). */
5922 static bool
5923 status_open(struct view *view, enum open_flags flags)
5925 const char **staged_argv = is_initial_commit() ?
5926 status_list_no_head_argv : status_diff_index_argv;
5927 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
5929 if (opt_is_inside_work_tree == FALSE) {
5930 report("The status view requires a working tree");
5931 return FALSE;
5934 reset_view(view);
5936 add_line_data(view, NULL, LINE_STAT_HEAD);
5937 status_update_onbranch();
5939 io_run_bg(update_index_argv);
5941 if (!opt_untracked_dirs_content)
5942 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5944 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
5945 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5946 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
5947 report("Failed to load status data");
5948 return FALSE;
5951 /* Restore the exact position or use the specialized restore
5952 * mode? */
5953 status_restore(view);
5954 return TRUE;
5957 static bool
5958 status_draw(struct view *view, struct line *line, unsigned int lineno)
5960 struct status *status = line->data;
5961 enum line_type type;
5962 const char *text;
5964 if (!status) {
5965 switch (line->type) {
5966 case LINE_STAT_STAGED:
5967 type = LINE_STAT_SECTION;
5968 text = "Changes to be committed:";
5969 break;
5971 case LINE_STAT_UNSTAGED:
5972 type = LINE_STAT_SECTION;
5973 text = "Changed but not updated:";
5974 break;
5976 case LINE_STAT_UNTRACKED:
5977 type = LINE_STAT_SECTION;
5978 text = "Untracked files:";
5979 break;
5981 case LINE_STAT_NONE:
5982 type = LINE_DEFAULT;
5983 text = " (no files)";
5984 break;
5986 case LINE_STAT_HEAD:
5987 type = LINE_STAT_HEAD;
5988 text = status_onbranch;
5989 break;
5991 default:
5992 return FALSE;
5994 } else {
5995 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5997 buf[0] = status->status;
5998 if (draw_text(view, line->type, buf))
5999 return TRUE;
6000 type = LINE_DEFAULT;
6001 text = status->new.name;
6004 draw_text(view, type, text);
6005 return TRUE;
6008 static enum request
6009 status_enter(struct view *view, struct line *line)
6011 struct status *status = line->data;
6012 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6014 if (line->type == LINE_STAT_NONE ||
6015 (!status && line[1].type == LINE_STAT_NONE)) {
6016 report("No file to diff");
6017 return REQ_NONE;
6020 switch (line->type) {
6021 case LINE_STAT_STAGED:
6022 case LINE_STAT_UNSTAGED:
6023 break;
6025 case LINE_STAT_UNTRACKED:
6026 if (!status) {
6027 report("No file to show");
6028 return REQ_NONE;
6031 if (!suffixcmp(status->new.name, -1, "/")) {
6032 report("Cannot display a directory");
6033 return REQ_NONE;
6035 break;
6037 case LINE_STAT_HEAD:
6038 return REQ_NONE;
6040 default:
6041 die("line type %d not handled in switch", line->type);
6044 if (status) {
6045 stage_status = *status;
6046 } else {
6047 memset(&stage_status, 0, sizeof(stage_status));
6050 stage_line_type = line->type;
6052 open_view(view, REQ_VIEW_STAGE, flags);
6053 return REQ_NONE;
6056 static bool
6057 status_exists(struct view *view, struct status *status, enum line_type type)
6059 unsigned long lineno;
6061 for (lineno = 0; lineno < view->lines; lineno++) {
6062 struct line *line = &view->line[lineno];
6063 struct status *pos = line->data;
6065 if (line->type != type)
6066 continue;
6067 if (!pos && (!status || !status->status) && line[1].data) {
6068 select_view_line(view, lineno);
6069 return TRUE;
6071 if (pos && !strcmp(status->new.name, pos->new.name)) {
6072 select_view_line(view, lineno);
6073 return TRUE;
6077 return FALSE;
6081 static bool
6082 status_update_prepare(struct io *io, enum line_type type)
6084 const char *staged_argv[] = {
6085 "git", "update-index", "-z", "--index-info", NULL
6087 const char *others_argv[] = {
6088 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6091 switch (type) {
6092 case LINE_STAT_STAGED:
6093 return io_run(io, IO_WR, opt_cdup, staged_argv);
6095 case LINE_STAT_UNSTAGED:
6096 case LINE_STAT_UNTRACKED:
6097 return io_run(io, IO_WR, opt_cdup, others_argv);
6099 default:
6100 die("line type %d not handled in switch", type);
6101 return FALSE;
6105 static bool
6106 status_update_write(struct io *io, struct status *status, enum line_type type)
6108 switch (type) {
6109 case LINE_STAT_STAGED:
6110 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6111 status->old.rev, status->old.name, 0);
6113 case LINE_STAT_UNSTAGED:
6114 case LINE_STAT_UNTRACKED:
6115 return io_printf(io, "%s%c", status->new.name, 0);
6117 default:
6118 die("line type %d not handled in switch", type);
6119 return FALSE;
6123 static bool
6124 status_update_file(struct status *status, enum line_type type)
6126 struct io io;
6127 bool result;
6129 if (!status_update_prepare(&io, type))
6130 return FALSE;
6132 result = status_update_write(&io, status, type);
6133 return io_done(&io) && result;
6136 static bool
6137 status_update_files(struct view *view, struct line *line)
6139 char buf[sizeof(view->ref)];
6140 struct io io;
6141 bool result = TRUE;
6142 struct line *pos;
6143 int files = 0;
6144 int file, done;
6145 int cursor_y = -1, cursor_x = -1;
6147 if (!status_update_prepare(&io, line->type))
6148 return FALSE;
6150 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6151 files++;
6153 string_copy(buf, view->ref);
6154 getsyx(cursor_y, cursor_x);
6155 for (file = 0, done = 5; result && file < files; line++, file++) {
6156 int almost_done = file * 100 / files;
6158 if (almost_done > done) {
6159 done = almost_done;
6160 string_format(view->ref, "updating file %u of %u (%d%% done)",
6161 file, files, done);
6162 update_view_title(view);
6163 setsyx(cursor_y, cursor_x);
6164 doupdate();
6166 result = status_update_write(&io, line->data, line->type);
6168 string_copy(view->ref, buf);
6170 return io_done(&io) && result;
6173 static bool
6174 status_update(struct view *view)
6176 struct line *line = &view->line[view->pos.lineno];
6178 assert(view->lines);
6180 if (!line->data) {
6181 if (status_has_none(view, line)) {
6182 report("Nothing to update");
6183 return FALSE;
6186 if (!status_update_files(view, line + 1)) {
6187 report("Failed to update file status");
6188 return FALSE;
6191 } else if (!status_update_file(line->data, line->type)) {
6192 report("Failed to update file status");
6193 return FALSE;
6196 return TRUE;
6199 static bool
6200 status_revert(struct status *status, enum line_type type, bool has_none)
6202 if (!status || type != LINE_STAT_UNSTAGED) {
6203 if (type == LINE_STAT_STAGED) {
6204 report("Cannot revert changes to staged files");
6205 } else if (type == LINE_STAT_UNTRACKED) {
6206 report("Cannot revert changes to untracked files");
6207 } else if (has_none) {
6208 report("Nothing to revert");
6209 } else {
6210 report("Cannot revert changes to multiple files");
6213 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6214 char mode[10] = "100644";
6215 const char *reset_argv[] = {
6216 "git", "update-index", "--cacheinfo", mode,
6217 status->old.rev, status->old.name, NULL
6219 const char *checkout_argv[] = {
6220 "git", "checkout", "--", status->old.name, NULL
6223 if (status->status == 'U') {
6224 string_format(mode, "%5o", status->old.mode);
6226 if (status->old.mode == 0 && status->new.mode == 0) {
6227 reset_argv[2] = "--force-remove";
6228 reset_argv[3] = status->old.name;
6229 reset_argv[4] = NULL;
6232 if (!io_run_fg(reset_argv, opt_cdup))
6233 return FALSE;
6234 if (status->old.mode == 0 && status->new.mode == 0)
6235 return TRUE;
6238 return io_run_fg(checkout_argv, opt_cdup);
6241 return FALSE;
6244 static enum request
6245 status_request(struct view *view, enum request request, struct line *line)
6247 struct status *status = line->data;
6249 switch (request) {
6250 case REQ_STATUS_UPDATE:
6251 if (!status_update(view))
6252 return REQ_NONE;
6253 break;
6255 case REQ_STATUS_REVERT:
6256 if (!status_revert(status, line->type, status_has_none(view, line)))
6257 return REQ_NONE;
6258 break;
6260 case REQ_STATUS_MERGE:
6261 if (!status || status->status != 'U') {
6262 report("Merging only possible for files with unmerged status ('U').");
6263 return REQ_NONE;
6265 open_mergetool(status->new.name);
6266 break;
6268 case REQ_EDIT:
6269 if (!status)
6270 return request;
6271 if (status->status == 'D') {
6272 report("File has been deleted.");
6273 return REQ_NONE;
6276 open_editor(status->new.name);
6277 break;
6279 case REQ_VIEW_BLAME:
6280 if (status)
6281 opt_ref[0] = 0;
6282 return request;
6284 case REQ_ENTER:
6285 /* After returning the status view has been split to
6286 * show the stage view. No further reloading is
6287 * necessary. */
6288 return status_enter(view, line);
6290 case REQ_REFRESH:
6291 /* Simply reload the view. */
6292 break;
6294 default:
6295 return request;
6298 refresh_view(view);
6300 return REQ_NONE;
6303 static void
6304 status_select(struct view *view, struct line *line)
6306 struct status *status = line->data;
6307 char file[SIZEOF_STR] = "all files";
6308 const char *text;
6309 const char *key;
6311 if (status && !string_format(file, "'%s'", status->new.name))
6312 return;
6314 if (!status && line[1].type == LINE_STAT_NONE)
6315 line++;
6317 switch (line->type) {
6318 case LINE_STAT_STAGED:
6319 text = "Press %s to unstage %s for commit";
6320 break;
6322 case LINE_STAT_UNSTAGED:
6323 text = "Press %s to stage %s for commit";
6324 break;
6326 case LINE_STAT_UNTRACKED:
6327 text = "Press %s to stage %s for addition";
6328 break;
6330 case LINE_STAT_HEAD:
6331 case LINE_STAT_NONE:
6332 text = "Nothing to update";
6333 break;
6335 default:
6336 die("line type %d not handled in switch", line->type);
6339 if (status && status->status == 'U') {
6340 text = "Press %s to resolve conflict in %s";
6341 key = get_view_key(view, REQ_STATUS_MERGE);
6343 } else {
6344 key = get_view_key(view, REQ_STATUS_UPDATE);
6347 string_format(view->ref, text, key, file);
6348 if (status)
6349 string_copy(opt_file, status->new.name);
6352 static bool
6353 status_grep(struct view *view, struct line *line)
6355 struct status *status = line->data;
6357 if (status) {
6358 const char buf[2] = { status->status, 0 };
6359 const char *text[] = { status->new.name, buf, NULL };
6361 return grep_text(view, text);
6364 return FALSE;
6367 static struct view_ops status_ops = {
6368 "file",
6369 { "status" },
6370 VIEW_CUSTOM_STATUS,
6372 status_open,
6373 NULL,
6374 status_draw,
6375 status_request,
6376 status_grep,
6377 status_select,
6381 struct stage_state {
6382 struct diff_state diff;
6383 size_t chunks;
6384 int *chunk;
6387 static bool
6388 stage_diff_write(struct io *io, struct line *line, struct line *end)
6390 while (line < end) {
6391 if (!io_write(io, line->data, strlen(line->data)) ||
6392 !io_write(io, "\n", 1))
6393 return FALSE;
6394 line++;
6395 if (line->type == LINE_DIFF_CHUNK ||
6396 line->type == LINE_DIFF_HEADER)
6397 break;
6400 return TRUE;
6403 static bool
6404 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6406 const char *apply_argv[SIZEOF_ARG] = {
6407 "git", "apply", "--whitespace=nowarn", NULL
6409 struct line *diff_hdr;
6410 struct io io;
6411 int argc = 3;
6413 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6414 if (!diff_hdr)
6415 return FALSE;
6417 if (!revert)
6418 apply_argv[argc++] = "--cached";
6419 if (line != NULL)
6420 apply_argv[argc++] = "--unidiff-zero";
6421 if (revert || stage_line_type == LINE_STAT_STAGED)
6422 apply_argv[argc++] = "-R";
6423 apply_argv[argc++] = "-";
6424 apply_argv[argc++] = NULL;
6425 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6426 return FALSE;
6428 if (line != NULL) {
6429 int lineno = 0;
6430 struct line *context = chunk + 1;
6431 const char *markers[] = {
6432 line->type == LINE_DIFF_DEL ? "" : ",0",
6433 line->type == LINE_DIFF_DEL ? ",0" : "",
6436 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6438 while (context < line) {
6439 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6440 break;
6441 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6442 lineno++;
6444 context++;
6447 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6448 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6449 lineno, markers[0], lineno, markers[1]) ||
6450 !stage_diff_write(&io, line, line + 1)) {
6451 chunk = NULL;
6453 } else {
6454 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6455 !stage_diff_write(&io, chunk, view->line + view->lines))
6456 chunk = NULL;
6459 io_done(&io);
6460 io_run_bg(update_index_argv);
6462 return chunk ? TRUE : FALSE;
6465 static bool
6466 stage_update(struct view *view, struct line *line, bool single)
6468 struct line *chunk = NULL;
6470 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6471 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6473 if (chunk) {
6474 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6475 report("Failed to apply chunk");
6476 return FALSE;
6479 } else if (!stage_status.status) {
6480 view = view->parent;
6482 for (line = view->line; view_has_line(view, line); line++)
6483 if (line->type == stage_line_type)
6484 break;
6486 if (!status_update_files(view, line + 1)) {
6487 report("Failed to update files");
6488 return FALSE;
6491 } else if (!status_update_file(&stage_status, stage_line_type)) {
6492 report("Failed to update file");
6493 return FALSE;
6496 return TRUE;
6499 static bool
6500 stage_revert(struct view *view, struct line *line)
6502 struct line *chunk = NULL;
6504 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6505 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6507 if (chunk) {
6508 if (!prompt_yesno("Are you sure you want to revert changes?"))
6509 return FALSE;
6511 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6512 report("Failed to revert chunk");
6513 return FALSE;
6515 return TRUE;
6517 } else {
6518 return status_revert(stage_status.status ? &stage_status : NULL,
6519 stage_line_type, FALSE);
6524 static void
6525 stage_next(struct view *view, struct line *line)
6527 struct stage_state *state = view->private;
6528 int i;
6530 if (!state->chunks) {
6531 for (line = view->line; view_has_line(view, line); line++) {
6532 if (line->type != LINE_DIFF_CHUNK)
6533 continue;
6535 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6536 report("Allocation failure");
6537 return;
6540 state->chunk[state->chunks++] = line - view->line;
6544 for (i = 0; i < state->chunks; i++) {
6545 if (state->chunk[i] > view->pos.lineno) {
6546 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6547 report("Chunk %d of %d", i + 1, state->chunks);
6548 return;
6552 report("No next chunk found");
6555 static enum request
6556 stage_request(struct view *view, enum request request, struct line *line)
6558 switch (request) {
6559 case REQ_STATUS_UPDATE:
6560 if (!stage_update(view, line, FALSE))
6561 return REQ_NONE;
6562 break;
6564 case REQ_STATUS_REVERT:
6565 if (!stage_revert(view, line))
6566 return REQ_NONE;
6567 break;
6569 case REQ_STAGE_UPDATE_LINE:
6570 if (stage_line_type == LINE_STAT_UNTRACKED ||
6571 stage_status.status == 'A') {
6572 report("Staging single lines is not supported for new files");
6573 return REQ_NONE;
6575 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6576 report("Please select a change to stage");
6577 return REQ_NONE;
6579 if (!stage_update(view, line, TRUE))
6580 return REQ_NONE;
6581 break;
6583 case REQ_STAGE_NEXT:
6584 if (stage_line_type == LINE_STAT_UNTRACKED) {
6585 report("File is untracked; press %s to add",
6586 get_view_key(view, REQ_STATUS_UPDATE));
6587 return REQ_NONE;
6589 stage_next(view, line);
6590 return REQ_NONE;
6592 case REQ_EDIT:
6593 if (!stage_status.new.name[0])
6594 return request;
6595 if (stage_status.status == 'D') {
6596 report("File has been deleted.");
6597 return REQ_NONE;
6600 open_editor(stage_status.new.name);
6601 break;
6603 case REQ_REFRESH:
6604 /* Reload everything ... */
6605 break;
6607 case REQ_VIEW_BLAME:
6608 if (stage_status.new.name[0]) {
6609 string_copy(opt_file, stage_status.new.name);
6610 opt_ref[0] = 0;
6612 return request;
6614 case REQ_ENTER:
6615 return diff_common_enter(view, request, line);
6617 case REQ_DIFF_CONTEXT_UP:
6618 case REQ_DIFF_CONTEXT_DOWN:
6619 if (!update_diff_context(request))
6620 return REQ_NONE;
6621 break;
6623 default:
6624 return request;
6627 refresh_view(view->parent);
6629 /* Check whether the staged entry still exists, and close the
6630 * stage view if it doesn't. */
6631 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6632 status_restore(view->parent);
6633 return REQ_VIEW_CLOSE;
6636 refresh_view(view);
6638 return REQ_NONE;
6641 static bool
6642 stage_open(struct view *view, enum open_flags flags)
6644 static const char *no_head_diff_argv[] = {
6645 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6646 stage_status.new.name)
6648 static const char *index_show_argv[] = {
6649 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6650 stage_status.old.name, stage_status.new.name)
6652 static const char *files_show_argv[] = {
6653 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6654 stage_status.old.name, stage_status.new.name)
6656 /* Diffs for unmerged entries are empty when passing the new
6657 * path, so leave out the new path. */
6658 static const char *files_unmerged_argv[] = {
6659 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6660 opt_diff_context_arg, opt_ignore_space_arg, "--",
6661 stage_status.old.name, NULL
6663 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6664 const char **argv = NULL;
6665 const char *info;
6667 if (!stage_line_type) {
6668 report("No stage content, press %s to open the status view and choose file",
6669 get_view_key(view, REQ_VIEW_STATUS));
6670 return FALSE;
6673 view->encoding = NULL;
6675 switch (stage_line_type) {
6676 case LINE_STAT_STAGED:
6677 if (is_initial_commit()) {
6678 argv = no_head_diff_argv;
6679 } else {
6680 argv = index_show_argv;
6682 if (stage_status.status)
6683 info = "Staged changes to %s";
6684 else
6685 info = "Staged changes";
6686 break;
6688 case LINE_STAT_UNSTAGED:
6689 if (stage_status.status != 'U')
6690 argv = files_show_argv;
6691 else
6692 argv = files_unmerged_argv;
6693 if (stage_status.status)
6694 info = "Unstaged changes to %s";
6695 else
6696 info = "Unstaged changes";
6697 break;
6699 case LINE_STAT_UNTRACKED:
6700 info = "Untracked file %s";
6701 argv = file_argv;
6702 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6703 break;
6705 case LINE_STAT_HEAD:
6706 default:
6707 die("line type %d not handled in switch", stage_line_type);
6710 if (!string_format(view->ref, info, stage_status.new.name)
6711 || !argv_copy(&view->argv, argv)) {
6712 report("Failed to open staged view");
6713 return FALSE;
6716 view->vid[0] = 0;
6717 view->dir = opt_cdup;
6718 return begin_update(view, NULL, NULL, flags);
6721 static bool
6722 stage_read(struct view *view, char *data)
6724 struct stage_state *state = view->private;
6726 if (data && diff_common_read(view, data, &state->diff))
6727 return TRUE;
6729 return pager_read(view, data);
6732 static struct view_ops stage_ops = {
6733 "line",
6734 { "stage" },
6735 VIEW_DIFF_LIKE,
6736 sizeof(struct stage_state),
6737 stage_open,
6738 stage_read,
6739 diff_common_draw,
6740 stage_request,
6741 pager_grep,
6742 pager_select,
6747 * Revision graph
6750 static const enum line_type graph_colors[] = {
6751 LINE_PALETTE_0,
6752 LINE_PALETTE_1,
6753 LINE_PALETTE_2,
6754 LINE_PALETTE_3,
6755 LINE_PALETTE_4,
6756 LINE_PALETTE_5,
6757 LINE_PALETTE_6,
6760 static enum line_type get_graph_color(struct graph_symbol *symbol)
6762 if (symbol->commit)
6763 return LINE_GRAPH_COMMIT;
6764 assert(symbol->color < ARRAY_SIZE(graph_colors));
6765 return graph_colors[symbol->color];
6768 static bool
6769 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6771 const char *chars = graph_symbol_to_utf8(symbol);
6773 return draw_text(view, color, chars + !!first);
6776 static bool
6777 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6779 const char *chars = graph_symbol_to_ascii(symbol);
6781 return draw_text(view, color, chars + !!first);
6784 static bool
6785 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6787 const chtype *chars = graph_symbol_to_chtype(symbol);
6789 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6792 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6794 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6796 static const draw_graph_fn fns[] = {
6797 draw_graph_ascii,
6798 draw_graph_chtype,
6799 draw_graph_utf8
6801 draw_graph_fn fn = fns[opt_line_graphics];
6802 int i;
6804 for (i = 0; i < canvas->size; i++) {
6805 struct graph_symbol *symbol = &canvas->symbols[i];
6806 enum line_type color = get_graph_color(symbol);
6808 if (fn(view, symbol, color, i == 0))
6809 return TRUE;
6812 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6816 * Main view backend
6819 struct commit {
6820 char id[SIZEOF_REV]; /* SHA1 ID. */
6821 char title[128]; /* First line of the commit message. */
6822 const char *author; /* Author of the commit. */
6823 struct time time; /* Date from the author ident. */
6824 struct ref_list *refs; /* Repository references. */
6825 struct graph_canvas graph; /* Ancestry chain graphics. */
6828 static struct commit *
6829 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6831 struct graph *graph = view->private;
6832 struct commit *commit;
6834 commit = calloc(1, sizeof(struct commit));
6835 if (!commit)
6836 return NULL;
6838 string_copy_rev(commit->id, ids);
6839 commit->refs = get_ref_list(commit->id);
6840 add_line_data(view, commit, type);
6841 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6842 return commit;
6845 bool
6846 main_has_changes(const char *argv[])
6848 struct io io;
6850 if (!io_run(&io, IO_BG, NULL, argv, -1))
6851 return FALSE;
6852 io_done(&io);
6853 return io.status == 1;
6856 static void
6857 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6859 char ids[SIZEOF_STR] = NULL_ID " ";
6860 struct graph *graph = view->private;
6861 struct commit *commit;
6862 struct timeval now;
6863 struct timezone tz;
6865 if (!parent)
6866 return;
6868 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6870 commit = main_add_commit(view, type, ids, FALSE);
6871 if (!commit)
6872 return;
6874 view->lineoffset++;
6875 if (!gettimeofday(&now, &tz)) {
6876 commit->time.tz = tz.tz_minuteswest * 60;
6877 commit->time.sec = now.tv_sec - commit->time.tz;
6880 commit->author = "";
6881 string_ncopy(commit->title, title, strlen(title));
6882 graph_render_parents(graph);
6885 static void
6886 main_add_changes_commits(struct view *view, const char *parent)
6888 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6889 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6890 const char *staged_parent = NULL_ID;
6891 const char *unstaged_parent = parent;
6893 io_run_bg(update_index_argv);
6895 if (!main_has_changes(unstaged_argv)) {
6896 unstaged_parent = NULL;
6897 staged_parent = parent;
6900 if (!main_has_changes(staged_argv)) {
6901 staged_parent = NULL;
6904 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6905 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6908 static bool
6909 main_open(struct view *view, enum open_flags flags)
6911 static const char *main_argv[] = {
6912 GIT_MAIN_LOG("%(diffargs)", "%(revargs)", "%(fileargs)")
6915 return begin_update(view, NULL, main_argv, flags);
6918 static bool
6919 main_draw(struct view *view, struct line *line, unsigned int lineno)
6921 struct commit *commit = line->data;
6923 if (!commit->author)
6924 return FALSE;
6926 if (draw_lineno(view, lineno))
6927 return TRUE;
6929 if (draw_date(view, &commit->time))
6930 return TRUE;
6932 if (draw_author(view, commit->author))
6933 return TRUE;
6935 if (opt_rev_graph && draw_graph(view, &commit->graph))
6936 return TRUE;
6938 if (draw_refs(view, commit->refs))
6939 return TRUE;
6941 draw_text(view, LINE_DEFAULT, commit->title);
6942 return TRUE;
6945 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6946 static bool
6947 main_read(struct view *view, char *line)
6949 struct graph *graph = view->private;
6950 enum line_type type;
6951 struct commit *commit;
6952 static bool in_header;
6954 if (!line) {
6955 if (!view->lines && !view->prev)
6956 die("No revisions match the given arguments.");
6957 if (view->lines > 0) {
6958 commit = view->line[view->lines - 1].data;
6959 view->line[view->lines - 1].dirty = 1;
6960 if (!commit->author) {
6961 view->lines--;
6962 free(commit);
6966 done_graph(graph);
6967 return TRUE;
6970 type = get_line_type(line);
6971 if (type == LINE_COMMIT) {
6972 bool is_boundary;
6974 in_header = TRUE;
6975 line += STRING_SIZE("commit ");
6976 is_boundary = *line == '-';
6977 if (is_boundary || !isalnum(*line))
6978 line++;
6980 if (!view->lines && opt_show_changes && opt_is_inside_work_tree)
6981 main_add_changes_commits(view, line);
6983 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6986 if (!view->lines)
6987 return TRUE;
6988 commit = view->line[view->lines - 1].data;
6990 /* Empty line separates the commit header from the log itself. */
6991 if (*line == '\0')
6992 in_header = FALSE;
6994 switch (type) {
6995 case LINE_PARENT:
6996 if (!graph->has_parents)
6997 graph_add_parent(graph, line + STRING_SIZE("parent "));
6998 break;
7000 case LINE_AUTHOR:
7001 parse_author_line(line + STRING_SIZE("author "),
7002 &commit->author, &commit->time);
7003 graph_render_parents(graph);
7004 break;
7006 default:
7007 /* Fill in the commit title if it has not already been set. */
7008 if (commit->title[0])
7009 break;
7011 /* Skip lines in the commit header. */
7012 if (in_header)
7013 break;
7015 /* Require titles to start with a non-space character at the
7016 * offset used by git log. */
7017 if (strncmp(line, " ", 4))
7018 break;
7019 line += 4;
7020 /* Well, if the title starts with a whitespace character,
7021 * try to be forgiving. Otherwise we end up with no title. */
7022 while (isspace(*line))
7023 line++;
7024 if (*line == '\0')
7025 break;
7026 /* FIXME: More graceful handling of titles; append "..." to
7027 * shortened titles, etc. */
7029 string_expand(commit->title, sizeof(commit->title), line, 1);
7030 view->line[view->lines - 1].dirty = 1;
7033 return TRUE;
7036 static enum request
7037 main_request(struct view *view, enum request request, struct line *line)
7039 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7041 switch (request) {
7042 case REQ_NEXT:
7043 case REQ_PREVIOUS:
7044 if (view_is_displayed(view) && display[0] != view)
7045 return request;
7046 /* Do not pass navigation requests to the branch view
7047 * when the main view is maximized. (GH #38) */
7048 move_view(view, request);
7049 break;
7051 case REQ_ENTER:
7052 if (view_is_displayed(view) && display[0] != view)
7053 maximize_view(view, TRUE);
7055 if (line->type == LINE_STAT_UNSTAGED
7056 || line->type == LINE_STAT_STAGED) {
7057 struct view *diff = VIEW(REQ_VIEW_DIFF);
7058 const char *diff_staged_argv[] = {
7059 GIT_DIFF_STAGED(opt_diff_context_arg,
7060 opt_ignore_space_arg, NULL, NULL)
7062 const char *diff_unstaged_argv[] = {
7063 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
7064 opt_ignore_space_arg, NULL, NULL)
7066 const char **diff_argv = line->type == LINE_STAT_STAGED
7067 ? diff_staged_argv : diff_unstaged_argv;
7069 open_argv(view, diff, diff_argv, NULL, flags);
7070 break;
7073 open_view(view, REQ_VIEW_DIFF, flags);
7074 break;
7075 case REQ_REFRESH:
7076 load_refs();
7077 refresh_view(view);
7078 break;
7080 case REQ_JUMP_COMMIT:
7082 int lineno;
7084 for (lineno = 0; lineno < view->lines; lineno++) {
7085 struct commit *commit = view->line[lineno].data;
7087 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7088 select_view_line(view, lineno);
7089 report("");
7090 return REQ_NONE;
7094 report("Unable to find commit '%s'", opt_search);
7095 break;
7097 default:
7098 return request;
7101 return REQ_NONE;
7104 static bool
7105 grep_refs(struct ref_list *list, regex_t *regex)
7107 regmatch_t pmatch;
7108 size_t i;
7110 if (!opt_show_refs || !list)
7111 return FALSE;
7113 for (i = 0; i < list->size; i++) {
7114 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7115 return TRUE;
7118 return FALSE;
7121 static bool
7122 main_grep(struct view *view, struct line *line)
7124 struct commit *commit = line->data;
7125 const char *text[] = {
7126 commit->title,
7127 mkauthor(commit->author, opt_author_cols, opt_author),
7128 mkdate(&commit->time, opt_date),
7129 NULL
7132 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7135 static void
7136 main_select(struct view *view, struct line *line)
7138 struct commit *commit = line->data;
7140 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7141 string_copy(view->ref, commit->title);
7142 else
7143 string_copy_rev(view->ref, commit->id);
7144 string_copy_rev(ref_commit, commit->id);
7147 static struct view_ops main_ops = {
7148 "commit",
7149 { "main" },
7150 VIEW_NO_FLAGS,
7151 sizeof(struct graph),
7152 main_open,
7153 main_read,
7154 main_draw,
7155 main_request,
7156 main_grep,
7157 main_select,
7162 * Status management
7165 /* Whether or not the curses interface has been initialized. */
7166 static bool cursed = FALSE;
7168 /* Terminal hacks and workarounds. */
7169 static bool use_scroll_redrawwin;
7170 static bool use_scroll_status_wclear;
7172 /* The status window is used for polling keystrokes. */
7173 static WINDOW *status_win;
7175 /* Reading from the prompt? */
7176 static bool input_mode = FALSE;
7178 static bool status_empty = FALSE;
7180 /* Update status and title window. */
7181 static void
7182 report(const char *msg, ...)
7184 struct view *view = display[current_view];
7186 if (input_mode)
7187 return;
7189 if (!view) {
7190 char buf[SIZEOF_STR];
7191 int retval;
7193 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7194 die("%s", buf);
7197 if (!status_empty || *msg) {
7198 va_list args;
7200 va_start(args, msg);
7202 wmove(status_win, 0, 0);
7203 if (view->has_scrolled && use_scroll_status_wclear)
7204 wclear(status_win);
7205 if (*msg) {
7206 vwprintw(status_win, msg, args);
7207 status_empty = FALSE;
7208 } else {
7209 status_empty = TRUE;
7211 wclrtoeol(status_win);
7212 wnoutrefresh(status_win);
7214 va_end(args);
7217 update_view_title(view);
7220 static void
7221 init_display(void)
7223 const char *term;
7224 int x, y;
7226 /* Initialize the curses library */
7227 if (isatty(STDIN_FILENO)) {
7228 cursed = !!initscr();
7229 opt_tty = stdin;
7230 } else {
7231 /* Leave stdin and stdout alone when acting as a pager. */
7232 opt_tty = fopen("/dev/tty", "r+");
7233 if (!opt_tty)
7234 die("Failed to open /dev/tty");
7235 cursed = !!newterm(NULL, opt_tty, opt_tty);
7238 if (!cursed)
7239 die("Failed to initialize curses");
7241 nonl(); /* Disable conversion and detect newlines from input. */
7242 cbreak(); /* Take input chars one at a time, no wait for \n */
7243 noecho(); /* Don't echo input */
7244 leaveok(stdscr, FALSE);
7246 if (has_colors())
7247 init_colors();
7249 getmaxyx(stdscr, y, x);
7250 status_win = newwin(1, x, y - 1, 0);
7251 if (!status_win)
7252 die("Failed to create status window");
7254 /* Enable keyboard mapping */
7255 keypad(status_win, TRUE);
7256 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7258 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7259 set_tabsize(opt_tab_size);
7260 #else
7261 TABSIZE = opt_tab_size;
7262 #endif
7264 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7265 if (term && !strcmp(term, "gnome-terminal")) {
7266 /* In the gnome-terminal-emulator, the message from
7267 * scrolling up one line when impossible followed by
7268 * scrolling down one line causes corruption of the
7269 * status line. This is fixed by calling wclear. */
7270 use_scroll_status_wclear = TRUE;
7271 use_scroll_redrawwin = FALSE;
7273 } else if (term && !strcmp(term, "xrvt-xpm")) {
7274 /* No problems with full optimizations in xrvt-(unicode)
7275 * and aterm. */
7276 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7278 } else {
7279 /* When scrolling in (u)xterm the last line in the
7280 * scrolling direction will update slowly. */
7281 use_scroll_redrawwin = TRUE;
7282 use_scroll_status_wclear = FALSE;
7286 static int
7287 get_input(int prompt_position)
7289 struct view *view;
7290 int i, key, cursor_y, cursor_x;
7292 if (prompt_position)
7293 input_mode = TRUE;
7295 while (TRUE) {
7296 bool loading = FALSE;
7298 foreach_view (view, i) {
7299 update_view(view);
7300 if (view_is_displayed(view) && view->has_scrolled &&
7301 use_scroll_redrawwin)
7302 redrawwin(view->win);
7303 view->has_scrolled = FALSE;
7304 if (view->pipe)
7305 loading = TRUE;
7308 /* Update the cursor position. */
7309 if (prompt_position) {
7310 getbegyx(status_win, cursor_y, cursor_x);
7311 cursor_x = prompt_position;
7312 } else {
7313 view = display[current_view];
7314 getbegyx(view->win, cursor_y, cursor_x);
7315 cursor_x = view->width - 1;
7316 cursor_y += view->pos.lineno - view->pos.offset;
7318 setsyx(cursor_y, cursor_x);
7320 /* Refresh, accept single keystroke of input */
7321 doupdate();
7322 nodelay(status_win, loading);
7323 key = wgetch(status_win);
7325 /* wgetch() with nodelay() enabled returns ERR when
7326 * there's no input. */
7327 if (key == ERR) {
7329 } else if (key == KEY_RESIZE) {
7330 int height, width;
7332 getmaxyx(stdscr, height, width);
7334 wresize(status_win, 1, width);
7335 mvwin(status_win, height - 1, 0);
7336 wnoutrefresh(status_win);
7337 resize_display();
7338 redraw_display(TRUE);
7340 } else {
7341 input_mode = FALSE;
7342 if (key == erasechar())
7343 key = KEY_BACKSPACE;
7344 return key;
7349 static char *
7350 prompt_input(const char *prompt, input_handler handler, void *data)
7352 enum input_status status = INPUT_OK;
7353 static char buf[SIZEOF_STR];
7354 size_t pos = 0;
7356 buf[pos] = 0;
7358 while (status == INPUT_OK || status == INPUT_SKIP) {
7359 int key;
7361 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7362 wclrtoeol(status_win);
7364 key = get_input(pos + 1);
7365 switch (key) {
7366 case KEY_RETURN:
7367 case KEY_ENTER:
7368 case '\n':
7369 status = pos ? INPUT_STOP : INPUT_CANCEL;
7370 break;
7372 case KEY_BACKSPACE:
7373 if (pos > 0)
7374 buf[--pos] = 0;
7375 else
7376 status = INPUT_CANCEL;
7377 break;
7379 case KEY_ESC:
7380 status = INPUT_CANCEL;
7381 break;
7383 default:
7384 if (pos >= sizeof(buf)) {
7385 report("Input string too long");
7386 return NULL;
7389 status = handler(data, buf, key);
7390 if (status == INPUT_OK)
7391 buf[pos++] = (char) key;
7395 /* Clear the status window */
7396 status_empty = FALSE;
7397 report("");
7399 if (status == INPUT_CANCEL)
7400 return NULL;
7402 buf[pos++] = 0;
7404 return buf;
7407 static enum input_status
7408 prompt_yesno_handler(void *data, char *buf, int c)
7410 if (c == 'y' || c == 'Y')
7411 return INPUT_STOP;
7412 if (c == 'n' || c == 'N')
7413 return INPUT_CANCEL;
7414 return INPUT_SKIP;
7417 static bool
7418 prompt_yesno(const char *prompt)
7420 char prompt2[SIZEOF_STR];
7422 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7423 return FALSE;
7425 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7428 static enum input_status
7429 read_prompt_handler(void *data, char *buf, int c)
7431 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7434 static char *
7435 read_prompt(const char *prompt)
7437 return prompt_input(prompt, read_prompt_handler, NULL);
7440 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7442 enum input_status status = INPUT_OK;
7443 int size = 0;
7445 while (items[size].text)
7446 size++;
7448 assert(size > 0);
7450 while (status == INPUT_OK) {
7451 const struct menu_item *item = &items[*selected];
7452 int key;
7453 int i;
7455 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7456 prompt, *selected + 1, size);
7457 if (item->hotkey)
7458 wprintw(status_win, "[%c] ", (char) item->hotkey);
7459 wprintw(status_win, "%s", item->text);
7460 wclrtoeol(status_win);
7462 key = get_input(COLS - 1);
7463 switch (key) {
7464 case KEY_RETURN:
7465 case KEY_ENTER:
7466 case '\n':
7467 status = INPUT_STOP;
7468 break;
7470 case KEY_LEFT:
7471 case KEY_UP:
7472 *selected = *selected - 1;
7473 if (*selected < 0)
7474 *selected = size - 1;
7475 break;
7477 case KEY_RIGHT:
7478 case KEY_DOWN:
7479 *selected = (*selected + 1) % size;
7480 break;
7482 case KEY_ESC:
7483 status = INPUT_CANCEL;
7484 break;
7486 default:
7487 for (i = 0; items[i].text; i++)
7488 if (items[i].hotkey == key) {
7489 *selected = i;
7490 status = INPUT_STOP;
7491 break;
7496 /* Clear the status window */
7497 status_empty = FALSE;
7498 report("");
7500 return status != INPUT_CANCEL;
7504 * Repository properties
7508 static void
7509 set_remote_branch(const char *name, const char *value, size_t valuelen)
7511 if (!strcmp(name, ".remote")) {
7512 string_ncopy(opt_remote, value, valuelen);
7514 } else if (*opt_remote && !strcmp(name, ".merge")) {
7515 size_t from = strlen(opt_remote);
7517 if (!prefixcmp(value, "refs/heads/"))
7518 value += STRING_SIZE("refs/heads/");
7520 if (!string_format_from(opt_remote, &from, "/%s", value))
7521 opt_remote[0] = 0;
7525 static void
7526 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7528 const char *argv[SIZEOF_ARG] = { name, "=" };
7529 int argc = 1 + (cmd == option_set_command);
7530 enum option_code error;
7532 if (!argv_from_string(argv, &argc, value))
7533 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7534 else
7535 error = cmd(argc, argv);
7537 if (error != OPT_OK)
7538 warn("Option 'tig.%s': %s", name, option_errors[error]);
7541 static bool
7542 set_environment_variable(const char *name, const char *value)
7544 size_t len = strlen(name) + 1 + strlen(value) + 1;
7545 char *env = malloc(len);
7547 if (env &&
7548 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7549 putenv(env) == 0)
7550 return TRUE;
7551 free(env);
7552 return FALSE;
7555 static void
7556 set_work_tree(const char *value)
7558 char cwd[SIZEOF_STR];
7560 if (!getcwd(cwd, sizeof(cwd)))
7561 die("Failed to get cwd path: %s", strerror(errno));
7562 if (chdir(opt_git_dir) < 0)
7563 die("Failed to chdir(%s): %s", strerror(errno));
7564 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7565 die("Failed to get git path: %s", strerror(errno));
7566 if (chdir(cwd) < 0)
7567 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7568 if (chdir(value) < 0)
7569 die("Failed to chdir(%s): %s", value, strerror(errno));
7570 if (!getcwd(cwd, sizeof(cwd)))
7571 die("Failed to get cwd path: %s", strerror(errno));
7572 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7573 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7574 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7575 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7576 opt_is_inside_work_tree = TRUE;
7579 static void
7580 parse_git_color_option(enum line_type type, char *value)
7582 struct line_info *info = &line_info[type];
7583 const char *argv[SIZEOF_ARG];
7584 int argc = 0;
7585 bool first_color = TRUE;
7586 int i;
7588 if (!argv_from_string(argv, &argc, value))
7589 return;
7591 info->fg = COLOR_DEFAULT;
7592 info->bg = COLOR_DEFAULT;
7593 info->attr = 0;
7595 for (i = 0; i < argc; i++) {
7596 int attr = 0;
7598 if (set_attribute(&attr, argv[i])) {
7599 info->attr |= attr;
7601 } else if (set_color(&attr, argv[i])) {
7602 if (first_color)
7603 info->fg = attr;
7604 else
7605 info->bg = attr;
7606 first_color = FALSE;
7611 static void
7612 set_git_color_option(const char *name, char *value)
7614 static const struct enum_map color_option_map[] = {
7615 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7616 ENUM_MAP("branch.local", LINE_MAIN_REF),
7617 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7618 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7620 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7621 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7622 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7623 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7624 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7625 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7626 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7628 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7630 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7631 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7632 ENUM_MAP("status.added", LINE_STAT_STAGED),
7633 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7634 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7635 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7638 int type = LINE_NONE;
7640 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7641 parse_git_color_option(type, value);
7645 static int
7646 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7648 if (!strcmp(name, "gui.encoding"))
7649 parse_encoding(&opt_encoding, value, TRUE);
7651 else if (!strcmp(name, "core.editor"))
7652 string_ncopy(opt_editor, value, valuelen);
7654 else if (!strcmp(name, "core.worktree"))
7655 set_work_tree(value);
7657 else if (!prefixcmp(name, "tig.color."))
7658 set_repo_config_option(name + 10, value, option_color_command);
7660 else if (!prefixcmp(name, "tig.bind."))
7661 set_repo_config_option(name + 9, value, option_bind_command);
7663 else if (!prefixcmp(name, "tig."))
7664 set_repo_config_option(name + 4, value, option_set_command);
7666 else if (!prefixcmp(name, "color."))
7667 set_git_color_option(name + STRING_SIZE("color."), value);
7669 else if (*opt_head && !prefixcmp(name, "branch.") &&
7670 !strncmp(name + 7, opt_head, strlen(opt_head)))
7671 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7673 return OK;
7676 static int
7677 load_git_config(void)
7679 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7681 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7684 static int
7685 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7687 if (!opt_git_dir[0]) {
7688 string_ncopy(opt_git_dir, name, namelen);
7690 } else if (opt_is_inside_work_tree == -1) {
7691 /* This can be 3 different values depending on the
7692 * version of git being used. If git-rev-parse does not
7693 * understand --is-inside-work-tree it will simply echo
7694 * the option else either "true" or "false" is printed.
7695 * Default to true for the unknown case. */
7696 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7698 } else if (*name == '.') {
7699 string_ncopy(opt_cdup, name, namelen);
7701 } else {
7702 string_ncopy(opt_prefix, name, namelen);
7705 return OK;
7708 static int
7709 load_repo_info(void)
7711 const char *rev_parse_argv[] = {
7712 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7713 "--show-cdup", "--show-prefix", NULL
7716 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7721 * Main
7724 static const char usage[] =
7725 "tig " TIG_VERSION " (" __DATE__ ")\n"
7726 "\n"
7727 "Usage: tig [options] [revs] [--] [paths]\n"
7728 " or: tig show [options] [revs] [--] [paths]\n"
7729 " or: tig blame [options] [rev] [--] path\n"
7730 " or: tig status\n"
7731 " or: tig < [git command output]\n"
7732 "\n"
7733 "Options:\n"
7734 " +<number> Select line <number> in the first view\n"
7735 " -v, --version Show version and exit\n"
7736 " -h, --help Show help message and exit";
7738 static void __NORETURN
7739 quit(int sig)
7741 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7742 if (cursed)
7743 endwin();
7744 exit(0);
7747 static void __NORETURN
7748 die(const char *err, ...)
7750 va_list args;
7752 endwin();
7754 va_start(args, err);
7755 fputs("tig: ", stderr);
7756 vfprintf(stderr, err, args);
7757 fputs("\n", stderr);
7758 va_end(args);
7760 exit(1);
7763 static void
7764 warn(const char *msg, ...)
7766 va_list args;
7768 va_start(args, msg);
7769 fputs("tig warning: ", stderr);
7770 vfprintf(stderr, msg, args);
7771 fputs("\n", stderr);
7772 va_end(args);
7775 static int
7776 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7778 const char ***filter_args = data;
7780 return argv_append(filter_args, name) ? OK : ERR;
7783 static void
7784 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7786 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7787 const char **all_argv = NULL;
7789 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7790 !argv_append_array(&all_argv, argv) ||
7791 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7792 die("Failed to split arguments");
7793 argv_free(all_argv);
7794 free(all_argv);
7797 static void
7798 filter_options(const char *argv[], bool blame)
7800 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7802 if (blame)
7803 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7804 else
7805 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7807 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7810 static enum request
7811 parse_options(int argc, const char *argv[])
7813 enum request request = REQ_VIEW_MAIN;
7814 const char *subcommand;
7815 bool seen_dashdash = FALSE;
7816 const char **filter_argv = NULL;
7817 int i;
7819 if (!isatty(STDIN_FILENO))
7820 return REQ_VIEW_PAGER;
7822 if (argc <= 1)
7823 return REQ_VIEW_MAIN;
7825 subcommand = argv[1];
7826 if (!strcmp(subcommand, "status")) {
7827 if (argc > 2)
7828 warn("ignoring arguments after `%s'", subcommand);
7829 return REQ_VIEW_STATUS;
7831 } else if (!strcmp(subcommand, "blame")) {
7832 request = REQ_VIEW_BLAME;
7834 } else if (!strcmp(subcommand, "show")) {
7835 request = REQ_VIEW_DIFF;
7837 } else {
7838 subcommand = NULL;
7841 for (i = 1 + !!subcommand; i < argc; i++) {
7842 const char *opt = argv[i];
7844 // stop parsing our options after -- and let rev-parse handle the rest
7845 if (!seen_dashdash) {
7846 if (!strcmp(opt, "--")) {
7847 seen_dashdash = TRUE;
7848 continue;
7850 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7851 printf("tig version %s\n", TIG_VERSION);
7852 quit(0);
7854 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7855 printf("%s\n", usage);
7856 quit(0);
7858 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7859 opt_lineno = atoi(opt + 1);
7860 continue;
7865 if (!argv_append(&filter_argv, opt))
7866 die("command too long");
7869 if (filter_argv)
7870 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7872 /* Finish validating and setting up blame options */
7873 if (request == REQ_VIEW_BLAME) {
7874 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7875 die("invalid number of options to blame\n\n%s", usage);
7877 if (opt_rev_argv) {
7878 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7881 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7884 return request;
7888 main(int argc, const char *argv[])
7890 const char *codeset = ENCODING_UTF8;
7891 enum request request = parse_options(argc, argv);
7892 struct view *view;
7893 int i;
7895 signal(SIGINT, quit);
7896 signal(SIGPIPE, SIG_IGN);
7898 if (setlocale(LC_ALL, "")) {
7899 codeset = nl_langinfo(CODESET);
7902 foreach_view(view, i) {
7903 add_keymap(&view->ops->keymap);
7906 if (load_repo_info() == ERR)
7907 die("Failed to load repo info.");
7909 if (load_options() == ERR)
7910 die("Failed to load user config.");
7912 if (load_git_config() == ERR)
7913 die("Failed to load repo config.");
7915 /* Require a git repository unless when running in pager mode. */
7916 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7917 die("Not a git repository");
7919 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7920 char translit[SIZEOF_STR];
7922 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7923 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7924 else
7925 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7926 if (opt_iconv_out == ICONV_NONE)
7927 die("Failed to initialize character set conversion");
7930 if (load_refs() == ERR)
7931 die("Failed to load refs.");
7933 init_display();
7935 while (view_driver(display[current_view], request)) {
7936 int key = get_input(0);
7938 view = display[current_view];
7939 request = get_keybinding(&view->ops->keymap, key);
7941 /* Some low-level request handling. This keeps access to
7942 * status_win restricted. */
7943 switch (request) {
7944 case REQ_NONE:
7945 report("Unknown key, press %s for help",
7946 get_view_key(view, REQ_VIEW_HELP));
7947 break;
7948 case REQ_PROMPT:
7950 char *cmd = read_prompt(":");
7952 if (cmd && string_isnumber(cmd)) {
7953 int lineno = view->pos.lineno + 1;
7955 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7956 select_view_line(view, lineno - 1);
7957 report("");
7958 } else {
7959 report("Unable to parse '%s' as a line number", cmd);
7961 } else if (cmd && iscommit(cmd)) {
7962 string_ncopy(opt_search, cmd, strlen(cmd));
7964 request = view_request(view, REQ_JUMP_COMMIT);
7965 if (request == REQ_JUMP_COMMIT) {
7966 report("Jumping to commits is not supported by the '%s' view", view->name);
7969 } else if (cmd) {
7970 struct view *next = VIEW(REQ_VIEW_PAGER);
7971 const char *argv[SIZEOF_ARG] = { "git" };
7972 int argc = 1;
7974 /* When running random commands, initially show the
7975 * command in the title. However, it maybe later be
7976 * overwritten if a commit line is selected. */
7977 string_ncopy(next->ref, cmd, strlen(cmd));
7979 if (!argv_from_string(argv, &argc, cmd)) {
7980 report("Too many arguments");
7981 } else if (!format_argv(&next->argv, argv, FALSE)) {
7982 report("Argument formatting failed");
7983 } else {
7984 next->dir = NULL;
7985 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7989 request = REQ_NONE;
7990 break;
7992 case REQ_SEARCH:
7993 case REQ_SEARCH_BACK:
7995 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7996 char *search = read_prompt(prompt);
7998 if (search)
7999 string_ncopy(opt_search, search, strlen(search));
8000 else if (*opt_search)
8001 request = request == REQ_SEARCH ?
8002 REQ_FIND_NEXT :
8003 REQ_FIND_PREV;
8004 else
8005 request = REQ_NONE;
8006 break;
8008 default:
8009 break;
8013 quit(0);
8015 return 0;