Do not show empty trees for staged and unstaged commit entries
[tig.git] / tig.c
blob0d5b1a9cd5b7f4a3f0f5d817f60d352aaa46e54a
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 * 30 * 12 },
84 struct tm tm;
86 if (!date || !time || !time->sec)
87 return "";
89 if (date == DATE_RELATIVE) {
90 struct timeval now;
91 time_t date = time->sec + time->tz;
92 time_t seconds;
93 int i;
95 gettimeofday(&now, NULL);
96 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
97 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
98 if (seconds >= reldate[i].value)
99 continue;
101 seconds /= reldate[i].namelen;
102 if (!string_format(buf, "%ld %s%s %s",
103 seconds, reldate[i].name,
104 seconds > 1 ? "s" : "",
105 now.tv_sec >= date ? "ago" : "ahead"))
106 break;
107 return buf;
111 if (date == DATE_LOCAL) {
112 time_t date = time->sec + time->tz;
113 localtime_r(&date, &tm);
115 else {
116 gmtime_r(&time->sec, &tm);
118 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
122 #define AUTHOR_ENUM(_) \
123 _(AUTHOR, NO), \
124 _(AUTHOR, FULL), \
125 _(AUTHOR, ABBREVIATED)
127 DEFINE_ENUM(author, AUTHOR_ENUM);
129 static const char *
130 get_author_initials(const char *author)
132 static char initials[AUTHOR_COLS * 6 + 1];
133 size_t pos = 0;
134 const char *end = strchr(author, '\0');
136 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
138 memset(initials, 0, sizeof(initials));
139 while (author < end) {
140 unsigned char bytes;
141 size_t i;
143 while (author < end && is_initial_sep(*author))
144 author++;
146 bytes = utf8_char_length(author, end);
147 if (bytes >= sizeof(initials) - 1 - pos)
148 break;
149 while (bytes--) {
150 initials[pos++] = *author++;
153 i = pos;
154 while (author < end && !is_initial_sep(*author)) {
155 bytes = utf8_char_length(author, end);
156 if (bytes >= sizeof(initials) - 1 - i) {
157 while (author < end && !is_initial_sep(*author))
158 author++;
159 break;
161 while (bytes--) {
162 initials[i++] = *author++;
166 initials[i++] = 0;
169 return initials;
172 #define author_trim(cols) (cols == 0 || cols > 5)
174 static const char *
175 mkauthor(const char *text, int cols, enum author author)
177 bool trim = author_trim(cols);
178 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
180 if (author == AUTHOR_NO)
181 return "";
182 if (abbreviate && text)
183 return get_author_initials(text);
184 return text;
187 static const char *
188 mkmode(mode_t mode)
190 if (S_ISDIR(mode))
191 return "drwxr-xr-x";
192 else if (S_ISLNK(mode))
193 return "lrwxrwxrwx";
194 else if (S_ISGITLINK(mode))
195 return "m---------";
196 else if (S_ISREG(mode) && mode & S_IXUSR)
197 return "-rwxr-xr-x";
198 else if (S_ISREG(mode))
199 return "-rw-r--r--";
200 else
201 return "----------";
204 #define FILENAME_ENUM(_) \
205 _(FILENAME, NO), \
206 _(FILENAME, ALWAYS), \
207 _(FILENAME, AUTO)
209 DEFINE_ENUM(filename, FILENAME_ENUM);
211 #define IGNORE_SPACE_ENUM(_) \
212 _(IGNORE_SPACE, NO), \
213 _(IGNORE_SPACE, ALL), \
214 _(IGNORE_SPACE, SOME), \
215 _(IGNORE_SPACE, AT_EOL)
217 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
219 #define COMMIT_ORDER_ENUM(_) \
220 _(COMMIT_ORDER, DEFAULT), \
221 _(COMMIT_ORDER, TOPO), \
222 _(COMMIT_ORDER, DATE), \
223 _(COMMIT_ORDER, REVERSE)
225 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
227 #define VIEW_INFO(_) \
228 _(MAIN, main, ref_head), \
229 _(DIFF, diff, ref_commit), \
230 _(LOG, log, ref_head), \
231 _(TREE, tree, ref_commit), \
232 _(BLOB, blob, ref_blob), \
233 _(BLAME, blame, ref_commit), \
234 _(BRANCH, branch, ref_head), \
235 _(HELP, help, ""), \
236 _(PAGER, pager, ""), \
237 _(STATUS, status, "status"), \
238 _(STAGE, stage, "stage")
240 static struct encoding *
241 get_path_encoding(const char *path, struct encoding *default_encoding)
243 const char *check_attr_argv[] = {
244 "git", "check-attr", "encoding", "--", path, NULL
246 char buf[SIZEOF_STR];
247 char *encoding;
249 /* <path>: encoding: <encoding> */
251 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
252 || !(encoding = strstr(buf, ENCODING_SEP)))
253 return default_encoding;
255 encoding += STRING_SIZE(ENCODING_SEP);
256 if (!strcmp(encoding, ENCODING_UTF8)
257 || !strcmp(encoding, "unspecified")
258 || !strcmp(encoding, "set"))
259 return default_encoding;
261 return encoding_open(encoding);
265 * User requests
268 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
270 #define REQ_INFO \
271 REQ_GROUP("View switching") \
272 VIEW_INFO(VIEW_REQ), \
274 REQ_GROUP("View manipulation") \
275 REQ_(ENTER, "Enter current line and scroll"), \
276 REQ_(NEXT, "Move to next"), \
277 REQ_(PREVIOUS, "Move to previous"), \
278 REQ_(PARENT, "Move to parent"), \
279 REQ_(VIEW_NEXT, "Move focus to next view"), \
280 REQ_(REFRESH, "Reload and refresh"), \
281 REQ_(MAXIMIZE, "Maximize the current view"), \
282 REQ_(VIEW_CLOSE, "Close the current view"), \
283 REQ_(QUIT, "Close all views and quit"), \
285 REQ_GROUP("View specific requests") \
286 REQ_(STATUS_UPDATE, "Update file status"), \
287 REQ_(STATUS_REVERT, "Revert file changes"), \
288 REQ_(STATUS_MERGE, "Merge file using external tool"), \
289 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
290 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
291 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
292 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
294 REQ_GROUP("Cursor navigation") \
295 REQ_(MOVE_UP, "Move cursor one line up"), \
296 REQ_(MOVE_DOWN, "Move cursor one line down"), \
297 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
298 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
299 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
300 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
302 REQ_GROUP("Scrolling") \
303 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
304 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
305 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
306 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
307 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
308 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
309 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
311 REQ_GROUP("Searching") \
312 REQ_(SEARCH, "Search the view"), \
313 REQ_(SEARCH_BACK, "Search backwards in the view"), \
314 REQ_(FIND_NEXT, "Find next search match"), \
315 REQ_(FIND_PREV, "Find previous search match"), \
317 REQ_GROUP("Option manipulation") \
318 REQ_(OPTIONS, "Open option menu"), \
319 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
320 REQ_(TOGGLE_DATE, "Toggle date display"), \
321 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
322 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
323 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
324 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
325 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
326 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
327 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
328 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
329 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
330 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
332 REQ_GROUP("Misc") \
333 REQ_(PROMPT, "Bring up the prompt"), \
334 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
335 REQ_(SHOW_VERSION, "Show version information"), \
336 REQ_(STOP_LOADING, "Stop all loading views"), \
337 REQ_(EDIT, "Open in editor"), \
338 REQ_(NONE, "Do nothing")
341 /* User action requests. */
342 enum request {
343 #define REQ_GROUP(help)
344 #define REQ_(req, help) REQ_##req
346 /* Offset all requests to avoid conflicts with ncurses getch values. */
347 REQ_UNKNOWN = KEY_MAX + 1,
348 REQ_OFFSET,
349 REQ_INFO,
351 /* Internal requests. */
352 REQ_JUMP_COMMIT,
354 #undef REQ_GROUP
355 #undef REQ_
358 struct request_info {
359 enum request request;
360 const char *name;
361 int namelen;
362 const char *help;
365 static const struct request_info req_info[] = {
366 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
367 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
368 REQ_INFO
369 #undef REQ_GROUP
370 #undef REQ_
373 static enum request
374 get_request(const char *name)
376 int namelen = strlen(name);
377 int i;
379 for (i = 0; i < ARRAY_SIZE(req_info); i++)
380 if (enum_equals(req_info[i], name, namelen))
381 return req_info[i].request;
383 return REQ_UNKNOWN;
388 * Options
391 /* Option and state variables. */
392 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
393 static enum date opt_date = DATE_DEFAULT;
394 static enum author opt_author = AUTHOR_FULL;
395 static enum filename opt_filename = FILENAME_AUTO;
396 static bool opt_rev_graph = TRUE;
397 static bool opt_line_number = FALSE;
398 static bool opt_show_refs = TRUE;
399 static bool opt_show_changes = TRUE;
400 static bool opt_untracked_dirs_content = TRUE;
401 static bool opt_read_git_colors = TRUE;
402 static int opt_diff_context = 3;
403 static char opt_diff_context_arg[9] = "";
404 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
405 static char opt_ignore_space_arg[22] = "";
406 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
407 static char opt_commit_order_arg[22] = "";
408 static bool opt_notes = TRUE;
409 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
410 static int opt_num_interval = 5;
411 static double opt_hscroll = 0.50;
412 static double opt_scale_split_view = 2.0 / 3.0;
413 static int opt_tab_size = 8;
414 static int opt_author_cols = AUTHOR_COLS;
415 static int opt_filename_cols = FILENAME_COLS;
416 static char opt_path[SIZEOF_STR] = "";
417 static char opt_file[SIZEOF_STR] = "";
418 static char opt_ref[SIZEOF_REF] = "";
419 static unsigned long opt_goto_line = 0;
420 static char opt_head[SIZEOF_REF] = "";
421 static char opt_remote[SIZEOF_REF] = "";
422 static struct encoding *opt_encoding = NULL;
423 static iconv_t opt_iconv_out = ICONV_NONE;
424 static char opt_search[SIZEOF_STR] = "";
425 static char opt_cdup[SIZEOF_STR] = "";
426 static char opt_prefix[SIZEOF_STR] = "";
427 static char opt_git_dir[SIZEOF_STR] = "";
428 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
429 static char opt_editor[SIZEOF_STR] = "";
430 static FILE *opt_tty = NULL;
431 static const char **opt_diff_argv = NULL;
432 static const char **opt_rev_argv = NULL;
433 static const char **opt_file_argv = NULL;
434 static const char **opt_blame_argv = NULL;
435 static int opt_lineno = 0;
437 #define is_initial_commit() (!get_ref_head())
438 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
439 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
441 static inline void
442 update_diff_context_arg(int diff_context)
444 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
445 string_ncopy(opt_diff_context_arg, "-U3", 3);
448 static inline void
449 update_ignore_space_arg()
451 if (opt_ignore_space == IGNORE_SPACE_ALL) {
452 string_copy(opt_ignore_space_arg, "--ignore-all-space");
453 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
454 string_copy(opt_ignore_space_arg, "--ignore-space-change");
455 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
456 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
457 } else {
458 string_copy(opt_ignore_space_arg, "");
462 static inline void
463 update_commit_order_arg()
465 if (opt_commit_order == COMMIT_ORDER_TOPO) {
466 string_copy(opt_commit_order_arg, "--topo-order");
467 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
468 string_copy(opt_commit_order_arg, "--date-order");
469 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
470 string_copy(opt_commit_order_arg, "--reverse");
471 } else {
472 string_copy(opt_commit_order_arg, "");
476 static inline void
477 update_notes_arg()
479 if (opt_notes) {
480 string_copy(opt_notes_arg, "--show-notes");
481 } else {
482 /* Notes are disabled by default when passing --pretty args. */
483 string_copy(opt_notes_arg, "");
488 * Line-oriented content detection.
491 #define LINE_INFO \
492 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
493 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
494 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
495 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
496 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
497 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
498 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
499 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
500 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
506 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
507 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
508 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
509 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
510 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
511 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
512 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
515 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
516 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
517 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
518 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
519 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
520 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
521 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
525 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
526 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
527 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
528 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
529 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
530 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
531 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
532 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
533 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
534 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
535 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
536 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
537 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
538 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
539 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
540 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
541 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
542 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
543 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
544 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
545 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
546 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
547 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
548 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
549 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
550 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
551 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
553 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
554 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
555 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
556 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
557 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
558 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
559 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
560 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
561 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
562 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
563 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
565 enum line_type {
566 #define LINE(type, line, fg, bg, attr) \
567 LINE_##type
568 LINE_INFO,
569 LINE_NONE
570 #undef LINE
573 struct line_info {
574 const char *name; /* Option name. */
575 int namelen; /* Size of option name. */
576 const char *line; /* The start of line to match. */
577 int linelen; /* Size of string to match. */
578 int fg, bg, attr; /* Color and text attributes for the lines. */
579 int color_pair;
582 static struct line_info line_info[] = {
583 #define LINE(type, line, fg, bg, attr) \
584 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
585 LINE_INFO
586 #undef LINE
589 static struct line_info **color_pair;
590 static size_t color_pairs;
592 static struct line_info *custom_color;
593 static size_t custom_colors;
595 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
596 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
598 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
599 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
601 /* Color IDs must be 1 or higher. [GH #15] */
602 #define COLOR_ID(line_type) ((line_type) + 1)
604 static enum line_type
605 get_line_type(const char *line)
607 int linelen = strlen(line);
608 enum line_type type;
610 for (type = 0; type < custom_colors; type++)
611 /* Case insensitive search matches Signed-off-by lines better. */
612 if (linelen >= custom_color[type].linelen &&
613 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
614 return TO_CUSTOM_COLOR_TYPE(type);
616 for (type = 0; type < ARRAY_SIZE(line_info); type++)
617 /* Case insensitive search matches Signed-off-by lines better. */
618 if (linelen >= line_info[type].linelen &&
619 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
620 return type;
622 return LINE_DEFAULT;
625 static enum line_type
626 get_line_type_from_ref(const struct ref *ref)
628 if (ref->head)
629 return LINE_MAIN_HEAD;
630 else if (ref->ltag)
631 return LINE_MAIN_LOCAL_TAG;
632 else if (ref->tag)
633 return LINE_MAIN_TAG;
634 else if (ref->tracked)
635 return LINE_MAIN_TRACKED;
636 else if (ref->remote)
637 return LINE_MAIN_REMOTE;
638 else if (ref->replace)
639 return LINE_MAIN_REPLACE;
641 return LINE_MAIN_REF;
644 static inline struct line_info *
645 get_line(enum line_type type)
647 if (type > LINE_NONE) {
648 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
649 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
650 } else {
651 assert(type < ARRAY_SIZE(line_info));
652 return &line_info[type];
656 static inline int
657 get_line_color(enum line_type type)
659 return COLOR_ID(get_line(type)->color_pair);
662 static inline int
663 get_line_attr(enum line_type type)
665 struct line_info *info = get_line(type);
667 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
670 static struct line_info *
671 get_line_info(const char *name)
673 size_t namelen = strlen(name);
674 enum line_type type;
676 for (type = 0; type < ARRAY_SIZE(line_info); type++)
677 if (enum_equals(line_info[type], name, namelen))
678 return &line_info[type];
680 return NULL;
683 static struct line_info *
684 add_custom_color(const char *quoted_line)
686 struct line_info *info;
687 char *line;
688 size_t linelen;
690 if (!realloc_custom_color(&custom_color, custom_colors, 1))
691 die("Failed to alloc custom line info");
693 linelen = strlen(quoted_line) - 1;
694 line = malloc(linelen);
695 if (!line)
696 return NULL;
698 strncpy(line, quoted_line + 1, linelen);
699 line[linelen - 1] = 0;
701 info = &custom_color[custom_colors++];
702 info->name = info->line = line;
703 info->namelen = info->linelen = strlen(line);
705 return info;
708 static void
709 init_line_info_color_pair(struct line_info *info, enum line_type type,
710 int default_bg, int default_fg)
712 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
713 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
714 int i;
716 for (i = 0; i < color_pairs; i++) {
717 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
718 info->color_pair = i;
719 return;
723 if (!realloc_color_pair(&color_pair, color_pairs, 1))
724 die("Failed to alloc color pair");
726 color_pair[color_pairs] = info;
727 info->color_pair = color_pairs++;
728 init_pair(COLOR_ID(info->color_pair), fg, bg);
731 static void
732 init_colors(void)
734 int default_bg = line_info[LINE_DEFAULT].bg;
735 int default_fg = line_info[LINE_DEFAULT].fg;
736 enum line_type type;
738 start_color();
740 if (assume_default_colors(default_fg, default_bg) == ERR) {
741 default_bg = COLOR_BLACK;
742 default_fg = COLOR_WHITE;
745 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
746 struct line_info *info = &line_info[type];
748 init_line_info_color_pair(info, type, default_bg, default_fg);
751 for (type = 0; type < custom_colors; type++) {
752 struct line_info *info = &custom_color[type];
754 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
755 default_bg, default_fg);
759 struct line {
760 enum line_type type;
762 /* State flags */
763 unsigned int selected:1;
764 unsigned int dirty:1;
765 unsigned int cleareol:1;
766 unsigned int dont_free:1;
767 unsigned int other:16;
769 void *data; /* User data */
774 * Keys
777 struct keybinding {
778 int alias;
779 enum request request;
782 static struct keybinding default_keybindings[] = {
783 /* View switching */
784 { 'm', REQ_VIEW_MAIN },
785 { 'd', REQ_VIEW_DIFF },
786 { 'l', REQ_VIEW_LOG },
787 { 't', REQ_VIEW_TREE },
788 { 'f', REQ_VIEW_BLOB },
789 { 'B', REQ_VIEW_BLAME },
790 { 'H', REQ_VIEW_BRANCH },
791 { 'p', REQ_VIEW_PAGER },
792 { 'h', REQ_VIEW_HELP },
793 { 'S', REQ_VIEW_STATUS },
794 { 'c', REQ_VIEW_STAGE },
796 /* View manipulation */
797 { 'q', REQ_VIEW_CLOSE },
798 { KEY_TAB, REQ_VIEW_NEXT },
799 { KEY_RETURN, REQ_ENTER },
800 { KEY_UP, REQ_PREVIOUS },
801 { KEY_CTL('P'), REQ_PREVIOUS },
802 { KEY_DOWN, REQ_NEXT },
803 { KEY_CTL('N'), REQ_NEXT },
804 { 'R', REQ_REFRESH },
805 { KEY_F(5), REQ_REFRESH },
806 { 'O', REQ_MAXIMIZE },
807 { ',', REQ_PARENT },
809 /* View specific */
810 { 'u', REQ_STATUS_UPDATE },
811 { '!', REQ_STATUS_REVERT },
812 { 'M', REQ_STATUS_MERGE },
813 { '1', REQ_STAGE_UPDATE_LINE },
814 { '@', REQ_STAGE_NEXT },
815 { '[', REQ_DIFF_CONTEXT_DOWN },
816 { ']', REQ_DIFF_CONTEXT_UP },
818 /* Cursor navigation */
819 { 'k', REQ_MOVE_UP },
820 { 'j', REQ_MOVE_DOWN },
821 { KEY_HOME, REQ_MOVE_FIRST_LINE },
822 { KEY_END, REQ_MOVE_LAST_LINE },
823 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
824 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
825 { ' ', REQ_MOVE_PAGE_DOWN },
826 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
827 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
828 { 'b', REQ_MOVE_PAGE_UP },
829 { '-', REQ_MOVE_PAGE_UP },
831 /* Scrolling */
832 { '|', REQ_SCROLL_FIRST_COL },
833 { KEY_LEFT, REQ_SCROLL_LEFT },
834 { KEY_RIGHT, REQ_SCROLL_RIGHT },
835 { KEY_IC, REQ_SCROLL_LINE_UP },
836 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
837 { KEY_DC, REQ_SCROLL_LINE_DOWN },
838 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
839 { 'w', REQ_SCROLL_PAGE_UP },
840 { 's', REQ_SCROLL_PAGE_DOWN },
842 /* Searching */
843 { '/', REQ_SEARCH },
844 { '?', REQ_SEARCH_BACK },
845 { 'n', REQ_FIND_NEXT },
846 { 'N', REQ_FIND_PREV },
848 /* Misc */
849 { 'Q', REQ_QUIT },
850 { 'z', REQ_STOP_LOADING },
851 { 'v', REQ_SHOW_VERSION },
852 { 'r', REQ_SCREEN_REDRAW },
853 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
854 { 'o', REQ_OPTIONS },
855 { '.', REQ_TOGGLE_LINENO },
856 { 'D', REQ_TOGGLE_DATE },
857 { 'A', REQ_TOGGLE_AUTHOR },
858 { 'g', REQ_TOGGLE_REV_GRAPH },
859 { '~', REQ_TOGGLE_GRAPHIC },
860 { '#', REQ_TOGGLE_FILENAME },
861 { 'F', REQ_TOGGLE_REFS },
862 { 'I', REQ_TOGGLE_SORT_ORDER },
863 { 'i', REQ_TOGGLE_SORT_FIELD },
864 { 'W', REQ_TOGGLE_IGNORE_SPACE },
865 { ':', REQ_PROMPT },
866 { 'e', REQ_EDIT },
869 struct keymap {
870 const char *name;
871 struct keymap *next;
872 struct keybinding *data;
873 size_t size;
874 bool hidden;
877 static struct keymap generic_keymap = { "generic" };
878 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
880 static struct keymap *keymaps = &generic_keymap;
882 static void
883 add_keymap(struct keymap *keymap)
885 keymap->next = keymaps;
886 keymaps = keymap;
889 static struct keymap *
890 get_keymap(const char *name)
892 struct keymap *keymap = keymaps;
894 while (keymap) {
895 if (!strcasecmp(keymap->name, name))
896 return keymap;
897 keymap = keymap->next;
900 return NULL;
904 static void
905 add_keybinding(struct keymap *table, enum request request, int key)
907 size_t i;
909 for (i = 0; i < table->size; i++) {
910 if (table->data[i].alias == key) {
911 table->data[i].request = request;
912 return;
916 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
917 if (!table->data)
918 die("Failed to allocate keybinding");
919 table->data[table->size].alias = key;
920 table->data[table->size++].request = request;
922 if (request == REQ_NONE && is_generic_keymap(table)) {
923 int i;
925 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
926 if (default_keybindings[i].alias == key)
927 default_keybindings[i].request = REQ_NONE;
931 /* Looks for a key binding first in the given map, then in the generic map, and
932 * lastly in the default keybindings. */
933 static enum request
934 get_keybinding(struct keymap *keymap, int key)
936 size_t i;
938 for (i = 0; i < keymap->size; i++)
939 if (keymap->data[i].alias == key)
940 return keymap->data[i].request;
942 for (i = 0; i < generic_keymap.size; i++)
943 if (generic_keymap.data[i].alias == key)
944 return generic_keymap.data[i].request;
946 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
947 if (default_keybindings[i].alias == key)
948 return default_keybindings[i].request;
950 return (enum request) key;
954 struct key {
955 const char *name;
956 int value;
959 static const struct key key_table[] = {
960 { "Enter", KEY_RETURN },
961 { "Space", ' ' },
962 { "Backspace", KEY_BACKSPACE },
963 { "Tab", KEY_TAB },
964 { "Escape", KEY_ESC },
965 { "Left", KEY_LEFT },
966 { "Right", KEY_RIGHT },
967 { "Up", KEY_UP },
968 { "Down", KEY_DOWN },
969 { "Insert", KEY_IC },
970 { "Delete", KEY_DC },
971 { "Hash", '#' },
972 { "Home", KEY_HOME },
973 { "End", KEY_END },
974 { "PageUp", KEY_PPAGE },
975 { "PageDown", KEY_NPAGE },
976 { "F1", KEY_F(1) },
977 { "F2", KEY_F(2) },
978 { "F3", KEY_F(3) },
979 { "F4", KEY_F(4) },
980 { "F5", KEY_F(5) },
981 { "F6", KEY_F(6) },
982 { "F7", KEY_F(7) },
983 { "F8", KEY_F(8) },
984 { "F9", KEY_F(9) },
985 { "F10", KEY_F(10) },
986 { "F11", KEY_F(11) },
987 { "F12", KEY_F(12) },
990 static int
991 get_key_value(const char *name)
993 int i;
995 for (i = 0; i < ARRAY_SIZE(key_table); i++)
996 if (!strcasecmp(key_table[i].name, name))
997 return key_table[i].value;
999 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1000 return (int)name[1] & 0x1f;
1001 if (strlen(name) == 1 && isprint(*name))
1002 return (int) *name;
1003 return ERR;
1006 static const char *
1007 get_key_name(int key_value)
1009 static char key_char[] = "'X'\0";
1010 const char *seq = NULL;
1011 int key;
1013 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1014 if (key_table[key].value == key_value)
1015 seq = key_table[key].name;
1017 if (seq == NULL && key_value < 0x7f) {
1018 char *s = key_char + 1;
1020 if (key_value >= 0x20) {
1021 *s++ = key_value;
1022 } else {
1023 *s++ = '^';
1024 *s++ = 0x40 | (key_value & 0x1f);
1026 *s++ = '\'';
1027 *s++ = '\0';
1028 seq = key_char;
1031 return seq ? seq : "(no key)";
1034 static bool
1035 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1037 const char *sep = *pos > 0 ? ", " : "";
1038 const char *keyname = get_key_name(keybinding->alias);
1040 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1043 static bool
1044 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1045 struct keymap *keymap, bool all)
1047 int i;
1049 for (i = 0; i < keymap->size; i++) {
1050 if (keymap->data[i].request == request) {
1051 if (!append_key(buf, pos, &keymap->data[i]))
1052 return FALSE;
1053 if (!all)
1054 break;
1058 return TRUE;
1061 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1063 static const char *
1064 get_keys(struct keymap *keymap, enum request request, bool all)
1066 static char buf[BUFSIZ];
1067 size_t pos = 0;
1068 int i;
1070 buf[pos] = 0;
1072 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1073 return "Too many keybindings!";
1074 if (pos > 0 && !all)
1075 return buf;
1077 if (!is_generic_keymap(keymap)) {
1078 /* Only the generic keymap includes the default keybindings when
1079 * listing all keys. */
1080 if (all)
1081 return buf;
1083 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1084 return "Too many keybindings!";
1085 if (pos)
1086 return buf;
1089 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1090 if (default_keybindings[i].request == request) {
1091 if (!append_key(buf, &pos, &default_keybindings[i]))
1092 return "Too many keybindings!";
1093 if (!all)
1094 return buf;
1098 return buf;
1101 struct run_request {
1102 struct keymap *keymap;
1103 int key;
1104 const char **argv;
1105 bool silent;
1108 static struct run_request *run_request;
1109 static size_t run_requests;
1111 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1113 static bool
1114 add_run_request(struct keymap *keymap, int key, const char **argv, bool silent, bool force)
1116 struct run_request *req;
1118 if (!force && get_keybinding(keymap, key) != key)
1119 return TRUE;
1121 if (!realloc_run_requests(&run_request, run_requests, 1))
1122 return FALSE;
1124 if (!argv_copy(&run_request[run_requests].argv, argv))
1125 return FALSE;
1127 req = &run_request[run_requests++];
1128 req->silent = silent;
1129 req->keymap = keymap;
1130 req->key = key;
1132 add_keybinding(keymap, REQ_NONE + run_requests, key);
1133 return TRUE;
1136 static struct run_request *
1137 get_run_request(enum request request)
1139 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1140 return NULL;
1141 return &run_request[request - REQ_NONE - 1];
1144 static void
1145 add_builtin_run_requests(void)
1147 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1148 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1149 const char *commit[] = { "git", "commit", NULL };
1150 const char *gc[] = { "git", "gc", NULL };
1152 add_run_request(get_keymap("main"), 'C', cherry_pick, FALSE, FALSE);
1153 add_run_request(get_keymap("status"), 'C', commit, FALSE, FALSE);
1154 add_run_request(get_keymap("branch"), 'C', checkout, FALSE, FALSE);
1155 add_run_request(get_keymap("generic"), 'G', gc, FALSE, FALSE);
1159 * User config file handling.
1162 #define OPT_ERR_INFO \
1163 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1164 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1165 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1166 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1167 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1168 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1169 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1170 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1171 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1172 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1173 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1174 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1175 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1176 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1177 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1178 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1179 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1180 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1181 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1183 enum option_code {
1184 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1185 OPT_ERR_INFO
1186 #undef OPT_ERR_
1187 OPT_OK
1190 static const char *option_errors[] = {
1191 #define OPT_ERR_(name, msg) msg
1192 OPT_ERR_INFO
1193 #undef OPT_ERR_
1196 static const struct enum_map color_map[] = {
1197 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1198 COLOR_MAP(DEFAULT),
1199 COLOR_MAP(BLACK),
1200 COLOR_MAP(BLUE),
1201 COLOR_MAP(CYAN),
1202 COLOR_MAP(GREEN),
1203 COLOR_MAP(MAGENTA),
1204 COLOR_MAP(RED),
1205 COLOR_MAP(WHITE),
1206 COLOR_MAP(YELLOW),
1209 static const struct enum_map attr_map[] = {
1210 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1211 ATTR_MAP(NORMAL),
1212 ATTR_MAP(BLINK),
1213 ATTR_MAP(BOLD),
1214 ATTR_MAP(DIM),
1215 ATTR_MAP(REVERSE),
1216 ATTR_MAP(STANDOUT),
1217 ATTR_MAP(UNDERLINE),
1220 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1222 static enum option_code
1223 parse_step(double *opt, const char *arg)
1225 *opt = atoi(arg);
1226 if (!strchr(arg, '%'))
1227 return OPT_OK;
1229 /* "Shift down" so 100% and 1 does not conflict. */
1230 *opt = (*opt - 1) / 100;
1231 if (*opt >= 1.0) {
1232 *opt = 0.99;
1233 return OPT_ERR_INVALID_STEP_VALUE;
1235 if (*opt < 0.0) {
1236 *opt = 1;
1237 return OPT_ERR_INVALID_STEP_VALUE;
1239 return OPT_OK;
1242 static enum option_code
1243 parse_int(int *opt, const char *arg, int min, int max)
1245 int value = atoi(arg);
1247 if (min <= value && value <= max) {
1248 *opt = value;
1249 return OPT_OK;
1252 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1255 static bool
1256 set_color(int *color, const char *name)
1258 if (map_enum(color, color_map, name))
1259 return TRUE;
1260 if (!prefixcmp(name, "color"))
1261 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1262 return FALSE;
1265 /* Wants: object fgcolor bgcolor [attribute] */
1266 static enum option_code
1267 option_color_command(int argc, const char *argv[])
1269 struct line_info *info;
1271 if (argc < 3)
1272 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1274 if (*argv[0] == '"' || *argv[0] == '\'') {
1275 info = add_custom_color(argv[0]);
1276 } else {
1277 info = get_line_info(argv[0]);
1279 if (!info) {
1280 static const struct enum_map obsolete[] = {
1281 ENUM_MAP("main-delim", LINE_DELIMITER),
1282 ENUM_MAP("main-date", LINE_DATE),
1283 ENUM_MAP("main-author", LINE_AUTHOR),
1285 int index;
1287 if (!map_enum(&index, obsolete, argv[0]))
1288 return OPT_ERR_UNKNOWN_COLOR_NAME;
1289 info = &line_info[index];
1292 if (!set_color(&info->fg, argv[1]) ||
1293 !set_color(&info->bg, argv[2]))
1294 return OPT_ERR_UNKNOWN_COLOR;
1296 info->attr = 0;
1297 while (argc-- > 3) {
1298 int attr;
1300 if (!set_attribute(&attr, argv[argc]))
1301 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1302 info->attr |= attr;
1305 return OPT_OK;
1308 static enum option_code
1309 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1311 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1312 ? TRUE : FALSE;
1313 if (matched)
1314 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1315 return OPT_OK;
1318 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1320 static enum option_code
1321 parse_enum_do(unsigned int *opt, const char *arg,
1322 const struct enum_map *map, size_t map_size)
1324 bool is_true;
1326 assert(map_size > 1);
1328 if (map_enum_do(map, map_size, (int *) opt, arg))
1329 return OPT_OK;
1331 parse_bool(&is_true, arg);
1332 *opt = is_true ? map[1].value : map[0].value;
1333 return OPT_OK;
1336 #define parse_enum(opt, arg, map) \
1337 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1339 static enum option_code
1340 parse_string(char *opt, const char *arg, size_t optsize)
1342 int arglen = strlen(arg);
1344 switch (arg[0]) {
1345 case '\"':
1346 case '\'':
1347 if (arglen == 1 || arg[arglen - 1] != arg[0])
1348 return OPT_ERR_UNMATCHED_QUOTATION;
1349 arg += 1; arglen -= 2;
1350 default:
1351 string_ncopy_do(opt, optsize, arg, arglen);
1352 return OPT_OK;
1356 static enum option_code
1357 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1359 char buf[SIZEOF_STR];
1360 enum option_code code = parse_string(buf, arg, sizeof(buf));
1362 if (code == OPT_OK) {
1363 struct encoding *encoding = *encoding_ref;
1365 if (encoding && !priority)
1366 return code;
1367 encoding = encoding_open(buf);
1368 if (encoding)
1369 *encoding_ref = encoding;
1372 return code;
1375 static enum option_code
1376 parse_args(const char ***args, const char *argv[])
1378 if (*args == NULL && !argv_copy(args, argv))
1379 return OPT_ERR_OUT_OF_MEMORY;
1380 return OPT_OK;
1383 /* Wants: name = value */
1384 static enum option_code
1385 option_set_command(int argc, const char *argv[])
1387 if (argc < 3)
1388 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1390 if (strcmp(argv[1], "="))
1391 return OPT_ERR_NO_VALUE_ASSIGNED;
1393 if (!strcmp(argv[0], "blame-options"))
1394 return parse_args(&opt_blame_argv, argv + 2);
1396 if (argc != 3)
1397 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1399 if (!strcmp(argv[0], "show-author"))
1400 return parse_enum(&opt_author, argv[2], author_map);
1402 if (!strcmp(argv[0], "show-date"))
1403 return parse_enum(&opt_date, argv[2], date_map);
1405 if (!strcmp(argv[0], "show-rev-graph"))
1406 return parse_bool(&opt_rev_graph, argv[2]);
1408 if (!strcmp(argv[0], "show-refs"))
1409 return parse_bool(&opt_show_refs, argv[2]);
1411 if (!strcmp(argv[0], "show-changes"))
1412 return parse_bool(&opt_show_changes, argv[2]);
1414 if (!strcmp(argv[0], "show-notes")) {
1415 bool matched = FALSE;
1416 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1418 if (res == OPT_OK && matched) {
1419 update_notes_arg();
1420 return res;
1423 opt_notes = TRUE;
1424 strcpy(opt_notes_arg, "--show-notes=");
1425 res = parse_string(opt_notes_arg + 8, argv[2],
1426 sizeof(opt_notes_arg) - 8);
1427 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1428 opt_notes_arg[7] = '\0';
1429 return res;
1432 if (!strcmp(argv[0], "show-line-numbers"))
1433 return parse_bool(&opt_line_number, argv[2]);
1435 if (!strcmp(argv[0], "line-graphics"))
1436 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1438 if (!strcmp(argv[0], "line-number-interval"))
1439 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1441 if (!strcmp(argv[0], "author-width"))
1442 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1444 if (!strcmp(argv[0], "filename-width"))
1445 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1447 if (!strcmp(argv[0], "show-filename"))
1448 return parse_enum(&opt_filename, argv[2], filename_map);
1450 if (!strcmp(argv[0], "horizontal-scroll"))
1451 return parse_step(&opt_hscroll, argv[2]);
1453 if (!strcmp(argv[0], "split-view-height"))
1454 return parse_step(&opt_scale_split_view, argv[2]);
1456 if (!strcmp(argv[0], "tab-size"))
1457 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1459 if (!strcmp(argv[0], "diff-context")) {
1460 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1462 if (code == OPT_OK)
1463 update_diff_context_arg(opt_diff_context);
1464 return code;
1467 if (!strcmp(argv[0], "ignore-space")) {
1468 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1470 if (code == OPT_OK)
1471 update_ignore_space_arg();
1472 return code;
1475 if (!strcmp(argv[0], "commit-order")) {
1476 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1478 if (code == OPT_OK)
1479 update_commit_order_arg();
1480 return code;
1483 if (!strcmp(argv[0], "status-untracked-dirs"))
1484 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1486 if (!strcmp(argv[0], "use-git-colors"))
1487 return parse_bool(&opt_read_git_colors, argv[2]);
1489 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1492 /* Wants: mode request key */
1493 static enum option_code
1494 option_bind_command(int argc, const char *argv[])
1496 enum request request;
1497 struct keymap *keymap;
1498 int key;
1500 if (argc < 3)
1501 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1503 if (!(keymap = get_keymap(argv[0])))
1504 return OPT_ERR_UNKNOWN_KEY_MAP;
1506 key = get_key_value(argv[1]);
1507 if (key == ERR)
1508 return OPT_ERR_UNKNOWN_KEY;
1510 request = get_request(argv[2]);
1511 if (request == REQ_UNKNOWN) {
1512 static const struct enum_map obsolete[] = {
1513 ENUM_MAP("cherry-pick", REQ_NONE),
1514 ENUM_MAP("screen-resize", REQ_NONE),
1515 ENUM_MAP("tree-parent", REQ_PARENT),
1517 int alias;
1519 if (map_enum(&alias, obsolete, argv[2])) {
1520 if (alias != REQ_NONE)
1521 add_keybinding(keymap, alias, key);
1522 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1525 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1526 bool silent = *argv[2] == '@';
1528 if (silent)
1529 argv[2]++;
1530 return add_run_request(keymap, key, argv + 2, silent, TRUE)
1531 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1533 if (request == REQ_UNKNOWN)
1534 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1536 add_keybinding(keymap, request, key);
1538 return OPT_OK;
1542 static enum option_code load_option_file(const char *path);
1544 static enum option_code
1545 option_source_command(int argc, const char *argv[])
1547 if (argc < 1)
1548 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1550 return load_option_file(argv[0]);
1553 static enum option_code
1554 set_option(const char *opt, char *value)
1556 const char *argv[SIZEOF_ARG];
1557 int argc = 0;
1559 if (!argv_from_string(argv, &argc, value))
1560 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1562 if (!strcmp(opt, "color"))
1563 return option_color_command(argc, argv);
1565 if (!strcmp(opt, "set"))
1566 return option_set_command(argc, argv);
1568 if (!strcmp(opt, "bind"))
1569 return option_bind_command(argc, argv);
1571 if (!strcmp(opt, "source"))
1572 return option_source_command(argc, argv);
1574 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1577 struct config_state {
1578 const char *path;
1579 int lineno;
1580 bool errors;
1583 static int
1584 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1586 struct config_state *config = data;
1587 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1589 config->lineno++;
1591 /* Check for comment markers, since read_properties() will
1592 * only ensure opt and value are split at first " \t". */
1593 optlen = strcspn(opt, "#");
1594 if (optlen == 0)
1595 return OK;
1597 if (opt[optlen] == 0) {
1598 /* Look for comment endings in the value. */
1599 size_t len = strcspn(value, "#");
1601 if (len < valuelen) {
1602 valuelen = len;
1603 value[valuelen] = 0;
1606 status = set_option(opt, value);
1609 if (status != OPT_OK) {
1610 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1611 option_errors[status], (int) optlen, opt);
1612 config->errors = TRUE;
1615 /* Always keep going if errors are encountered. */
1616 return OK;
1619 static enum option_code
1620 load_option_file(const char *path)
1622 struct config_state config = { path, 0, FALSE };
1623 struct io io;
1625 /* Do not read configuration from stdin if set to "" */
1626 if (!path || !strlen(path))
1627 return OPT_OK;
1629 /* It's OK that the file doesn't exist. */
1630 if (!io_open(&io, "%s", path))
1631 return OPT_ERR_FILE_DOES_NOT_EXIST;
1633 if (io_load(&io, " \t", read_option, &config) == ERR ||
1634 config.errors == TRUE)
1635 warn("Errors while loading %s.", path);
1636 return OPT_OK;
1639 static int
1640 load_options(void)
1642 const char *home = getenv("HOME");
1643 const char *tigrc_user = getenv("TIGRC_USER");
1644 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1645 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1646 char buf[SIZEOF_STR];
1648 if (!tigrc_system)
1649 tigrc_system = SYSCONFDIR "/tigrc";
1650 load_option_file(tigrc_system);
1652 if (!tigrc_user) {
1653 if (!home || !string_format(buf, "%s/.tigrc", home))
1654 return ERR;
1655 tigrc_user = buf;
1657 load_option_file(tigrc_user);
1659 /* Add _after_ loading config files to avoid adding run requests
1660 * that conflict with keybindings. */
1661 add_builtin_run_requests();
1663 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1664 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1665 int argc = 0;
1667 if (!string_format(buf, "%s", tig_diff_opts) ||
1668 !argv_from_string(diff_opts, &argc, buf))
1669 die("TIG_DIFF_OPTS contains too many arguments");
1670 else if (!argv_copy(&opt_diff_argv, diff_opts))
1671 die("Failed to format TIG_DIFF_OPTS arguments");
1674 return OK;
1679 * The viewer
1682 struct view;
1683 struct view_ops;
1685 /* The display array of active views and the index of the current view. */
1686 static struct view *display[2];
1687 static WINDOW *display_win[2];
1688 static WINDOW *display_title[2];
1689 static unsigned int current_view;
1691 #define foreach_displayed_view(view, i) \
1692 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1694 #define displayed_views() (display[1] != NULL ? 2 : 1)
1696 /* Current head and commit ID */
1697 static char ref_blob[SIZEOF_REF] = "";
1698 static char ref_commit[SIZEOF_REF] = "HEAD";
1699 static char ref_head[SIZEOF_REF] = "HEAD";
1700 static char ref_branch[SIZEOF_REF] = "";
1702 enum view_flag {
1703 VIEW_NO_FLAGS = 0,
1704 VIEW_ALWAYS_LINENO = 1 << 0,
1705 VIEW_CUSTOM_STATUS = 1 << 1,
1706 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1707 VIEW_ADD_PAGER_REFS = 1 << 3,
1708 VIEW_OPEN_DIFF = 1 << 4,
1709 VIEW_NO_REF = 1 << 5,
1710 VIEW_NO_GIT_DIR = 1 << 6,
1711 VIEW_DIFF_LIKE = 1 << 7,
1714 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1716 struct position {
1717 unsigned long offset; /* Offset of the window top */
1718 unsigned long col; /* Offset from the window side. */
1719 unsigned long lineno; /* Current line number */
1722 struct view {
1723 const char *name; /* View name */
1724 const char *id; /* Points to either of ref_{head,commit,blob} */
1726 struct view_ops *ops; /* View operations */
1728 char ref[SIZEOF_REF]; /* Hovered commit reference */
1729 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1731 int height, width; /* The width and height of the main window */
1732 WINDOW *win; /* The main window */
1734 /* Navigation */
1735 struct position pos; /* Current position. */
1736 struct position prev_pos; /* Previous position. */
1738 /* Searching */
1739 char grep[SIZEOF_STR]; /* Search string */
1740 regex_t *regex; /* Pre-compiled regexp */
1742 /* If non-NULL, points to the view that opened this view. If this view
1743 * is closed tig will switch back to the parent view. */
1744 struct view *parent;
1745 struct view *prev;
1747 /* Buffering */
1748 size_t lines; /* Total number of lines */
1749 struct line *line; /* Line index */
1750 unsigned int digits; /* Number of digits in the lines member. */
1752 /* Drawing */
1753 struct line *curline; /* Line currently being drawn. */
1754 enum line_type curtype; /* Attribute currently used for drawing. */
1755 unsigned long col; /* Column when drawing. */
1756 bool has_scrolled; /* View was scrolled. */
1758 /* Loading */
1759 const char **argv; /* Shell command arguments. */
1760 const char *dir; /* Directory from which to execute. */
1761 struct io io;
1762 struct io *pipe;
1763 time_t start_time;
1764 time_t update_secs;
1765 struct encoding *encoding;
1767 /* Private data */
1768 void *private;
1771 enum open_flags {
1772 OPEN_DEFAULT = 0, /* Use default view switching. */
1773 OPEN_SPLIT = 1, /* Split current view. */
1774 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1775 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1776 OPEN_PREPARED = 32, /* Open already prepared command. */
1777 OPEN_EXTRA = 64, /* Open extra data from command. */
1780 struct view_ops {
1781 /* What type of content being displayed. Used in the title bar. */
1782 const char *type;
1783 /* What keymap does this view have */
1784 struct keymap keymap;
1785 /* Flags to control the view behavior. */
1786 enum view_flag flags;
1787 /* Size of private data. */
1788 size_t private_size;
1789 /* Open and reads in all view content. */
1790 bool (*open)(struct view *view, enum open_flags flags);
1791 /* Read one line; updates view->line. */
1792 bool (*read)(struct view *view, char *data);
1793 /* Draw one line; @lineno must be < view->height. */
1794 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1795 /* Depending on view handle a special requests. */
1796 enum request (*request)(struct view *view, enum request request, struct line *line);
1797 /* Search for regexp in a line. */
1798 bool (*grep)(struct view *view, struct line *line);
1799 /* Select line */
1800 void (*select)(struct view *view, struct line *line);
1803 #define VIEW_OPS(id, name, ref) name##_ops
1804 static struct view_ops VIEW_INFO(VIEW_OPS);
1806 static struct view views[] = {
1807 #define VIEW_DATA(id, name, ref) \
1808 { #name, ref, &name##_ops }
1809 VIEW_INFO(VIEW_DATA)
1812 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1814 #define foreach_view(view, i) \
1815 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1817 #define view_is_displayed(view) \
1818 (view == display[0] || view == display[1])
1820 static enum request
1821 view_request(struct view *view, enum request request)
1823 if (!view || !view->lines)
1824 return request;
1825 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1829 * View drawing.
1832 static inline void
1833 set_view_attr(struct view *view, enum line_type type)
1835 if (!view->curline->selected && view->curtype != type) {
1836 (void) wattrset(view->win, get_line_attr(type));
1837 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1838 view->curtype = type;
1842 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1844 static bool
1845 draw_chars(struct view *view, enum line_type type, const char *string,
1846 int max_len, bool use_tilde)
1848 static char out_buffer[BUFSIZ * 2];
1849 int len = 0;
1850 int col = 0;
1851 int trimmed = FALSE;
1852 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1854 if (max_len <= 0)
1855 return VIEW_MAX_LEN(view) <= 0;
1857 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1859 set_view_attr(view, type);
1860 if (len > 0) {
1861 if (opt_iconv_out != ICONV_NONE) {
1862 size_t inlen = len + 1;
1863 char *instr = calloc(1, inlen);
1864 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1865 if (!instr)
1866 return VIEW_MAX_LEN(view) <= 0;
1868 strncpy(instr, string, len);
1870 char *outbuf = out_buffer;
1871 size_t outlen = sizeof(out_buffer);
1873 size_t ret;
1875 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1876 if (ret != (size_t) -1) {
1877 string = out_buffer;
1878 len = sizeof(out_buffer) - outlen;
1880 free(instr);
1883 waddnstr(view->win, string, len);
1885 if (trimmed && use_tilde) {
1886 set_view_attr(view, LINE_DELIMITER);
1887 waddch(view->win, '~');
1888 col++;
1892 view->col += col;
1893 return VIEW_MAX_LEN(view) <= 0;
1896 static bool
1897 draw_space(struct view *view, enum line_type type, int max, int spaces)
1899 static char space[] = " ";
1901 spaces = MIN(max, spaces);
1903 while (spaces > 0) {
1904 int len = MIN(spaces, sizeof(space) - 1);
1906 if (draw_chars(view, type, space, len, FALSE))
1907 return TRUE;
1908 spaces -= len;
1911 return VIEW_MAX_LEN(view) <= 0;
1914 static bool
1915 draw_text(struct view *view, enum line_type type, const char *string)
1917 static char text[SIZEOF_STR];
1919 do {
1920 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1922 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1923 return TRUE;
1924 string += pos;
1925 } while (*string);
1927 return VIEW_MAX_LEN(view) <= 0;
1930 static bool
1931 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1933 char text[SIZEOF_STR];
1934 int retval;
1936 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1937 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1940 static bool
1941 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1943 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1944 int max = VIEW_MAX_LEN(view);
1945 int i;
1947 if (max < size)
1948 size = max;
1950 set_view_attr(view, type);
1951 /* Using waddch() instead of waddnstr() ensures that
1952 * they'll be rendered correctly for the cursor line. */
1953 for (i = skip; i < size; i++)
1954 waddch(view->win, graphic[i]);
1956 view->col += size;
1957 if (separator) {
1958 if (size < max && skip <= size)
1959 waddch(view->win, ' ');
1960 view->col++;
1963 return VIEW_MAX_LEN(view) <= 0;
1966 static bool
1967 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1969 int max = MIN(VIEW_MAX_LEN(view), len);
1970 int col = view->col;
1972 if (!text)
1973 return draw_space(view, type, max, max);
1975 return draw_chars(view, type, text, max - 1, trim)
1976 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1979 static bool
1980 draw_date(struct view *view, struct time *time)
1982 const char *date = mkdate(time, opt_date);
1983 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1985 if (opt_date == DATE_NO)
1986 return FALSE;
1988 return draw_field(view, LINE_DATE, date, cols, FALSE);
1991 static bool
1992 draw_author(struct view *view, const char *author)
1994 bool trim = author_trim(opt_author_cols);
1995 const char *text = mkauthor(author, opt_author_cols, opt_author);
1997 if (opt_author == AUTHOR_NO)
1998 return FALSE;
2000 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2003 static bool
2004 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2006 bool trim = filename && strlen(filename) >= opt_filename_cols;
2008 if (opt_filename == FILENAME_NO)
2009 return FALSE;
2011 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2012 return FALSE;
2014 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2017 static bool
2018 draw_mode(struct view *view, mode_t mode)
2020 const char *str = mkmode(mode);
2022 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2025 static bool
2026 draw_lineno(struct view *view, unsigned int lineno)
2028 char number[10];
2029 int digits3 = view->digits < 3 ? 3 : view->digits;
2030 int max = MIN(VIEW_MAX_LEN(view), digits3);
2031 char *text = NULL;
2032 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2034 if (!opt_line_number)
2035 return FALSE;
2037 lineno += view->pos.offset + 1;
2038 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2039 static char fmt[] = "%1ld";
2041 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2042 if (string_format(number, fmt, lineno))
2043 text = number;
2045 if (text)
2046 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2047 else
2048 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2049 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2052 static bool
2053 draw_refs(struct view *view, struct ref_list *refs)
2055 size_t i;
2057 if (!opt_show_refs || !refs)
2058 return FALSE;
2060 for (i = 0; i < refs->size; i++) {
2061 struct ref *ref = refs->refs[i];
2062 enum line_type type = get_line_type_from_ref(ref);
2064 if (draw_formatted(view, type, "[%s]", ref->name))
2065 return TRUE;
2067 if (draw_text(view, LINE_DEFAULT, " "))
2068 return TRUE;
2071 return FALSE;
2074 static bool
2075 draw_view_line(struct view *view, unsigned int lineno)
2077 struct line *line;
2078 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2080 assert(view_is_displayed(view));
2082 if (view->pos.offset + lineno >= view->lines)
2083 return FALSE;
2085 line = &view->line[view->pos.offset + lineno];
2087 wmove(view->win, lineno, 0);
2088 if (line->cleareol)
2089 wclrtoeol(view->win);
2090 view->col = 0;
2091 view->curline = line;
2092 view->curtype = LINE_NONE;
2093 line->selected = FALSE;
2094 line->dirty = line->cleareol = 0;
2096 if (selected) {
2097 set_view_attr(view, LINE_CURSOR);
2098 line->selected = TRUE;
2099 view->ops->select(view, line);
2102 return view->ops->draw(view, line, lineno);
2105 static void
2106 redraw_view_dirty(struct view *view)
2108 bool dirty = FALSE;
2109 int lineno;
2111 for (lineno = 0; lineno < view->height; lineno++) {
2112 if (view->pos.offset + lineno >= view->lines)
2113 break;
2114 if (!view->line[view->pos.offset + lineno].dirty)
2115 continue;
2116 dirty = TRUE;
2117 if (!draw_view_line(view, lineno))
2118 break;
2121 if (!dirty)
2122 return;
2123 wnoutrefresh(view->win);
2126 static void
2127 redraw_view_from(struct view *view, int lineno)
2129 assert(0 <= lineno && lineno < view->height);
2131 for (; lineno < view->height; lineno++) {
2132 if (!draw_view_line(view, lineno))
2133 break;
2136 wnoutrefresh(view->win);
2139 static void
2140 redraw_view(struct view *view)
2142 werase(view->win);
2143 redraw_view_from(view, 0);
2147 static void
2148 update_view_title(struct view *view)
2150 char buf[SIZEOF_STR];
2151 char state[SIZEOF_STR];
2152 size_t bufpos = 0, statelen = 0;
2153 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2155 assert(view_is_displayed(view));
2157 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2158 unsigned int view_lines = view->pos.offset + view->height;
2159 unsigned int lines = view->lines
2160 ? MIN(view_lines, view->lines) * 100 / view->lines
2161 : 0;
2163 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2164 view->ops->type,
2165 view->pos.lineno + 1,
2166 view->lines,
2167 lines);
2171 if (view->pipe) {
2172 time_t secs = time(NULL) - view->start_time;
2174 /* Three git seconds are a long time ... */
2175 if (secs > 2)
2176 string_format_from(state, &statelen, " loading %lds", secs);
2179 string_format_from(buf, &bufpos, "[%s]", view->name);
2180 if (*view->ref && bufpos < view->width) {
2181 size_t refsize = strlen(view->ref);
2182 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2184 if (minsize < view->width)
2185 refsize = view->width - minsize + 7;
2186 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2189 if (statelen && bufpos < view->width) {
2190 string_format_from(buf, &bufpos, "%s", state);
2193 if (view == display[current_view])
2194 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2195 else
2196 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2198 mvwaddnstr(window, 0, 0, buf, bufpos);
2199 wclrtoeol(window);
2200 wnoutrefresh(window);
2203 static int
2204 apply_step(double step, int value)
2206 if (step >= 1)
2207 return (int) step;
2208 value *= step + 0.01;
2209 return value ? value : 1;
2212 static void
2213 resize_display(void)
2215 int offset, i;
2216 struct view *base = display[0];
2217 struct view *view = display[1] ? display[1] : display[0];
2219 /* Setup window dimensions */
2221 getmaxyx(stdscr, base->height, base->width);
2223 /* Make room for the status window. */
2224 base->height -= 1;
2226 if (view != base) {
2227 /* Horizontal split. */
2228 view->width = base->width;
2229 view->height = apply_step(opt_scale_split_view, base->height);
2230 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2231 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2232 base->height -= view->height;
2234 /* Make room for the title bar. */
2235 view->height -= 1;
2238 /* Make room for the title bar. */
2239 base->height -= 1;
2241 offset = 0;
2243 foreach_displayed_view (view, i) {
2244 if (!display_win[i]) {
2245 display_win[i] = newwin(view->height, view->width, offset, 0);
2246 if (!display_win[i])
2247 die("Failed to create %s view", view->name);
2249 scrollok(display_win[i], FALSE);
2251 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2252 if (!display_title[i])
2253 die("Failed to create title window");
2255 } else {
2256 wresize(display_win[i], view->height, view->width);
2257 mvwin(display_win[i], offset, 0);
2258 mvwin(display_title[i], offset + view->height, 0);
2261 view->win = display_win[i];
2263 offset += view->height + 1;
2267 static void
2268 redraw_display(bool clear)
2270 struct view *view;
2271 int i;
2273 foreach_displayed_view (view, i) {
2274 if (clear)
2275 wclear(view->win);
2276 redraw_view(view);
2277 update_view_title(view);
2283 * Option management
2286 #define TOGGLE_MENU \
2287 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2288 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2289 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2290 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2291 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2292 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2293 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2294 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2295 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2296 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2298 static bool
2299 toggle_option(enum request request)
2301 const struct {
2302 enum request request;
2303 const struct enum_map *map;
2304 size_t map_size;
2305 } data[] = {
2306 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2307 TOGGLE_MENU
2308 #undef TOGGLE_
2310 const struct menu_item menu[] = {
2311 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2312 TOGGLE_MENU
2313 #undef TOGGLE_
2314 { 0 }
2316 int i = 0;
2318 if (request == REQ_OPTIONS) {
2319 if (!prompt_menu("Toggle option", menu, &i))
2320 return FALSE;
2321 } else {
2322 while (i < ARRAY_SIZE(data) && data[i].request != request)
2323 i++;
2324 if (i >= ARRAY_SIZE(data))
2325 die("Invalid request (%d)", request);
2328 if (data[i].map != NULL) {
2329 unsigned int *opt = menu[i].data;
2331 *opt = (*opt + 1) % data[i].map_size;
2332 if (data[i].map == ignore_space_map) {
2333 update_ignore_space_arg();
2334 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2335 return TRUE;
2337 } else if (data[i].map == commit_order_map) {
2338 update_commit_order_arg();
2339 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2340 return TRUE;
2343 redraw_display(FALSE);
2344 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2346 } else {
2347 bool *option = menu[i].data;
2349 *option = !*option;
2350 redraw_display(FALSE);
2351 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2354 return FALSE;
2359 * Navigation
2362 static bool
2363 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2365 if (lineno >= view->lines)
2366 lineno = view->lines > 0 ? view->lines - 1 : 0;
2368 if (offset > lineno || offset + view->height <= lineno) {
2369 unsigned long half = view->height / 2;
2371 if (lineno > half)
2372 offset = lineno - half;
2373 else
2374 offset = 0;
2377 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2378 view->pos.offset = offset;
2379 view->pos.lineno = lineno;
2380 return TRUE;
2383 return FALSE;
2386 /* Scrolling backend */
2387 static void
2388 do_scroll_view(struct view *view, int lines)
2390 bool redraw_current_line = FALSE;
2392 /* The rendering expects the new offset. */
2393 view->pos.offset += lines;
2395 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2396 assert(lines);
2398 /* Move current line into the view. */
2399 if (view->pos.lineno < view->pos.offset) {
2400 view->pos.lineno = view->pos.offset;
2401 redraw_current_line = TRUE;
2402 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2403 view->pos.lineno = view->pos.offset + view->height - 1;
2404 redraw_current_line = TRUE;
2407 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2409 /* Redraw the whole screen if scrolling is pointless. */
2410 if (view->height < ABS(lines)) {
2411 redraw_view(view);
2413 } else {
2414 int line = lines > 0 ? view->height - lines : 0;
2415 int end = line + ABS(lines);
2417 scrollok(view->win, TRUE);
2418 wscrl(view->win, lines);
2419 scrollok(view->win, FALSE);
2421 while (line < end && draw_view_line(view, line))
2422 line++;
2424 if (redraw_current_line)
2425 draw_view_line(view, view->pos.lineno - view->pos.offset);
2426 wnoutrefresh(view->win);
2429 view->has_scrolled = TRUE;
2430 report("");
2433 /* Scroll frontend */
2434 static void
2435 scroll_view(struct view *view, enum request request)
2437 int lines = 1;
2439 assert(view_is_displayed(view));
2441 switch (request) {
2442 case REQ_SCROLL_FIRST_COL:
2443 view->pos.col = 0;
2444 redraw_view_from(view, 0);
2445 report("");
2446 return;
2447 case REQ_SCROLL_LEFT:
2448 if (view->pos.col == 0) {
2449 report("Cannot scroll beyond the first column");
2450 return;
2452 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2453 view->pos.col = 0;
2454 else
2455 view->pos.col -= apply_step(opt_hscroll, view->width);
2456 redraw_view_from(view, 0);
2457 report("");
2458 return;
2459 case REQ_SCROLL_RIGHT:
2460 view->pos.col += apply_step(opt_hscroll, view->width);
2461 redraw_view(view);
2462 report("");
2463 return;
2464 case REQ_SCROLL_PAGE_DOWN:
2465 lines = view->height;
2466 case REQ_SCROLL_LINE_DOWN:
2467 if (view->pos.offset + lines > view->lines)
2468 lines = view->lines - view->pos.offset;
2470 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2471 report("Cannot scroll beyond the last line");
2472 return;
2474 break;
2476 case REQ_SCROLL_PAGE_UP:
2477 lines = view->height;
2478 case REQ_SCROLL_LINE_UP:
2479 if (lines > view->pos.offset)
2480 lines = view->pos.offset;
2482 if (lines == 0) {
2483 report("Cannot scroll beyond the first line");
2484 return;
2487 lines = -lines;
2488 break;
2490 default:
2491 die("request %d not handled in switch", request);
2494 do_scroll_view(view, lines);
2497 /* Cursor moving */
2498 static void
2499 move_view(struct view *view, enum request request)
2501 int scroll_steps = 0;
2502 int steps;
2504 switch (request) {
2505 case REQ_MOVE_FIRST_LINE:
2506 steps = -view->pos.lineno;
2507 break;
2509 case REQ_MOVE_LAST_LINE:
2510 steps = view->lines - view->pos.lineno - 1;
2511 break;
2513 case REQ_MOVE_PAGE_UP:
2514 steps = view->height > view->pos.lineno
2515 ? -view->pos.lineno : -view->height;
2516 break;
2518 case REQ_MOVE_PAGE_DOWN:
2519 steps = view->pos.lineno + view->height >= view->lines
2520 ? view->lines - view->pos.lineno - 1 : view->height;
2521 break;
2523 case REQ_MOVE_UP:
2524 case REQ_PREVIOUS:
2525 steps = -1;
2526 break;
2528 case REQ_MOVE_DOWN:
2529 case REQ_NEXT:
2530 steps = 1;
2531 break;
2533 default:
2534 die("request %d not handled in switch", request);
2537 if (steps <= 0 && view->pos.lineno == 0) {
2538 report("Cannot move beyond the first line");
2539 return;
2541 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2542 report("Cannot move beyond the last line");
2543 return;
2546 /* Move the current line */
2547 view->pos.lineno += steps;
2548 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2550 /* Check whether the view needs to be scrolled */
2551 if (view->pos.lineno < view->pos.offset ||
2552 view->pos.lineno >= view->pos.offset + view->height) {
2553 scroll_steps = steps;
2554 if (steps < 0 && -steps > view->pos.offset) {
2555 scroll_steps = -view->pos.offset;
2557 } else if (steps > 0) {
2558 if (view->pos.lineno == view->lines - 1 &&
2559 view->lines > view->height) {
2560 scroll_steps = view->lines - view->pos.offset - 1;
2561 if (scroll_steps >= view->height)
2562 scroll_steps -= view->height - 1;
2567 if (!view_is_displayed(view)) {
2568 view->pos.offset += scroll_steps;
2569 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2570 view->ops->select(view, &view->line[view->pos.lineno]);
2571 return;
2574 /* Repaint the old "current" line if we be scrolling */
2575 if (ABS(steps) < view->height)
2576 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2578 if (scroll_steps) {
2579 do_scroll_view(view, scroll_steps);
2580 return;
2583 /* Draw the current line */
2584 draw_view_line(view, view->pos.lineno - view->pos.offset);
2586 wnoutrefresh(view->win);
2587 report("");
2592 * Searching
2595 static void search_view(struct view *view, enum request request);
2597 static bool
2598 grep_text(struct view *view, const char *text[])
2600 regmatch_t pmatch;
2601 size_t i;
2603 for (i = 0; text[i]; i++)
2604 if (*text[i] &&
2605 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2606 return TRUE;
2607 return FALSE;
2610 static void
2611 select_view_line(struct view *view, unsigned long lineno)
2613 struct position old = view->pos;
2615 if (goto_view_line(view, view->pos.offset, lineno)) {
2616 if (view_is_displayed(view)) {
2617 if (old.offset != view->pos.offset) {
2618 redraw_view(view);
2619 } else {
2620 draw_view_line(view, old.lineno - view->pos.offset);
2621 draw_view_line(view, view->pos.lineno - view->pos.offset);
2622 wnoutrefresh(view->win);
2624 } else {
2625 view->ops->select(view, &view->line[view->pos.lineno]);
2630 static void
2631 find_next(struct view *view, enum request request)
2633 unsigned long lineno = view->pos.lineno;
2634 int direction;
2636 if (!*view->grep) {
2637 if (!*opt_search)
2638 report("No previous search");
2639 else
2640 search_view(view, request);
2641 return;
2644 switch (request) {
2645 case REQ_SEARCH:
2646 case REQ_FIND_NEXT:
2647 direction = 1;
2648 break;
2650 case REQ_SEARCH_BACK:
2651 case REQ_FIND_PREV:
2652 direction = -1;
2653 break;
2655 default:
2656 return;
2659 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2660 lineno += direction;
2662 /* Note, lineno is unsigned long so will wrap around in which case it
2663 * will become bigger than view->lines. */
2664 for (; lineno < view->lines; lineno += direction) {
2665 if (view->ops->grep(view, &view->line[lineno])) {
2666 select_view_line(view, lineno);
2667 report("Line %ld matches '%s'", lineno + 1, view->grep);
2668 return;
2672 report("No match found for '%s'", view->grep);
2675 static void
2676 search_view(struct view *view, enum request request)
2678 int regex_err;
2680 if (view->regex) {
2681 regfree(view->regex);
2682 *view->grep = 0;
2683 } else {
2684 view->regex = calloc(1, sizeof(*view->regex));
2685 if (!view->regex)
2686 return;
2689 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2690 if (regex_err != 0) {
2691 char buf[SIZEOF_STR] = "unknown error";
2693 regerror(regex_err, view->regex, buf, sizeof(buf));
2694 report("Search failed: %s", buf);
2695 return;
2698 string_copy(view->grep, opt_search);
2700 find_next(view, request);
2704 * Incremental updating
2707 static inline bool
2708 check_position(struct position *pos)
2710 return pos->lineno || pos->col || pos->offset;
2713 static inline void
2714 clear_position(struct position *pos)
2716 memset(pos, 0, sizeof(*pos));
2719 static void
2720 reset_view(struct view *view)
2722 int i;
2724 for (i = 0; i < view->lines; i++)
2725 if (!view->line[i].dont_free)
2726 free(view->line[i].data);
2727 free(view->line);
2729 view->prev_pos = view->pos;
2730 clear_position(&view->pos);
2732 view->line = NULL;
2733 view->lines = 0;
2734 view->vid[0] = 0;
2735 view->update_secs = 0;
2738 static const char *
2739 format_arg(const char *name)
2741 static struct {
2742 const char *name;
2743 size_t namelen;
2744 const char *value;
2745 const char *value_if_empty;
2746 } vars[] = {
2747 #define FORMAT_VAR(name, value, value_if_empty) \
2748 { name, STRING_SIZE(name), value, value_if_empty }
2749 FORMAT_VAR("%(directory)", opt_path, "."),
2750 FORMAT_VAR("%(file)", opt_file, ""),
2751 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2752 FORMAT_VAR("%(head)", ref_head, ""),
2753 FORMAT_VAR("%(commit)", ref_commit, ""),
2754 FORMAT_VAR("%(blob)", ref_blob, ""),
2755 FORMAT_VAR("%(branch)", ref_branch, ""),
2757 int i;
2759 if (!prefixcmp(name, "%(prompt"))
2760 return read_prompt("Command argument: ");
2762 for (i = 0; i < ARRAY_SIZE(vars); i++)
2763 if (!strncmp(name, vars[i].name, vars[i].namelen))
2764 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2766 report("Unknown replacement: `%s`", name);
2767 return NULL;
2770 static bool
2771 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2773 char buf[SIZEOF_STR];
2774 int argc;
2776 argv_free(*dst_argv);
2778 for (argc = 0; src_argv[argc]; argc++) {
2779 const char *arg = src_argv[argc];
2780 size_t bufpos = 0;
2782 if (!strcmp(arg, "%(fileargs)")) {
2783 if (!argv_append_array(dst_argv, opt_file_argv))
2784 break;
2785 continue;
2787 } else if (!strcmp(arg, "%(diffargs)")) {
2788 if (!argv_append_array(dst_argv, opt_diff_argv))
2789 break;
2790 continue;
2792 } else if (!strcmp(arg, "%(blameargs)")) {
2793 if (!argv_append_array(dst_argv, opt_blame_argv))
2794 break;
2795 continue;
2797 } else if (!strcmp(arg, "%(revargs)") ||
2798 (first && !strcmp(arg, "%(commit)"))) {
2799 if (!argv_append_array(dst_argv, opt_rev_argv))
2800 break;
2801 continue;
2804 while (arg) {
2805 char *next = strstr(arg, "%(");
2806 int len = next - arg;
2807 const char *value;
2809 if (!next) {
2810 len = strlen(arg);
2811 value = "";
2813 } else {
2814 value = format_arg(next);
2816 if (!value) {
2817 return FALSE;
2821 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2822 return FALSE;
2824 arg = next ? strchr(next, ')') + 1 : NULL;
2827 if (!argv_append(dst_argv, buf))
2828 break;
2831 return src_argv[argc] == NULL;
2834 static bool
2835 restore_view_position(struct view *view)
2837 /* A view without a previous view is the first view */
2838 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2839 select_view_line(view, opt_lineno - 1);
2840 opt_lineno = 0;
2843 /* Ensure that the view position is in a valid state. */
2844 if (!check_position(&view->prev_pos) ||
2845 (view->pipe && view->lines <= view->prev_pos.lineno))
2846 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2848 /* Changing the view position cancels the restoring. */
2849 /* FIXME: Changing back to the first line is not detected. */
2850 if (check_position(&view->pos)) {
2851 clear_position(&view->prev_pos);
2852 return FALSE;
2855 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2856 view_is_displayed(view))
2857 werase(view->win);
2859 view->pos.col = view->prev_pos.col;
2860 clear_position(&view->prev_pos);
2862 return TRUE;
2865 static void
2866 end_update(struct view *view, bool force)
2868 if (!view->pipe)
2869 return;
2870 while (!view->ops->read(view, NULL))
2871 if (!force)
2872 return;
2873 if (force)
2874 io_kill(view->pipe);
2875 io_done(view->pipe);
2876 view->pipe = NULL;
2879 static void
2880 setup_update(struct view *view, const char *vid)
2882 reset_view(view);
2883 string_copy_rev(view->vid, vid);
2884 view->pipe = &view->io;
2885 view->start_time = time(NULL);
2888 static bool
2889 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2891 bool extra = !!(flags & (OPEN_EXTRA));
2892 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2893 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2895 if (!reload && !strcmp(view->vid, view->id))
2896 return TRUE;
2898 if (view->pipe) {
2899 if (extra)
2900 io_done(view->pipe);
2901 else
2902 end_update(view, TRUE);
2905 if (!refresh && argv) {
2906 view->dir = dir;
2907 if (!format_argv(&view->argv, argv, !view->prev)) {
2908 report("Failed to format %s arguments", view->name);
2909 return FALSE;
2912 /* Put the current ref_* value to the view title ref
2913 * member. This is needed by the blob view. Most other
2914 * views sets it automatically after loading because the
2915 * first line is a commit line. */
2916 string_copy_rev(view->ref, view->id);
2919 if (view->argv && view->argv[0] &&
2920 !io_run(&view->io, IO_RD, view->dir, view->argv)) {
2921 report("Failed to open %s view", view->name);
2922 return FALSE;
2925 if (!extra)
2926 setup_update(view, view->id);
2928 return TRUE;
2931 static bool
2932 update_view(struct view *view)
2934 char *line;
2935 /* Clear the view and redraw everything since the tree sorting
2936 * might have rearranged things. */
2937 bool redraw = view->lines == 0;
2938 bool can_read = TRUE;
2940 if (!view->pipe)
2941 return TRUE;
2943 if (!io_can_read(view->pipe, FALSE)) {
2944 if (view->lines == 0 && view_is_displayed(view)) {
2945 time_t secs = time(NULL) - view->start_time;
2947 if (secs > 1 && secs > view->update_secs) {
2948 if (view->update_secs == 0)
2949 redraw_view(view);
2950 update_view_title(view);
2951 view->update_secs = secs;
2954 return TRUE;
2957 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2958 if (view->encoding) {
2959 line = encoding_convert(view->encoding, line);
2962 if (!view->ops->read(view, line)) {
2963 report("Allocation failure");
2964 end_update(view, TRUE);
2965 return FALSE;
2970 unsigned long lines = view->lines;
2971 int digits;
2973 for (digits = 0; lines; digits++)
2974 lines /= 10;
2976 /* Keep the displayed view in sync with line number scaling. */
2977 if (digits != view->digits) {
2978 view->digits = digits;
2979 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2980 redraw = TRUE;
2984 if (io_error(view->pipe)) {
2985 report("Failed to read: %s", io_strerror(view->pipe));
2986 end_update(view, TRUE);
2988 } else if (io_eof(view->pipe)) {
2989 if (view_is_displayed(view))
2990 report("");
2991 end_update(view, FALSE);
2994 if (restore_view_position(view))
2995 redraw = TRUE;
2997 if (!view_is_displayed(view))
2998 return TRUE;
3000 if (redraw)
3001 redraw_view_from(view, 0);
3002 else
3003 redraw_view_dirty(view);
3005 /* Update the title _after_ the redraw so that if the redraw picks up a
3006 * commit reference in view->ref it'll be available here. */
3007 update_view_title(view);
3008 return TRUE;
3011 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3013 static struct line *
3014 add_line_data(struct view *view, void *data, enum line_type type)
3016 struct line *line;
3018 if (!realloc_lines(&view->line, view->lines, 1))
3019 return NULL;
3021 line = &view->line[view->lines++];
3022 memset(line, 0, sizeof(*line));
3023 line->type = type;
3024 line->data = data;
3025 line->dirty = 1;
3027 return line;
3030 static struct line *
3031 add_line_static_data(struct view *view, void *data, enum line_type type)
3033 struct line *line = add_line_data(view, data, type);
3035 if (line)
3036 line->dont_free = TRUE;
3037 return line;
3040 static struct line *
3041 add_line_text(struct view *view, const char *text, enum line_type type)
3043 char *data = text ? strdup(text) : NULL;
3045 return data ? add_line_data(view, data, type) : NULL;
3048 static struct line *
3049 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3051 char buf[SIZEOF_STR];
3052 int retval;
3054 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3055 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3059 * View opening
3062 static void
3063 split_view(struct view *prev, struct view *view)
3065 display[1] = view;
3066 current_view = 1;
3067 view->parent = prev;
3068 resize_display();
3070 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3071 /* Take the title line into account. */
3072 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3074 /* Scroll the view that was split if the current line is
3075 * outside the new limited view. */
3076 do_scroll_view(prev, lines);
3079 if (view != prev && view_is_displayed(prev)) {
3080 /* "Blur" the previous view. */
3081 update_view_title(prev);
3085 static void
3086 maximize_view(struct view *view, bool redraw)
3088 memset(display, 0, sizeof(display));
3089 current_view = 0;
3090 display[current_view] = view;
3091 resize_display();
3092 if (redraw) {
3093 redraw_display(FALSE);
3094 report("");
3098 static void
3099 load_view(struct view *view, struct view *prev, enum open_flags flags)
3101 if (view->pipe)
3102 end_update(view, TRUE);
3103 if (view->ops->private_size) {
3104 if (!view->private)
3105 view->private = calloc(1, view->ops->private_size);
3106 else
3107 memset(view->private, 0, view->ops->private_size);
3110 /* When prev == view it means this is the first loaded view. */
3111 if (prev && view != prev) {
3112 view->prev = prev;
3115 if (!view->ops->open(view, flags))
3116 return;
3118 if (prev) {
3119 bool split = !!(flags & OPEN_SPLIT);
3121 if (split) {
3122 split_view(prev, view);
3123 } else {
3124 maximize_view(view, FALSE);
3128 restore_view_position(view);
3130 if (view->pipe && view->lines == 0) {
3131 /* Clear the old view and let the incremental updating refill
3132 * the screen. */
3133 werase(view->win);
3134 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3135 clear_position(&view->prev_pos);
3136 report("");
3137 } else if (view_is_displayed(view)) {
3138 redraw_view(view);
3139 report("");
3143 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3144 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3146 static void
3147 open_view(struct view *prev, enum request request, enum open_flags flags)
3149 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3150 struct view *view = VIEW(request);
3151 int nviews = displayed_views();
3153 assert(flags ^ OPEN_REFRESH);
3155 if (view == prev && nviews == 1 && !reload) {
3156 report("Already in %s view", view->name);
3157 return;
3160 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3161 report("The %s view is disabled in pager view", view->name);
3162 return;
3165 load_view(view, prev ? prev : view, flags);
3168 static void
3169 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3171 enum request request = view - views + REQ_OFFSET + 1;
3173 if (view->pipe)
3174 end_update(view, TRUE);
3175 view->dir = dir;
3177 if (!argv_copy(&view->argv, argv)) {
3178 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3179 } else {
3180 open_view(prev, request, flags | OPEN_PREPARED);
3184 static void
3185 open_external_viewer(const char *argv[], const char *dir)
3187 def_prog_mode(); /* save current tty modes */
3188 endwin(); /* restore original tty modes */
3189 io_run_fg(argv, dir);
3190 fprintf(stderr, "Press Enter to continue");
3191 getc(opt_tty);
3192 reset_prog_mode();
3193 redraw_display(TRUE);
3196 static void
3197 open_mergetool(const char *file)
3199 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3201 open_external_viewer(mergetool_argv, opt_cdup);
3204 static void
3205 open_editor(const char *file)
3207 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3208 char editor_cmd[SIZEOF_STR];
3209 const char *editor;
3210 int argc = 0;
3212 editor = getenv("GIT_EDITOR");
3213 if (!editor && *opt_editor)
3214 editor = opt_editor;
3215 if (!editor)
3216 editor = getenv("VISUAL");
3217 if (!editor)
3218 editor = getenv("EDITOR");
3219 if (!editor)
3220 editor = "vi";
3222 string_ncopy(editor_cmd, editor, strlen(editor));
3223 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3224 report("Failed to read editor command");
3225 return;
3228 editor_argv[argc] = file;
3229 open_external_viewer(editor_argv, opt_cdup);
3232 static void
3233 open_run_request(enum request request)
3235 struct run_request *req = get_run_request(request);
3236 const char **argv = NULL;
3238 if (!req) {
3239 report("Unknown run request");
3240 return;
3243 if (format_argv(&argv, req->argv, FALSE)) {
3244 if (req->silent)
3245 io_run_bg(argv);
3246 else
3247 open_external_viewer(argv, NULL);
3249 if (argv)
3250 argv_free(argv);
3251 free(argv);
3255 * User request switch noodle
3258 static int
3259 view_driver(struct view *view, enum request request)
3261 int i;
3263 if (request == REQ_NONE)
3264 return TRUE;
3266 if (request > REQ_NONE) {
3267 open_run_request(request);
3268 view_request(view, REQ_REFRESH);
3269 return TRUE;
3272 request = view_request(view, request);
3273 if (request == REQ_NONE)
3274 return TRUE;
3276 switch (request) {
3277 case REQ_MOVE_UP:
3278 case REQ_MOVE_DOWN:
3279 case REQ_MOVE_PAGE_UP:
3280 case REQ_MOVE_PAGE_DOWN:
3281 case REQ_MOVE_FIRST_LINE:
3282 case REQ_MOVE_LAST_LINE:
3283 move_view(view, request);
3284 break;
3286 case REQ_SCROLL_FIRST_COL:
3287 case REQ_SCROLL_LEFT:
3288 case REQ_SCROLL_RIGHT:
3289 case REQ_SCROLL_LINE_DOWN:
3290 case REQ_SCROLL_LINE_UP:
3291 case REQ_SCROLL_PAGE_DOWN:
3292 case REQ_SCROLL_PAGE_UP:
3293 scroll_view(view, request);
3294 break;
3296 case REQ_VIEW_MAIN:
3297 case REQ_VIEW_DIFF:
3298 case REQ_VIEW_LOG:
3299 case REQ_VIEW_TREE:
3300 case REQ_VIEW_HELP:
3301 case REQ_VIEW_BRANCH:
3302 case REQ_VIEW_BLAME:
3303 case REQ_VIEW_BLOB:
3304 case REQ_VIEW_STATUS:
3305 case REQ_VIEW_STAGE:
3306 case REQ_VIEW_PAGER:
3307 open_view(view, request, OPEN_DEFAULT);
3308 break;
3310 case REQ_NEXT:
3311 case REQ_PREVIOUS:
3312 if (view->parent) {
3313 int line;
3315 view = view->parent;
3316 line = view->pos.lineno;
3317 move_view(view, request);
3318 if (view_is_displayed(view))
3319 update_view_title(view);
3320 if (line != view->pos.lineno)
3321 view_request(view, REQ_ENTER);
3322 } else {
3323 move_view(view, request);
3325 break;
3327 case REQ_VIEW_NEXT:
3329 int nviews = displayed_views();
3330 int next_view = (current_view + 1) % nviews;
3332 if (next_view == current_view) {
3333 report("Only one view is displayed");
3334 break;
3337 current_view = next_view;
3338 /* Blur out the title of the previous view. */
3339 update_view_title(view);
3340 report("");
3341 break;
3343 case REQ_REFRESH:
3344 report("Refreshing is not yet supported for the %s view", view->name);
3345 break;
3347 case REQ_MAXIMIZE:
3348 if (displayed_views() == 2)
3349 maximize_view(view, TRUE);
3350 break;
3352 case REQ_OPTIONS:
3353 case REQ_TOGGLE_LINENO:
3354 case REQ_TOGGLE_DATE:
3355 case REQ_TOGGLE_AUTHOR:
3356 case REQ_TOGGLE_FILENAME:
3357 case REQ_TOGGLE_GRAPHIC:
3358 case REQ_TOGGLE_REV_GRAPH:
3359 case REQ_TOGGLE_REFS:
3360 case REQ_TOGGLE_CHANGES:
3361 case REQ_TOGGLE_IGNORE_SPACE:
3362 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3363 reload_view(view);
3364 break;
3366 case REQ_TOGGLE_SORT_FIELD:
3367 case REQ_TOGGLE_SORT_ORDER:
3368 report("Sorting is not yet supported for the %s view", view->name);
3369 break;
3371 case REQ_DIFF_CONTEXT_UP:
3372 case REQ_DIFF_CONTEXT_DOWN:
3373 report("Changing the diff context is not yet supported for the %s view", view->name);
3374 break;
3376 case REQ_SEARCH:
3377 case REQ_SEARCH_BACK:
3378 search_view(view, request);
3379 break;
3381 case REQ_FIND_NEXT:
3382 case REQ_FIND_PREV:
3383 find_next(view, request);
3384 break;
3386 case REQ_STOP_LOADING:
3387 foreach_view(view, i) {
3388 if (view->pipe)
3389 report("Stopped loading the %s view", view->name),
3390 end_update(view, TRUE);
3392 break;
3394 case REQ_SHOW_VERSION:
3395 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3396 return TRUE;
3398 case REQ_SCREEN_REDRAW:
3399 redraw_display(TRUE);
3400 break;
3402 case REQ_EDIT:
3403 report("Nothing to edit");
3404 break;
3406 case REQ_ENTER:
3407 report("Nothing to enter");
3408 break;
3410 case REQ_VIEW_CLOSE:
3411 /* XXX: Mark closed views by letting view->prev point to the
3412 * view itself. Parents to closed view should never be
3413 * followed. */
3414 if (view->prev && view->prev != view) {
3415 maximize_view(view->prev, TRUE);
3416 view->prev = view;
3417 break;
3419 /* Fall-through */
3420 case REQ_QUIT:
3421 return FALSE;
3423 default:
3424 report("Unknown key, press %s for help",
3425 get_view_key(view, REQ_VIEW_HELP));
3426 return TRUE;
3429 return TRUE;
3434 * View backend utilities
3437 enum sort_field {
3438 ORDERBY_NAME,
3439 ORDERBY_DATE,
3440 ORDERBY_AUTHOR,
3443 struct sort_state {
3444 const enum sort_field *fields;
3445 size_t size, current;
3446 bool reverse;
3449 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3450 #define get_sort_field(state) ((state).fields[(state).current])
3451 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3453 static void
3454 sort_view(struct view *view, enum request request, struct sort_state *state,
3455 int (*compare)(const void *, const void *))
3457 switch (request) {
3458 case REQ_TOGGLE_SORT_FIELD:
3459 state->current = (state->current + 1) % state->size;
3460 break;
3462 case REQ_TOGGLE_SORT_ORDER:
3463 state->reverse = !state->reverse;
3464 break;
3465 default:
3466 die("Not a sort request");
3469 qsort(view->line, view->lines, sizeof(*view->line), compare);
3470 redraw_view(view);
3473 static bool
3474 update_diff_context(enum request request)
3476 int diff_context = opt_diff_context;
3478 switch (request) {
3479 case REQ_DIFF_CONTEXT_UP:
3480 opt_diff_context += 1;
3481 update_diff_context_arg(opt_diff_context);
3482 break;
3484 case REQ_DIFF_CONTEXT_DOWN:
3485 if (opt_diff_context == 0) {
3486 report("Diff context cannot be less than zero");
3487 break;
3489 opt_diff_context -= 1;
3490 update_diff_context_arg(opt_diff_context);
3491 break;
3493 default:
3494 die("Not a diff context request");
3497 return diff_context != opt_diff_context;
3500 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3502 /* Small author cache to reduce memory consumption. It uses binary
3503 * search to lookup or find place to position new entries. No entries
3504 * are ever freed. */
3505 static const char *
3506 get_author(const char *name)
3508 static const char **authors;
3509 static size_t authors_size;
3510 int from = 0, to = authors_size - 1;
3512 while (from <= to) {
3513 size_t pos = (to + from) / 2;
3514 int cmp = strcmp(name, authors[pos]);
3516 if (!cmp)
3517 return authors[pos];
3519 if (cmp < 0)
3520 to = pos - 1;
3521 else
3522 from = pos + 1;
3525 if (!realloc_authors(&authors, authors_size, 1))
3526 return NULL;
3527 name = strdup(name);
3528 if (!name)
3529 return NULL;
3531 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3532 authors[from] = name;
3533 authors_size++;
3535 return name;
3538 static void
3539 parse_timesec(struct time *time, const char *sec)
3541 time->sec = (time_t) atol(sec);
3544 static void
3545 parse_timezone(struct time *time, const char *zone)
3547 long tz;
3549 tz = ('0' - zone[1]) * 60 * 60 * 10;
3550 tz += ('0' - zone[2]) * 60 * 60;
3551 tz += ('0' - zone[3]) * 60 * 10;
3552 tz += ('0' - zone[4]) * 60;
3554 if (zone[0] == '-')
3555 tz = -tz;
3557 time->tz = tz;
3558 time->sec -= tz;
3561 /* Parse author lines where the name may be empty:
3562 * author <email@address.tld> 1138474660 +0100
3564 static void
3565 parse_author_line(char *ident, const char **author, struct time *time)
3567 char *nameend = strchr(ident, '<');
3568 char *emailend = strchr(ident, '>');
3570 if (nameend && emailend)
3571 *nameend = *emailend = 0;
3572 ident = chomp_string(ident);
3573 if (!*ident) {
3574 if (nameend)
3575 ident = chomp_string(nameend + 1);
3576 if (!*ident)
3577 ident = "Unknown";
3580 *author = get_author(ident);
3582 /* Parse epoch and timezone */
3583 if (emailend && emailend[1] == ' ') {
3584 char *secs = emailend + 2;
3585 char *zone = strchr(secs, ' ');
3587 parse_timesec(time, secs);
3589 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3590 parse_timezone(time, zone + 1);
3594 static struct line *
3595 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3597 for (; view->line < line; line--)
3598 if (line->type == type)
3599 return line;
3601 return NULL;
3605 * Blame
3608 struct blame_commit {
3609 char id[SIZEOF_REV]; /* SHA1 ID. */
3610 char title[128]; /* First line of the commit message. */
3611 const char *author; /* Author of the commit. */
3612 struct time time; /* Date from the author ident. */
3613 char filename[128]; /* Name of file. */
3614 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3615 char parent_filename[128]; /* Parent/previous name of file. */
3618 struct blame_header {
3619 char id[SIZEOF_REV]; /* SHA1 ID. */
3620 size_t orig_lineno;
3621 size_t lineno;
3622 size_t group;
3625 static bool
3626 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3628 const char *pos = *posref;
3630 *posref = NULL;
3631 pos = strchr(pos + 1, ' ');
3632 if (!pos || !isdigit(pos[1]))
3633 return FALSE;
3634 *number = atoi(pos + 1);
3635 if (*number < min || *number > max)
3636 return FALSE;
3638 *posref = pos;
3639 return TRUE;
3642 static bool
3643 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3645 const char *pos = text + SIZEOF_REV - 2;
3647 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3648 return FALSE;
3650 string_ncopy(header->id, text, SIZEOF_REV);
3652 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3653 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3654 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3655 return FALSE;
3657 return TRUE;
3660 static bool
3661 match_blame_header(const char *name, char **line)
3663 size_t namelen = strlen(name);
3664 bool matched = !strncmp(name, *line, namelen);
3666 if (matched)
3667 *line += namelen;
3669 return matched;
3672 static bool
3673 parse_blame_info(struct blame_commit *commit, char *line)
3675 if (match_blame_header("author ", &line)) {
3676 commit->author = get_author(line);
3678 } else if (match_blame_header("author-time ", &line)) {
3679 parse_timesec(&commit->time, line);
3681 } else if (match_blame_header("author-tz ", &line)) {
3682 parse_timezone(&commit->time, line);
3684 } else if (match_blame_header("summary ", &line)) {
3685 string_ncopy(commit->title, line, strlen(line));
3687 } else if (match_blame_header("previous ", &line)) {
3688 if (strlen(line) <= SIZEOF_REV)
3689 return FALSE;
3690 string_copy_rev(commit->parent_id, line);
3691 line += SIZEOF_REV;
3692 string_ncopy(commit->parent_filename, line, strlen(line));
3694 } else if (match_blame_header("filename ", &line)) {
3695 string_ncopy(commit->filename, line, strlen(line));
3696 return TRUE;
3699 return FALSE;
3703 * Pager backend
3706 static bool
3707 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3709 if (draw_lineno(view, lineno))
3710 return TRUE;
3712 draw_text(view, line->type, line->data);
3713 return TRUE;
3716 static bool
3717 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3719 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3720 char ref[SIZEOF_STR];
3722 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3723 return TRUE;
3725 /* This is the only fatal call, since it can "corrupt" the buffer. */
3726 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3727 return FALSE;
3729 return TRUE;
3732 static void
3733 add_pager_refs(struct view *view, struct line *line)
3735 char buf[SIZEOF_STR];
3736 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3737 struct ref_list *list;
3738 size_t bufpos = 0, i;
3739 const char *sep = "Refs: ";
3740 bool is_tag = FALSE;
3742 assert(line->type == LINE_COMMIT);
3744 list = get_ref_list(commit_id);
3745 if (!list) {
3746 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3747 goto try_add_describe_ref;
3748 return;
3751 for (i = 0; i < list->size; i++) {
3752 struct ref *ref = list->refs[i];
3753 const char *fmt = ref->tag ? "%s[%s]" :
3754 ref->remote ? "%s<%s>" : "%s%s";
3756 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3757 return;
3758 sep = ", ";
3759 if (ref->tag)
3760 is_tag = TRUE;
3763 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3764 try_add_describe_ref:
3765 /* Add <tag>-g<commit_id> "fake" reference. */
3766 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3767 return;
3770 if (bufpos == 0)
3771 return;
3773 add_line_text(view, buf, LINE_PP_REFS);
3776 static bool
3777 pager_common_read(struct view *view, char *data, enum line_type type)
3779 struct line *line;
3781 if (!data)
3782 return TRUE;
3784 line = add_line_text(view, data, type);
3785 if (!line)
3786 return FALSE;
3788 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3789 add_pager_refs(view, line);
3791 return TRUE;
3794 static bool
3795 pager_read(struct view *view, char *data)
3797 if (!data)
3798 return TRUE;
3800 return pager_common_read(view, data, get_line_type(data));
3803 static enum request
3804 pager_request(struct view *view, enum request request, struct line *line)
3806 int split = 0;
3808 if (request != REQ_ENTER)
3809 return request;
3811 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3812 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3813 split = 1;
3816 /* Always scroll the view even if it was split. That way
3817 * you can use Enter to scroll through the log view and
3818 * split open each commit diff. */
3819 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3821 /* FIXME: A minor workaround. Scrolling the view will call report("")
3822 * but if we are scrolling a non-current view this won't properly
3823 * update the view title. */
3824 if (split)
3825 update_view_title(view);
3827 return REQ_NONE;
3830 static bool
3831 pager_grep(struct view *view, struct line *line)
3833 const char *text[] = { line->data, NULL };
3835 return grep_text(view, text);
3838 static void
3839 pager_select(struct view *view, struct line *line)
3841 if (line->type == LINE_COMMIT) {
3842 char *text = (char *)line->data + STRING_SIZE("commit ");
3844 if (!view_has_flags(view, VIEW_NO_REF))
3845 string_copy_rev(view->ref, text);
3846 string_copy_rev(ref_commit, text);
3850 static bool
3851 pager_open(struct view *view, enum open_flags flags)
3853 if (display[0] == NULL) {
3854 if (!io_open(&view->io, ""))
3855 die("Failed to open stdin");
3856 flags = OPEN_PREPARED;
3858 } else if (!view->pipe && !view->lines) {
3859 report("No pager content, press %s to run command from prompt",
3860 get_view_key(view, REQ_PROMPT));
3861 return FALSE;
3864 return begin_update(view, NULL, NULL, flags);
3867 static struct view_ops pager_ops = {
3868 "line",
3869 { "pager" },
3870 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3872 pager_open,
3873 pager_read,
3874 pager_draw,
3875 pager_request,
3876 pager_grep,
3877 pager_select,
3880 static bool
3881 log_open(struct view *view, enum open_flags flags)
3883 static const char *log_argv[] = {
3884 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3887 return begin_update(view, NULL, log_argv, flags);
3890 static enum request
3891 log_request(struct view *view, enum request request, struct line *line)
3893 switch (request) {
3894 case REQ_REFRESH:
3895 load_refs();
3896 refresh_view(view);
3897 return REQ_NONE;
3898 default:
3899 return pager_request(view, request, line);
3903 static struct view_ops log_ops = {
3904 "line",
3905 { "log" },
3906 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3908 log_open,
3909 pager_read,
3910 pager_draw,
3911 log_request,
3912 pager_grep,
3913 pager_select,
3916 struct diff_state {
3917 bool reading_diff_stat;
3918 bool combined_diff;
3921 static bool
3922 diff_open(struct view *view, enum open_flags flags)
3924 static const char *diff_argv[] = {
3925 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3926 "--patch-with-stat", "--find-copies-harder", "-C",
3927 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3928 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3931 return begin_update(view, NULL, diff_argv, flags);
3934 static bool
3935 diff_common_read(struct view *view, char *data, struct diff_state *state)
3937 enum line_type type;
3939 if (state->reading_diff_stat) {
3940 size_t len = strlen(data);
3941 char *pipe = strchr(data, '|');
3942 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3943 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3944 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || strstr(data, ".../"));
3946 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
3947 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3948 } else {
3949 state->reading_diff_stat = FALSE;
3952 } else if (!strcmp(data, "---")) {
3953 state->reading_diff_stat = TRUE;
3956 type = get_line_type(data);
3958 if (type == LINE_DIFF_HEADER) {
3959 const int len = line_info[LINE_DIFF_HEADER].linelen;
3961 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3962 !strncmp(data + len, "cc ", strlen("cc ")))
3963 state->combined_diff = TRUE;
3966 /* ADD2 and DEL2 are only valid in combined diff hunks */
3967 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3968 type = LINE_DEFAULT;
3970 return pager_common_read(view, data, type);
3973 static enum request
3974 diff_common_enter(struct view *view, enum request request, struct line *line)
3976 if (line->type == LINE_DIFF_STAT) {
3977 int file_number = 0;
3979 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3980 file_number++;
3981 line--;
3984 while (line < view->line + view->lines) {
3985 if (line->type == LINE_DIFF_HEADER) {
3986 if (file_number == 1) {
3987 break;
3989 file_number--;
3991 line++;
3995 select_view_line(view, line - view->line);
3996 report("");
3997 return REQ_NONE;
3999 } else {
4000 return pager_request(view, request, line);
4004 static bool
4005 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4007 char *sep = strchr(*text, c);
4009 if (sep != NULL) {
4010 *sep = 0;
4011 draw_text(view, *type, *text);
4012 *sep = c;
4013 *text = sep;
4014 *type = next_type;
4017 return sep != NULL;
4020 static bool
4021 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4023 char *text = line->data;
4024 enum line_type type = line->type;
4026 if (draw_lineno(view, lineno))
4027 return TRUE;
4029 if (type == LINE_DIFF_STAT) {
4030 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4031 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4032 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4033 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4034 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4035 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4036 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4038 } else {
4039 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4040 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4044 draw_text(view, type, text);
4045 return TRUE;
4048 static bool
4049 diff_read(struct view *view, char *data)
4051 struct diff_state *state = view->private;
4053 if (!data) {
4054 /* Fall back to retry if no diff will be shown. */
4055 if (view->lines == 0 && opt_file_argv) {
4056 int pos = argv_size(view->argv)
4057 - argv_size(opt_file_argv) - 1;
4059 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4060 for (; view->argv[pos]; pos++) {
4061 free((void *) view->argv[pos]);
4062 view->argv[pos] = NULL;
4065 if (view->pipe)
4066 io_done(view->pipe);
4067 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4068 return FALSE;
4071 return TRUE;
4074 return diff_common_read(view, data, state);
4077 static bool
4078 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4079 struct blame_header *header, struct blame_commit *commit)
4081 char line_arg[SIZEOF_STR];
4082 const char *blame_argv[] = {
4083 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4085 struct io io;
4086 bool ok = FALSE;
4087 char *buf;
4089 if (!string_format(line_arg, "-L%d,+1", lineno))
4090 return FALSE;
4092 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4093 return FALSE;
4095 while ((buf = io_get(&io, '\n', TRUE))) {
4096 if (header) {
4097 if (!parse_blame_header(header, buf, 9999999))
4098 break;
4099 header = NULL;
4101 } else if (parse_blame_info(commit, buf)) {
4102 ok = TRUE;
4103 break;
4107 if (io_error(&io))
4108 ok = FALSE;
4110 io_done(&io);
4111 return ok;
4114 static bool
4115 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4117 return prefixcmp(chunk, "@@ -") ||
4118 !(chunk = strchr(chunk, marker)) ||
4119 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4122 static enum request
4123 diff_trace_origin(struct view *view, struct line *line)
4125 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4126 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4127 const char *chunk_data;
4128 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4129 int lineno = 0;
4130 const char *file = NULL;
4131 char ref[SIZEOF_REF];
4132 struct blame_header header;
4133 struct blame_commit commit;
4135 if (!diff || !chunk || chunk == line) {
4136 report("The line to trace must be inside a diff chunk");
4137 return REQ_NONE;
4140 for (; diff < line && !file; diff++) {
4141 const char *data = diff->data;
4143 if (!prefixcmp(data, "--- a/")) {
4144 file = data + STRING_SIZE("--- a/");
4145 break;
4149 if (diff == line || !file) {
4150 report("Failed to read the file name");
4151 return REQ_NONE;
4154 chunk_data = chunk->data;
4156 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4157 report("Failed to read the line number");
4158 return REQ_NONE;
4161 if (lineno == 0) {
4162 report("This is the origin of the line");
4163 return REQ_NONE;
4166 for (chunk += 1; chunk < line; chunk++) {
4167 if (chunk->type == LINE_DIFF_ADD) {
4168 lineno += chunk_marker == '+';
4169 } else if (chunk->type == LINE_DIFF_DEL) {
4170 lineno += chunk_marker == '-';
4171 } else {
4172 lineno++;
4176 if (chunk_marker == '+')
4177 string_copy(ref, view->vid);
4178 else
4179 string_format(ref, "%s^", view->vid);
4181 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4182 report("Failed to read blame data");
4183 return REQ_NONE;
4186 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4187 string_copy(opt_ref, header.id);
4188 opt_goto_line = header.orig_lineno - 1;
4190 return REQ_VIEW_BLAME;
4193 static enum request
4194 diff_request(struct view *view, enum request request, struct line *line)
4196 switch (request) {
4197 case REQ_VIEW_BLAME:
4198 return diff_trace_origin(view, line);
4200 case REQ_DIFF_CONTEXT_UP:
4201 case REQ_DIFF_CONTEXT_DOWN:
4202 if (!update_diff_context(request))
4203 return REQ_NONE;
4204 reload_view(view);
4205 return REQ_NONE;
4208 case REQ_ENTER:
4209 return diff_common_enter(view, request, line);
4211 default:
4212 return pager_request(view, request, line);
4216 static void
4217 diff_select(struct view *view, struct line *line)
4219 if (line->type == LINE_DIFF_STAT) {
4220 const char *key = get_view_key(view, REQ_ENTER);
4222 string_format(view->ref, "Press '%s' to jump to file diff", key);
4223 } else {
4224 string_ncopy(view->ref, view->id, strlen(view->id));
4225 return pager_select(view, line);
4229 static struct view_ops diff_ops = {
4230 "line",
4231 { "diff" },
4232 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4233 sizeof(struct diff_state),
4234 diff_open,
4235 diff_read,
4236 diff_common_draw,
4237 diff_request,
4238 pager_grep,
4239 diff_select,
4243 * Help backend
4246 static bool
4247 help_draw(struct view *view, struct line *line, unsigned int lineno)
4249 if (line->type == LINE_HELP_KEYMAP) {
4250 struct keymap *keymap = line->data;
4252 draw_formatted(view, line->type, "[%c] %s bindings",
4253 keymap->hidden ? '+' : '-', keymap->name);
4254 return TRUE;
4255 } else {
4256 return pager_draw(view, line, lineno);
4260 static bool
4261 help_open_keymap_title(struct view *view, struct keymap *keymap)
4263 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4264 return keymap->hidden;
4267 static void
4268 help_open_keymap(struct view *view, struct keymap *keymap)
4270 const char *group = NULL;
4271 char buf[SIZEOF_STR];
4272 size_t bufpos;
4273 bool add_title = TRUE;
4274 int i;
4276 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4277 const char *key = NULL;
4279 if (req_info[i].request == REQ_NONE)
4280 continue;
4282 if (!req_info[i].request) {
4283 group = req_info[i].help;
4284 continue;
4287 key = get_keys(keymap, req_info[i].request, TRUE);
4288 if (!key || !*key)
4289 continue;
4291 if (add_title && help_open_keymap_title(view, keymap))
4292 return;
4293 add_title = FALSE;
4295 if (group) {
4296 add_line_text(view, group, LINE_HELP_GROUP);
4297 group = NULL;
4300 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4301 enum_name(req_info[i]), req_info[i].help);
4304 group = "External commands:";
4306 for (i = 0; i < run_requests; i++) {
4307 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4308 const char *key;
4309 int argc;
4311 if (!req || req->keymap != keymap)
4312 continue;
4314 key = get_key_name(req->key);
4315 if (!*key)
4316 key = "(no key defined)";
4318 if (add_title && help_open_keymap_title(view, keymap))
4319 return;
4320 add_title = FALSE;
4322 if (group) {
4323 add_line_text(view, group, LINE_HELP_GROUP);
4324 group = NULL;
4327 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4328 if (!string_format_from(buf, &bufpos, "%s%s",
4329 argc ? " " : "", req->argv[argc]))
4330 return;
4332 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4336 static bool
4337 help_open(struct view *view, enum open_flags flags)
4339 struct keymap *keymap;
4341 reset_view(view);
4342 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4343 add_line_text(view, "", LINE_DEFAULT);
4345 for (keymap = keymaps; keymap; keymap = keymap->next)
4346 help_open_keymap(view, keymap);
4348 return TRUE;
4351 static enum request
4352 help_request(struct view *view, enum request request, struct line *line)
4354 switch (request) {
4355 case REQ_ENTER:
4356 if (line->type == LINE_HELP_KEYMAP) {
4357 struct keymap *keymap = line->data;
4359 keymap->hidden = !keymap->hidden;
4360 refresh_view(view);
4363 return REQ_NONE;
4364 default:
4365 return pager_request(view, request, line);
4369 static struct view_ops help_ops = {
4370 "line",
4371 { "help" },
4372 VIEW_NO_GIT_DIR,
4374 help_open,
4375 NULL,
4376 help_draw,
4377 help_request,
4378 pager_grep,
4379 pager_select,
4384 * Tree backend
4387 struct tree_stack_entry {
4388 struct tree_stack_entry *prev; /* Entry below this in the stack */
4389 unsigned long lineno; /* Line number to restore */
4390 char *name; /* Position of name in opt_path */
4393 /* The top of the path stack. */
4394 static struct tree_stack_entry *tree_stack = NULL;
4395 unsigned long tree_lineno = 0;
4397 static void
4398 pop_tree_stack_entry(void)
4400 struct tree_stack_entry *entry = tree_stack;
4402 tree_lineno = entry->lineno;
4403 entry->name[0] = 0;
4404 tree_stack = entry->prev;
4405 free(entry);
4408 static void
4409 push_tree_stack_entry(const char *name, unsigned long lineno)
4411 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4412 size_t pathlen = strlen(opt_path);
4414 if (!entry)
4415 return;
4417 entry->prev = tree_stack;
4418 entry->name = opt_path + pathlen;
4419 tree_stack = entry;
4421 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4422 pop_tree_stack_entry();
4423 return;
4426 /* Move the current line to the first tree entry. */
4427 tree_lineno = 1;
4428 entry->lineno = lineno;
4431 /* Parse output from git-ls-tree(1):
4433 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4436 #define SIZEOF_TREE_ATTR \
4437 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4439 #define SIZEOF_TREE_MODE \
4440 STRING_SIZE("100644 ")
4442 #define TREE_ID_OFFSET \
4443 STRING_SIZE("100644 blob ")
4445 struct tree_entry {
4446 char id[SIZEOF_REV];
4447 mode_t mode;
4448 struct time time; /* Date from the author ident. */
4449 const char *author; /* Author of the commit. */
4450 char name[1];
4453 struct tree_state {
4454 const char *author_name;
4455 struct time author_time;
4456 bool read_date;
4459 static const char *
4460 tree_path(const struct line *line)
4462 return ((struct tree_entry *) line->data)->name;
4465 static int
4466 tree_compare_entry(const struct line *line1, const struct line *line2)
4468 if (line1->type != line2->type)
4469 return line1->type == LINE_TREE_DIR ? -1 : 1;
4470 return strcmp(tree_path(line1), tree_path(line2));
4473 static const enum sort_field tree_sort_fields[] = {
4474 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4476 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4478 static int
4479 tree_compare(const void *l1, const void *l2)
4481 const struct line *line1 = (const struct line *) l1;
4482 const struct line *line2 = (const struct line *) l2;
4483 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4484 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4486 if (line1->type == LINE_TREE_HEAD)
4487 return -1;
4488 if (line2->type == LINE_TREE_HEAD)
4489 return 1;
4491 switch (get_sort_field(tree_sort_state)) {
4492 case ORDERBY_DATE:
4493 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4495 case ORDERBY_AUTHOR:
4496 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4498 case ORDERBY_NAME:
4499 default:
4500 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4505 static struct line *
4506 tree_entry(struct view *view, enum line_type type, const char *path,
4507 const char *mode, const char *id)
4509 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4510 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4512 if (!entry || !line) {
4513 free(entry);
4514 return NULL;
4517 strncpy(entry->name, path, strlen(path));
4518 if (mode)
4519 entry->mode = strtoul(mode, NULL, 8);
4520 if (id)
4521 string_copy_rev(entry->id, id);
4523 return line;
4526 static bool
4527 tree_read_date(struct view *view, char *text, struct tree_state *state)
4529 if (!text && state->read_date) {
4530 state->read_date = FALSE;
4531 return TRUE;
4533 } else if (!text) {
4534 /* Find next entry to process */
4535 const char *log_file[] = {
4536 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4537 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4540 if (!view->lines) {
4541 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4542 report("Tree is empty");
4543 return TRUE;
4546 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4547 report("Failed to load tree data");
4548 return TRUE;
4551 state->read_date = TRUE;
4552 return FALSE;
4554 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4555 parse_author_line(text + STRING_SIZE("author "),
4556 &state->author_name, &state->author_time);
4558 } else if (*text == ':') {
4559 char *pos;
4560 size_t annotated = 1;
4561 size_t i;
4563 pos = strchr(text, '\t');
4564 if (!pos)
4565 return TRUE;
4566 text = pos + 1;
4567 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4568 text += strlen(opt_path);
4569 pos = strchr(text, '/');
4570 if (pos)
4571 *pos = 0;
4573 for (i = 1; i < view->lines; i++) {
4574 struct line *line = &view->line[i];
4575 struct tree_entry *entry = line->data;
4577 annotated += !!entry->author;
4578 if (entry->author || strcmp(entry->name, text))
4579 continue;
4581 entry->author = state->author_name;
4582 entry->time = state->author_time;
4583 line->dirty = 1;
4584 break;
4587 if (annotated == view->lines)
4588 io_kill(view->pipe);
4590 return TRUE;
4593 static bool
4594 tree_read(struct view *view, char *text)
4596 struct tree_state *state = view->private;
4597 struct tree_entry *data;
4598 struct line *entry, *line;
4599 enum line_type type;
4600 size_t textlen = text ? strlen(text) : 0;
4601 char *path = text + SIZEOF_TREE_ATTR;
4603 if (state->read_date || !text)
4604 return tree_read_date(view, text, state);
4606 if (textlen <= SIZEOF_TREE_ATTR)
4607 return FALSE;
4608 if (view->lines == 0 &&
4609 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4610 return FALSE;
4612 /* Strip the path part ... */
4613 if (*opt_path) {
4614 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4615 size_t striplen = strlen(opt_path);
4617 if (pathlen > striplen)
4618 memmove(path, path + striplen,
4619 pathlen - striplen + 1);
4621 /* Insert "link" to parent directory. */
4622 if (view->lines == 1 &&
4623 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4624 return FALSE;
4627 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4628 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4629 if (!entry)
4630 return FALSE;
4631 data = entry->data;
4633 /* Skip "Directory ..." and ".." line. */
4634 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4635 if (tree_compare_entry(line, entry) <= 0)
4636 continue;
4638 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4640 line->data = data;
4641 line->type = type;
4642 for (; line <= entry; line++)
4643 line->dirty = line->cleareol = 1;
4644 return TRUE;
4647 if (tree_lineno > view->pos.lineno) {
4648 view->pos.lineno = tree_lineno;
4649 tree_lineno = 0;
4652 return TRUE;
4655 static bool
4656 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4658 struct tree_entry *entry = line->data;
4660 if (line->type == LINE_TREE_HEAD) {
4661 if (draw_text(view, line->type, "Directory path /"))
4662 return TRUE;
4663 } else {
4664 if (draw_mode(view, entry->mode))
4665 return TRUE;
4667 if (draw_author(view, entry->author))
4668 return TRUE;
4670 if (draw_date(view, &entry->time))
4671 return TRUE;
4674 draw_text(view, line->type, entry->name);
4675 return TRUE;
4678 static void
4679 open_blob_editor(const char *id)
4681 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4682 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4683 int fd = mkstemp(file);
4685 if (fd == -1)
4686 report("Failed to create temporary file");
4687 else if (!io_run_append(blob_argv, fd))
4688 report("Failed to save blob data to file");
4689 else
4690 open_editor(file);
4691 if (fd != -1)
4692 unlink(file);
4695 static enum request
4696 tree_request(struct view *view, enum request request, struct line *line)
4698 enum open_flags flags;
4699 struct tree_entry *entry = line->data;
4701 switch (request) {
4702 case REQ_VIEW_BLAME:
4703 if (line->type != LINE_TREE_FILE) {
4704 report("Blame only supported for files");
4705 return REQ_NONE;
4708 string_copy(opt_ref, view->vid);
4709 return request;
4711 case REQ_EDIT:
4712 if (line->type != LINE_TREE_FILE) {
4713 report("Edit only supported for files");
4714 } else if (!is_head_commit(view->vid)) {
4715 open_blob_editor(entry->id);
4716 } else {
4717 open_editor(opt_file);
4719 return REQ_NONE;
4721 case REQ_TOGGLE_SORT_FIELD:
4722 case REQ_TOGGLE_SORT_ORDER:
4723 sort_view(view, request, &tree_sort_state, tree_compare);
4724 return REQ_NONE;
4726 case REQ_PARENT:
4727 if (!*opt_path) {
4728 /* quit view if at top of tree */
4729 return REQ_VIEW_CLOSE;
4731 /* fake 'cd ..' */
4732 line = &view->line[1];
4733 break;
4735 case REQ_ENTER:
4736 break;
4738 default:
4739 return request;
4742 /* Cleanup the stack if the tree view is at a different tree. */
4743 while (!*opt_path && tree_stack)
4744 pop_tree_stack_entry();
4746 switch (line->type) {
4747 case LINE_TREE_DIR:
4748 /* Depending on whether it is a subdirectory or parent link
4749 * mangle the path buffer. */
4750 if (line == &view->line[1] && *opt_path) {
4751 pop_tree_stack_entry();
4753 } else {
4754 const char *basename = tree_path(line);
4756 push_tree_stack_entry(basename, view->pos.lineno);
4759 /* Trees and subtrees share the same ID, so they are not not
4760 * unique like blobs. */
4761 flags = OPEN_RELOAD;
4762 request = REQ_VIEW_TREE;
4763 break;
4765 case LINE_TREE_FILE:
4766 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4767 request = REQ_VIEW_BLOB;
4768 break;
4770 default:
4771 return REQ_NONE;
4774 open_view(view, request, flags);
4775 if (request == REQ_VIEW_TREE)
4776 view->pos.lineno = tree_lineno;
4778 return REQ_NONE;
4781 static bool
4782 tree_grep(struct view *view, struct line *line)
4784 struct tree_entry *entry = line->data;
4785 const char *text[] = {
4786 entry->name,
4787 mkauthor(entry->author, opt_author_cols, opt_author),
4788 mkdate(&entry->time, opt_date),
4789 NULL
4792 return grep_text(view, text);
4795 static void
4796 tree_select(struct view *view, struct line *line)
4798 struct tree_entry *entry = line->data;
4800 if (line->type == LINE_TREE_FILE) {
4801 string_copy_rev(ref_blob, entry->id);
4802 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4804 } else if (line->type != LINE_TREE_DIR) {
4805 return;
4808 string_copy_rev(view->ref, entry->id);
4811 static bool
4812 tree_open(struct view *view, enum open_flags flags)
4814 static const char *tree_argv[] = {
4815 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4818 if (string_rev_is_null(ref_commit)) {
4819 report("No tree exists for this commit");
4820 return FALSE;
4823 if (view->lines == 0 && opt_prefix[0]) {
4824 char *pos = opt_prefix;
4826 while (pos && *pos) {
4827 char *end = strchr(pos, '/');
4829 if (end)
4830 *end = 0;
4831 push_tree_stack_entry(pos, 0);
4832 pos = end;
4833 if (end) {
4834 *end = '/';
4835 pos++;
4839 } else if (strcmp(view->vid, view->id)) {
4840 opt_path[0] = 0;
4843 return begin_update(view, opt_cdup, tree_argv, flags);
4846 static struct view_ops tree_ops = {
4847 "file",
4848 { "tree" },
4849 VIEW_NO_FLAGS,
4850 sizeof(struct tree_state),
4851 tree_open,
4852 tree_read,
4853 tree_draw,
4854 tree_request,
4855 tree_grep,
4856 tree_select,
4859 static bool
4860 blob_open(struct view *view, enum open_flags flags)
4862 static const char *blob_argv[] = {
4863 "git", "cat-file", "blob", "%(blob)", NULL
4866 if (!ref_blob[0]) {
4867 report("No file chosen, press %s to open tree view",
4868 get_view_key(view, REQ_VIEW_TREE));
4869 return FALSE;
4872 view->encoding = get_path_encoding(opt_file, opt_encoding);
4874 return begin_update(view, NULL, blob_argv, flags);
4877 static bool
4878 blob_read(struct view *view, char *line)
4880 if (!line)
4881 return TRUE;
4882 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4885 static enum request
4886 blob_request(struct view *view, enum request request, struct line *line)
4888 switch (request) {
4889 case REQ_EDIT:
4890 open_blob_editor(view->vid);
4891 return REQ_NONE;
4892 default:
4893 return pager_request(view, request, line);
4897 static struct view_ops blob_ops = {
4898 "line",
4899 { "blob" },
4900 VIEW_NO_FLAGS,
4902 blob_open,
4903 blob_read,
4904 pager_draw,
4905 blob_request,
4906 pager_grep,
4907 pager_select,
4911 * Blame backend
4913 * Loading the blame view is a two phase job:
4915 * 1. File content is read either using opt_file from the
4916 * filesystem or using git-cat-file.
4917 * 2. Then blame information is incrementally added by
4918 * reading output from git-blame.
4921 struct blame {
4922 struct blame_commit *commit;
4923 unsigned long lineno;
4924 char text[1];
4927 struct blame_state {
4928 struct blame_commit *commit;
4929 int blamed;
4930 bool done_reading;
4931 bool auto_filename_display;
4934 static bool
4935 blame_detect_filename_display(struct view *view)
4937 bool show_filenames = FALSE;
4938 const char *filename = NULL;
4939 int i;
4941 if (opt_blame_argv) {
4942 for (i = 0; opt_blame_argv[i]; i++) {
4943 if (prefixcmp(opt_blame_argv[i], "-C"))
4944 continue;
4946 show_filenames = TRUE;
4950 for (i = 0; i < view->lines; i++) {
4951 struct blame *blame = view->line[i].data;
4953 if (blame->commit && blame->commit->id[0]) {
4954 if (!filename)
4955 filename = blame->commit->filename;
4956 else if (strcmp(filename, blame->commit->filename))
4957 show_filenames = TRUE;
4961 return show_filenames;
4964 static bool
4965 blame_open(struct view *view, enum open_flags flags)
4967 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4968 char path[SIZEOF_STR];
4969 size_t i;
4971 if (!opt_file[0]) {
4972 report("No file chosen, press %s to open tree view",
4973 get_view_key(view, REQ_VIEW_TREE));
4974 return FALSE;
4977 if (!view->prev && *opt_prefix) {
4978 string_copy(path, opt_file);
4979 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
4980 report("Failed to setup the blame view");
4981 return FALSE;
4985 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4986 const char *blame_cat_file_argv[] = {
4987 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4990 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4991 return FALSE;
4994 /* First pass: remove multiple references to the same commit. */
4995 for (i = 0; i < view->lines; i++) {
4996 struct blame *blame = view->line[i].data;
4998 if (blame->commit && blame->commit->id[0])
4999 blame->commit->id[0] = 0;
5000 else
5001 blame->commit = NULL;
5004 /* Second pass: free existing references. */
5005 for (i = 0; i < view->lines; i++) {
5006 struct blame *blame = view->line[i].data;
5008 if (blame->commit)
5009 free(blame->commit);
5012 string_format(view->vid, "%s", opt_file);
5013 string_format(view->ref, "%s ...", opt_file);
5015 return TRUE;
5018 static struct blame_commit *
5019 get_blame_commit(struct view *view, const char *id)
5021 size_t i;
5023 for (i = 0; i < view->lines; i++) {
5024 struct blame *blame = view->line[i].data;
5026 if (!blame->commit)
5027 continue;
5029 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5030 return blame->commit;
5034 struct blame_commit *commit = calloc(1, sizeof(*commit));
5036 if (commit)
5037 string_ncopy(commit->id, id, SIZEOF_REV);
5038 return commit;
5042 static struct blame_commit *
5043 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5045 struct blame_header header;
5046 struct blame_commit *commit;
5047 struct blame *blame;
5049 if (!parse_blame_header(&header, text, view->lines))
5050 return NULL;
5052 commit = get_blame_commit(view, text);
5053 if (!commit)
5054 return NULL;
5056 state->blamed += header.group;
5057 while (header.group--) {
5058 struct line *line = &view->line[header.lineno + header.group - 1];
5060 blame = line->data;
5061 blame->commit = commit;
5062 blame->lineno = header.orig_lineno + header.group - 1;
5063 line->dirty = 1;
5066 return commit;
5069 static bool
5070 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5072 if (!line) {
5073 const char *blame_argv[] = {
5074 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5075 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5078 if (view->lines == 0 && !view->prev)
5079 die("No blame exist for %s", view->vid);
5081 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5082 report("Failed to load blame data");
5083 return TRUE;
5086 if (opt_goto_line > 0) {
5087 select_view_line(view, opt_goto_line);
5088 opt_goto_line = 0;
5091 state->done_reading = TRUE;
5092 return FALSE;
5094 } else {
5095 size_t linelen = strlen(line);
5096 struct blame *blame = malloc(sizeof(*blame) + linelen);
5098 if (!blame)
5099 return FALSE;
5101 blame->commit = NULL;
5102 strncpy(blame->text, line, linelen);
5103 blame->text[linelen] = 0;
5104 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5108 static bool
5109 blame_read(struct view *view, char *line)
5111 struct blame_state *state = view->private;
5113 if (!state->done_reading)
5114 return blame_read_file(view, line, state);
5116 if (!line) {
5117 state->auto_filename_display = blame_detect_filename_display(view);
5118 string_format(view->ref, "%s", view->vid);
5119 if (view_is_displayed(view)) {
5120 update_view_title(view);
5121 redraw_view_from(view, 0);
5123 return TRUE;
5126 if (!state->commit) {
5127 state->commit = read_blame_commit(view, line, state);
5128 string_format(view->ref, "%s %2d%%", view->vid,
5129 view->lines ? state->blamed * 100 / view->lines : 0);
5131 } else if (parse_blame_info(state->commit, line)) {
5132 state->commit = NULL;
5135 return TRUE;
5138 static bool
5139 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5141 struct blame_state *state = view->private;
5142 struct blame *blame = line->data;
5143 struct time *time = NULL;
5144 const char *id = NULL, *author = NULL, *filename = NULL;
5145 enum line_type id_type = LINE_BLAME_ID;
5146 static const enum line_type blame_colors[] = {
5147 LINE_PALETTE_0,
5148 LINE_PALETTE_1,
5149 LINE_PALETTE_2,
5150 LINE_PALETTE_3,
5151 LINE_PALETTE_4,
5152 LINE_PALETTE_5,
5153 LINE_PALETTE_6,
5156 #define BLAME_COLOR(i) \
5157 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5159 if (blame->commit && *blame->commit->filename) {
5160 id = blame->commit->id;
5161 author = blame->commit->author;
5162 filename = blame->commit->filename;
5163 time = &blame->commit->time;
5164 id_type = BLAME_COLOR((long) blame->commit);
5167 if (draw_date(view, time))
5168 return TRUE;
5170 if (draw_author(view, author))
5171 return TRUE;
5173 if (draw_filename(view, filename, state->auto_filename_display))
5174 return TRUE;
5176 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5177 return TRUE;
5179 if (draw_lineno(view, lineno))
5180 return TRUE;
5182 draw_text(view, LINE_DEFAULT, blame->text);
5183 return TRUE;
5186 static bool
5187 check_blame_commit(struct blame *blame, bool check_null_id)
5189 if (!blame->commit)
5190 report("Commit data not loaded yet");
5191 else if (check_null_id && string_rev_is_null(blame->commit->id))
5192 report("No commit exist for the selected line");
5193 else
5194 return TRUE;
5195 return FALSE;
5198 static void
5199 setup_blame_parent_line(struct view *view, struct blame *blame)
5201 char from[SIZEOF_REF + SIZEOF_STR];
5202 char to[SIZEOF_REF + SIZEOF_STR];
5203 const char *diff_tree_argv[] = {
5204 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5205 "--no-color", "-U0", from, to, "--", NULL
5207 struct io io;
5208 int parent_lineno = -1;
5209 int blamed_lineno = -1;
5210 char *line;
5212 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5213 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5214 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5215 return;
5217 while ((line = io_get(&io, '\n', TRUE))) {
5218 if (*line == '@') {
5219 char *pos = strchr(line, '+');
5221 parent_lineno = atoi(line + 4);
5222 if (pos)
5223 blamed_lineno = atoi(pos + 1);
5225 } else if (*line == '+' && parent_lineno != -1) {
5226 if (blame->lineno == blamed_lineno - 1 &&
5227 !strcmp(blame->text, line + 1)) {
5228 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5229 break;
5231 blamed_lineno++;
5235 io_done(&io);
5238 static enum request
5239 blame_request(struct view *view, enum request request, struct line *line)
5241 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5242 struct blame *blame = line->data;
5244 switch (request) {
5245 case REQ_VIEW_BLAME:
5246 if (check_blame_commit(blame, TRUE)) {
5247 string_copy(opt_ref, blame->commit->id);
5248 string_copy(opt_file, blame->commit->filename);
5249 if (blame->lineno)
5250 view->pos.lineno = blame->lineno;
5251 reload_view(view);
5253 break;
5255 case REQ_PARENT:
5256 if (!check_blame_commit(blame, TRUE))
5257 break;
5258 if (!*blame->commit->parent_id) {
5259 report("The selected commit has no parents");
5260 } else {
5261 string_copy_rev(opt_ref, blame->commit->parent_id);
5262 string_copy(opt_file, blame->commit->parent_filename);
5263 setup_blame_parent_line(view, blame);
5264 opt_goto_line = blame->lineno;
5265 reload_view(view);
5267 break;
5269 case REQ_ENTER:
5270 if (!check_blame_commit(blame, FALSE))
5271 break;
5273 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5274 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5275 break;
5277 if (string_rev_is_null(blame->commit->id)) {
5278 struct view *diff = VIEW(REQ_VIEW_DIFF);
5279 const char *diff_parent_argv[] = {
5280 GIT_DIFF_BLAME(opt_diff_context_arg,
5281 opt_ignore_space_arg, view->vid)
5283 const char *diff_no_parent_argv[] = {
5284 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5285 opt_ignore_space_arg, view->vid)
5287 const char **diff_index_argv = *blame->commit->parent_id
5288 ? diff_parent_argv : diff_no_parent_argv;
5290 open_argv(view, diff, diff_index_argv, NULL, flags);
5291 if (diff->pipe)
5292 string_copy_rev(diff->ref, NULL_ID);
5293 } else {
5294 open_view(view, REQ_VIEW_DIFF, flags);
5296 break;
5298 default:
5299 return request;
5302 return REQ_NONE;
5305 static bool
5306 blame_grep(struct view *view, struct line *line)
5308 struct blame *blame = line->data;
5309 struct blame_commit *commit = blame->commit;
5310 const char *text[] = {
5311 blame->text,
5312 commit ? commit->title : "",
5313 commit ? commit->id : "",
5314 commit && opt_author ? commit->author : "",
5315 commit ? mkdate(&commit->time, opt_date) : "",
5316 NULL
5319 return grep_text(view, text);
5322 static void
5323 blame_select(struct view *view, struct line *line)
5325 struct blame *blame = line->data;
5326 struct blame_commit *commit = blame->commit;
5328 if (!commit)
5329 return;
5331 if (string_rev_is_null(commit->id))
5332 string_ncopy(ref_commit, "HEAD", 4);
5333 else
5334 string_copy_rev(ref_commit, commit->id);
5337 static struct view_ops blame_ops = {
5338 "line",
5339 { "blame" },
5340 VIEW_ALWAYS_LINENO,
5341 sizeof(struct blame_state),
5342 blame_open,
5343 blame_read,
5344 blame_draw,
5345 blame_request,
5346 blame_grep,
5347 blame_select,
5351 * Branch backend
5354 struct branch {
5355 const char *author; /* Author of the last commit. */
5356 struct time time; /* Date of the last activity. */
5357 const struct ref *ref; /* Name and commit ID information. */
5360 static const struct ref branch_all;
5362 static const enum sort_field branch_sort_fields[] = {
5363 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5365 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5367 struct branch_state {
5368 char id[SIZEOF_REV];
5371 static int
5372 branch_compare(const void *l1, const void *l2)
5374 const struct branch *branch1 = ((const struct line *) l1)->data;
5375 const struct branch *branch2 = ((const struct line *) l2)->data;
5377 if (branch1->ref == &branch_all)
5378 return -1;
5379 else if (branch2->ref == &branch_all)
5380 return 1;
5382 switch (get_sort_field(branch_sort_state)) {
5383 case ORDERBY_DATE:
5384 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5386 case ORDERBY_AUTHOR:
5387 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5389 case ORDERBY_NAME:
5390 default:
5391 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5395 static bool
5396 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5398 struct branch *branch = line->data;
5399 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5401 if (draw_date(view, &branch->time))
5402 return TRUE;
5404 if (draw_author(view, branch->author))
5405 return TRUE;
5407 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5408 return TRUE;
5411 static enum request
5412 branch_request(struct view *view, enum request request, struct line *line)
5414 struct branch *branch = line->data;
5416 switch (request) {
5417 case REQ_REFRESH:
5418 load_refs();
5419 refresh_view(view);
5420 return REQ_NONE;
5422 case REQ_TOGGLE_SORT_FIELD:
5423 case REQ_TOGGLE_SORT_ORDER:
5424 sort_view(view, request, &branch_sort_state, branch_compare);
5425 return REQ_NONE;
5427 case REQ_ENTER:
5429 const struct ref *ref = branch->ref;
5430 const char *all_branches_argv[] = {
5431 "git", "log", ENCODING_ARG, "--no-color",
5432 "--pretty=raw", "--parents", opt_commit_order_arg,
5433 ref == &branch_all ? "--all" : ref->name, NULL
5435 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5437 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5438 return REQ_NONE;
5440 case REQ_JUMP_COMMIT:
5442 int lineno;
5444 for (lineno = 0; lineno < view->lines; lineno++) {
5445 struct branch *branch = view->line[lineno].data;
5447 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5448 select_view_line(view, lineno);
5449 report("");
5450 return REQ_NONE;
5454 default:
5455 return request;
5459 static bool
5460 branch_read(struct view *view, char *line)
5462 struct branch_state *state = view->private;
5463 struct branch *reference;
5464 size_t i;
5466 if (!line)
5467 return TRUE;
5469 switch (get_line_type(line)) {
5470 case LINE_COMMIT:
5471 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5472 return TRUE;
5474 case LINE_AUTHOR:
5475 for (i = 0, reference = NULL; i < view->lines; i++) {
5476 struct branch *branch = view->line[i].data;
5478 if (strcmp(branch->ref->id, state->id))
5479 continue;
5481 view->line[i].dirty = TRUE;
5482 if (reference) {
5483 branch->author = reference->author;
5484 branch->time = reference->time;
5485 continue;
5488 parse_author_line(line + STRING_SIZE("author "),
5489 &branch->author, &branch->time);
5490 reference = branch;
5492 return TRUE;
5494 default:
5495 return TRUE;
5500 static bool
5501 branch_open_visitor(void *data, const struct ref *ref)
5503 struct view *view = data;
5504 struct branch *branch;
5506 if (ref->tag || ref->ltag)
5507 return TRUE;
5509 branch = calloc(1, sizeof(*branch));
5510 if (!branch)
5511 return FALSE;
5513 branch->ref = ref;
5514 return !!add_line_data(view, branch, LINE_DEFAULT);
5517 static bool
5518 branch_open(struct view *view, enum open_flags flags)
5520 const char *branch_log[] = {
5521 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5522 "--simplify-by-decoration", "--all", NULL
5525 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5526 report("Failed to load branch data");
5527 return FALSE;
5530 branch_open_visitor(view, &branch_all);
5531 foreach_ref(branch_open_visitor, view);
5533 return TRUE;
5536 static bool
5537 branch_grep(struct view *view, struct line *line)
5539 struct branch *branch = line->data;
5540 const char *text[] = {
5541 branch->ref->name,
5542 mkauthor(branch->author, opt_author_cols, opt_author),
5543 NULL
5546 return grep_text(view, text);
5549 static void
5550 branch_select(struct view *view, struct line *line)
5552 struct branch *branch = line->data;
5554 string_copy_rev(view->ref, branch->ref->id);
5555 string_copy_rev(ref_commit, branch->ref->id);
5556 string_copy_rev(ref_head, branch->ref->id);
5557 string_copy_rev(ref_branch, branch->ref->name);
5560 static struct view_ops branch_ops = {
5561 "branch",
5562 { "branch" },
5563 VIEW_NO_FLAGS,
5564 sizeof(struct branch_state),
5565 branch_open,
5566 branch_read,
5567 branch_draw,
5568 branch_request,
5569 branch_grep,
5570 branch_select,
5574 * Status backend
5577 struct status {
5578 char status;
5579 struct {
5580 mode_t mode;
5581 char rev[SIZEOF_REV];
5582 char name[SIZEOF_STR];
5583 } old;
5584 struct {
5585 mode_t mode;
5586 char rev[SIZEOF_REV];
5587 char name[SIZEOF_STR];
5588 } new;
5591 static char status_onbranch[SIZEOF_STR];
5592 static struct status stage_status;
5593 static enum line_type stage_line_type;
5595 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5597 /* This should work even for the "On branch" line. */
5598 static inline bool
5599 status_has_none(struct view *view, struct line *line)
5601 return line < view->line + view->lines && !line[1].data;
5604 /* Get fields from the diff line:
5605 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5607 static inline bool
5608 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5610 const char *old_mode = buf + 1;
5611 const char *new_mode = buf + 8;
5612 const char *old_rev = buf + 15;
5613 const char *new_rev = buf + 56;
5614 const char *status = buf + 97;
5616 if (bufsize < 98 ||
5617 old_mode[-1] != ':' ||
5618 new_mode[-1] != ' ' ||
5619 old_rev[-1] != ' ' ||
5620 new_rev[-1] != ' ' ||
5621 status[-1] != ' ')
5622 return FALSE;
5624 file->status = *status;
5626 string_copy_rev(file->old.rev, old_rev);
5627 string_copy_rev(file->new.rev, new_rev);
5629 file->old.mode = strtoul(old_mode, NULL, 8);
5630 file->new.mode = strtoul(new_mode, NULL, 8);
5632 file->old.name[0] = file->new.name[0] = 0;
5634 return TRUE;
5637 static bool
5638 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5640 struct status *unmerged = NULL;
5641 char *buf;
5642 struct io io;
5644 if (!io_run(&io, IO_RD, opt_cdup, argv))
5645 return FALSE;
5647 add_line_data(view, NULL, type);
5649 while ((buf = io_get(&io, 0, TRUE))) {
5650 struct status *file = unmerged;
5652 if (!file) {
5653 file = calloc(1, sizeof(*file));
5654 if (!file || !add_line_data(view, file, type))
5655 goto error_out;
5658 /* Parse diff info part. */
5659 if (status) {
5660 file->status = status;
5661 if (status == 'A')
5662 string_copy(file->old.rev, NULL_ID);
5664 } else if (!file->status || file == unmerged) {
5665 if (!status_get_diff(file, buf, strlen(buf)))
5666 goto error_out;
5668 buf = io_get(&io, 0, TRUE);
5669 if (!buf)
5670 break;
5672 /* Collapse all modified entries that follow an
5673 * associated unmerged entry. */
5674 if (unmerged == file) {
5675 unmerged->status = 'U';
5676 unmerged = NULL;
5677 } else if (file->status == 'U') {
5678 unmerged = file;
5682 /* Grab the old name for rename/copy. */
5683 if (!*file->old.name &&
5684 (file->status == 'R' || file->status == 'C')) {
5685 string_ncopy(file->old.name, buf, strlen(buf));
5687 buf = io_get(&io, 0, TRUE);
5688 if (!buf)
5689 break;
5692 /* git-ls-files just delivers a NUL separated list of
5693 * file names similar to the second half of the
5694 * git-diff-* output. */
5695 string_ncopy(file->new.name, buf, strlen(buf));
5696 if (!*file->old.name)
5697 string_copy(file->old.name, file->new.name);
5698 file = NULL;
5701 if (io_error(&io)) {
5702 error_out:
5703 io_done(&io);
5704 return FALSE;
5707 if (!view->line[view->lines - 1].data)
5708 add_line_data(view, NULL, LINE_STAT_NONE);
5710 io_done(&io);
5711 return TRUE;
5714 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5715 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5717 static const char *status_list_other_argv[] = {
5718 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5721 static const char *status_list_no_head_argv[] = {
5722 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5725 static const char *update_index_argv[] = {
5726 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5729 /* Restore the previous line number to stay in the context or select a
5730 * line with something that can be updated. */
5731 static void
5732 status_restore(struct view *view)
5734 if (!check_position(&view->prev_pos))
5735 return;
5737 if (view->prev_pos.lineno >= view->lines)
5738 view->prev_pos.lineno = view->lines - 1;
5739 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5740 view->prev_pos.lineno++;
5741 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5742 view->prev_pos.lineno--;
5744 /* If the above fails, always skip the "On branch" line. */
5745 if (view->prev_pos.lineno < view->lines)
5746 view->pos.lineno = view->prev_pos.lineno;
5747 else
5748 view->pos.lineno = 1;
5750 if (view->prev_pos.offset > view->pos.lineno)
5751 view->pos.offset = view->pos.lineno;
5752 else if (view->prev_pos.offset < view->lines)
5753 view->pos.offset = view->prev_pos.offset;
5755 clear_position(&view->prev_pos);
5758 static void
5759 status_update_onbranch(void)
5761 static const char *paths[][2] = {
5762 { "rebase-apply/rebasing", "Rebasing" },
5763 { "rebase-apply/applying", "Applying mailbox" },
5764 { "rebase-apply/", "Rebasing mailbox" },
5765 { "rebase-merge/interactive", "Interactive rebase" },
5766 { "rebase-merge/", "Rebase merge" },
5767 { "MERGE_HEAD", "Merging" },
5768 { "BISECT_LOG", "Bisecting" },
5769 { "HEAD", "On branch" },
5771 char buf[SIZEOF_STR];
5772 struct stat stat;
5773 int i;
5775 if (is_initial_commit()) {
5776 string_copy(status_onbranch, "Initial commit");
5777 return;
5780 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5781 char *head = opt_head;
5783 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5784 lstat(buf, &stat) < 0)
5785 continue;
5787 if (!*opt_head) {
5788 struct io io;
5790 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5791 io_read_buf(&io, buf, sizeof(buf))) {
5792 head = buf;
5793 if (!prefixcmp(head, "refs/heads/"))
5794 head += STRING_SIZE("refs/heads/");
5798 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5799 string_copy(status_onbranch, opt_head);
5800 return;
5803 string_copy(status_onbranch, "Not currently on any branch");
5806 /* First parse staged info using git-diff-index(1), then parse unstaged
5807 * info using git-diff-files(1), and finally untracked files using
5808 * git-ls-files(1). */
5809 static bool
5810 status_open(struct view *view, enum open_flags flags)
5812 const char **staged_argv = is_initial_commit() ?
5813 status_list_no_head_argv : status_diff_index_argv;
5814 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
5816 if (opt_is_inside_work_tree == FALSE) {
5817 report("The status view requires a working tree");
5818 return FALSE;
5821 reset_view(view);
5823 add_line_data(view, NULL, LINE_STAT_HEAD);
5824 status_update_onbranch();
5826 io_run_bg(update_index_argv);
5828 if (!opt_untracked_dirs_content)
5829 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5831 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
5832 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5833 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
5834 report("Failed to load status data");
5835 return FALSE;
5838 /* Restore the exact position or use the specialized restore
5839 * mode? */
5840 status_restore(view);
5841 return TRUE;
5844 static bool
5845 status_draw(struct view *view, struct line *line, unsigned int lineno)
5847 struct status *status = line->data;
5848 enum line_type type;
5849 const char *text;
5851 if (!status) {
5852 switch (line->type) {
5853 case LINE_STAT_STAGED:
5854 type = LINE_STAT_SECTION;
5855 text = "Changes to be committed:";
5856 break;
5858 case LINE_STAT_UNSTAGED:
5859 type = LINE_STAT_SECTION;
5860 text = "Changed but not updated:";
5861 break;
5863 case LINE_STAT_UNTRACKED:
5864 type = LINE_STAT_SECTION;
5865 text = "Untracked files:";
5866 break;
5868 case LINE_STAT_NONE:
5869 type = LINE_DEFAULT;
5870 text = " (no files)";
5871 break;
5873 case LINE_STAT_HEAD:
5874 type = LINE_STAT_HEAD;
5875 text = status_onbranch;
5876 break;
5878 default:
5879 return FALSE;
5881 } else {
5882 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5884 buf[0] = status->status;
5885 if (draw_text(view, line->type, buf))
5886 return TRUE;
5887 type = LINE_DEFAULT;
5888 text = status->new.name;
5891 draw_text(view, type, text);
5892 return TRUE;
5895 static enum request
5896 status_enter(struct view *view, struct line *line)
5898 struct status *status = line->data;
5899 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5901 if (line->type == LINE_STAT_NONE ||
5902 (!status && line[1].type == LINE_STAT_NONE)) {
5903 report("No file to diff");
5904 return REQ_NONE;
5907 switch (line->type) {
5908 case LINE_STAT_STAGED:
5909 case LINE_STAT_UNSTAGED:
5910 break;
5912 case LINE_STAT_UNTRACKED:
5913 if (!status) {
5914 report("No file to show");
5915 return REQ_NONE;
5918 if (!suffixcmp(status->new.name, -1, "/")) {
5919 report("Cannot display a directory");
5920 return REQ_NONE;
5922 break;
5924 case LINE_STAT_HEAD:
5925 return REQ_NONE;
5927 default:
5928 die("line type %d not handled in switch", line->type);
5931 if (status) {
5932 stage_status = *status;
5933 } else {
5934 memset(&stage_status, 0, sizeof(stage_status));
5937 stage_line_type = line->type;
5939 open_view(view, REQ_VIEW_STAGE, flags);
5940 return REQ_NONE;
5943 static bool
5944 status_exists(struct view *view, struct status *status, enum line_type type)
5946 unsigned long lineno;
5948 for (lineno = 0; lineno < view->lines; lineno++) {
5949 struct line *line = &view->line[lineno];
5950 struct status *pos = line->data;
5952 if (line->type != type)
5953 continue;
5954 if (!pos && (!status || !status->status) && line[1].data) {
5955 select_view_line(view, lineno);
5956 return TRUE;
5958 if (pos && !strcmp(status->new.name, pos->new.name)) {
5959 select_view_line(view, lineno);
5960 return TRUE;
5964 return FALSE;
5968 static bool
5969 status_update_prepare(struct io *io, enum line_type type)
5971 const char *staged_argv[] = {
5972 "git", "update-index", "-z", "--index-info", NULL
5974 const char *others_argv[] = {
5975 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5978 switch (type) {
5979 case LINE_STAT_STAGED:
5980 return io_run(io, IO_WR, opt_cdup, staged_argv);
5982 case LINE_STAT_UNSTAGED:
5983 case LINE_STAT_UNTRACKED:
5984 return io_run(io, IO_WR, opt_cdup, others_argv);
5986 default:
5987 die("line type %d not handled in switch", type);
5988 return FALSE;
5992 static bool
5993 status_update_write(struct io *io, struct status *status, enum line_type type)
5995 switch (type) {
5996 case LINE_STAT_STAGED:
5997 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5998 status->old.rev, status->old.name, 0);
6000 case LINE_STAT_UNSTAGED:
6001 case LINE_STAT_UNTRACKED:
6002 return io_printf(io, "%s%c", status->new.name, 0);
6004 default:
6005 die("line type %d not handled in switch", type);
6006 return FALSE;
6010 static bool
6011 status_update_file(struct status *status, enum line_type type)
6013 struct io io;
6014 bool result;
6016 if (!status_update_prepare(&io, type))
6017 return FALSE;
6019 result = status_update_write(&io, status, type);
6020 return io_done(&io) && result;
6023 static bool
6024 status_update_files(struct view *view, struct line *line)
6026 char buf[sizeof(view->ref)];
6027 struct io io;
6028 bool result = TRUE;
6029 struct line *pos;
6030 int files = 0;
6031 int file, done;
6032 int cursor_y = -1, cursor_x = -1;
6034 if (!status_update_prepare(&io, line->type))
6035 return FALSE;
6037 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
6038 files++;
6040 string_copy(buf, view->ref);
6041 getsyx(cursor_y, cursor_x);
6042 for (file = 0, done = 5; result && file < files; line++, file++) {
6043 int almost_done = file * 100 / files;
6045 if (almost_done > done) {
6046 done = almost_done;
6047 string_format(view->ref, "updating file %u of %u (%d%% done)",
6048 file, files, done);
6049 update_view_title(view);
6050 setsyx(cursor_y, cursor_x);
6051 doupdate();
6053 result = status_update_write(&io, line->data, line->type);
6055 string_copy(view->ref, buf);
6057 return io_done(&io) && result;
6060 static bool
6061 status_update(struct view *view)
6063 struct line *line = &view->line[view->pos.lineno];
6065 assert(view->lines);
6067 if (!line->data) {
6068 /* This should work even for the "On branch" line. */
6069 if (line < view->line + view->lines && !line[1].data) {
6070 report("Nothing to update");
6071 return FALSE;
6074 if (!status_update_files(view, line + 1)) {
6075 report("Failed to update file status");
6076 return FALSE;
6079 } else if (!status_update_file(line->data, line->type)) {
6080 report("Failed to update file status");
6081 return FALSE;
6084 return TRUE;
6087 static bool
6088 status_revert(struct status *status, enum line_type type, bool has_none)
6090 if (!status || type != LINE_STAT_UNSTAGED) {
6091 if (type == LINE_STAT_STAGED) {
6092 report("Cannot revert changes to staged files");
6093 } else if (type == LINE_STAT_UNTRACKED) {
6094 report("Cannot revert changes to untracked files");
6095 } else if (has_none) {
6096 report("Nothing to revert");
6097 } else {
6098 report("Cannot revert changes to multiple files");
6101 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6102 char mode[10] = "100644";
6103 const char *reset_argv[] = {
6104 "git", "update-index", "--cacheinfo", mode,
6105 status->old.rev, status->old.name, NULL
6107 const char *checkout_argv[] = {
6108 "git", "checkout", "--", status->old.name, NULL
6111 if (status->status == 'U') {
6112 string_format(mode, "%5o", status->old.mode);
6114 if (status->old.mode == 0 && status->new.mode == 0) {
6115 reset_argv[2] = "--force-remove";
6116 reset_argv[3] = status->old.name;
6117 reset_argv[4] = NULL;
6120 if (!io_run_fg(reset_argv, opt_cdup))
6121 return FALSE;
6122 if (status->old.mode == 0 && status->new.mode == 0)
6123 return TRUE;
6126 return io_run_fg(checkout_argv, opt_cdup);
6129 return FALSE;
6132 static enum request
6133 status_request(struct view *view, enum request request, struct line *line)
6135 struct status *status = line->data;
6137 switch (request) {
6138 case REQ_STATUS_UPDATE:
6139 if (!status_update(view))
6140 return REQ_NONE;
6141 break;
6143 case REQ_STATUS_REVERT:
6144 if (!status_revert(status, line->type, status_has_none(view, line)))
6145 return REQ_NONE;
6146 break;
6148 case REQ_STATUS_MERGE:
6149 if (!status || status->status != 'U') {
6150 report("Merging only possible for files with unmerged status ('U').");
6151 return REQ_NONE;
6153 open_mergetool(status->new.name);
6154 break;
6156 case REQ_EDIT:
6157 if (!status)
6158 return request;
6159 if (status->status == 'D') {
6160 report("File has been deleted.");
6161 return REQ_NONE;
6164 open_editor(status->new.name);
6165 break;
6167 case REQ_VIEW_BLAME:
6168 if (status)
6169 opt_ref[0] = 0;
6170 return request;
6172 case REQ_ENTER:
6173 /* After returning the status view has been split to
6174 * show the stage view. No further reloading is
6175 * necessary. */
6176 return status_enter(view, line);
6178 case REQ_REFRESH:
6179 /* Simply reload the view. */
6180 break;
6182 default:
6183 return request;
6186 refresh_view(view);
6188 return REQ_NONE;
6191 static void
6192 status_select(struct view *view, struct line *line)
6194 struct status *status = line->data;
6195 char file[SIZEOF_STR] = "all files";
6196 const char *text;
6197 const char *key;
6199 if (status && !string_format(file, "'%s'", status->new.name))
6200 return;
6202 if (!status && line[1].type == LINE_STAT_NONE)
6203 line++;
6205 switch (line->type) {
6206 case LINE_STAT_STAGED:
6207 text = "Press %s to unstage %s for commit";
6208 break;
6210 case LINE_STAT_UNSTAGED:
6211 text = "Press %s to stage %s for commit";
6212 break;
6214 case LINE_STAT_UNTRACKED:
6215 text = "Press %s to stage %s for addition";
6216 break;
6218 case LINE_STAT_HEAD:
6219 case LINE_STAT_NONE:
6220 text = "Nothing to update";
6221 break;
6223 default:
6224 die("line type %d not handled in switch", line->type);
6227 if (status && status->status == 'U') {
6228 text = "Press %s to resolve conflict in %s";
6229 key = get_view_key(view, REQ_STATUS_MERGE);
6231 } else {
6232 key = get_view_key(view, REQ_STATUS_UPDATE);
6235 string_format(view->ref, text, key, file);
6236 if (status)
6237 string_copy(opt_file, status->new.name);
6240 static bool
6241 status_grep(struct view *view, struct line *line)
6243 struct status *status = line->data;
6245 if (status) {
6246 const char buf[2] = { status->status, 0 };
6247 const char *text[] = { status->new.name, buf, NULL };
6249 return grep_text(view, text);
6252 return FALSE;
6255 static struct view_ops status_ops = {
6256 "file",
6257 { "status" },
6258 VIEW_CUSTOM_STATUS,
6260 status_open,
6261 NULL,
6262 status_draw,
6263 status_request,
6264 status_grep,
6265 status_select,
6269 struct stage_state {
6270 struct diff_state diff;
6271 size_t chunks;
6272 int *chunk;
6275 static bool
6276 stage_diff_write(struct io *io, struct line *line, struct line *end)
6278 while (line < end) {
6279 if (!io_write(io, line->data, strlen(line->data)) ||
6280 !io_write(io, "\n", 1))
6281 return FALSE;
6282 line++;
6283 if (line->type == LINE_DIFF_CHUNK ||
6284 line->type == LINE_DIFF_HEADER)
6285 break;
6288 return TRUE;
6291 static bool
6292 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6294 const char *apply_argv[SIZEOF_ARG] = {
6295 "git", "apply", "--whitespace=nowarn", NULL
6297 struct line *diff_hdr;
6298 struct io io;
6299 int argc = 3;
6301 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6302 if (!diff_hdr)
6303 return FALSE;
6305 if (!revert)
6306 apply_argv[argc++] = "--cached";
6307 if (line != NULL)
6308 apply_argv[argc++] = "--unidiff-zero";
6309 if (revert || stage_line_type == LINE_STAT_STAGED)
6310 apply_argv[argc++] = "-R";
6311 apply_argv[argc++] = "-";
6312 apply_argv[argc++] = NULL;
6313 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6314 return FALSE;
6316 if (line != NULL) {
6317 int lineno = 0;
6318 struct line *context = chunk + 1;
6319 const char *markers[] = {
6320 line->type == LINE_DIFF_DEL ? "" : ",0",
6321 line->type == LINE_DIFF_DEL ? ",0" : "",
6324 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6326 while (context < line) {
6327 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6328 break;
6329 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6330 lineno++;
6332 context++;
6335 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6336 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6337 lineno, markers[0], lineno, markers[1]) ||
6338 !stage_diff_write(&io, line, line + 1)) {
6339 chunk = NULL;
6341 } else {
6342 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6343 !stage_diff_write(&io, chunk, view->line + view->lines))
6344 chunk = NULL;
6347 io_done(&io);
6348 io_run_bg(update_index_argv);
6350 return chunk ? TRUE : FALSE;
6353 static bool
6354 stage_update(struct view *view, struct line *line, bool single)
6356 struct line *chunk = NULL;
6358 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6359 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6361 if (chunk) {
6362 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6363 report("Failed to apply chunk");
6364 return FALSE;
6367 } else if (!stage_status.status) {
6368 view = view->parent;
6370 for (line = view->line; line < view->line + view->lines; line++)
6371 if (line->type == stage_line_type)
6372 break;
6374 if (!status_update_files(view, line + 1)) {
6375 report("Failed to update files");
6376 return FALSE;
6379 } else if (!status_update_file(&stage_status, stage_line_type)) {
6380 report("Failed to update file");
6381 return FALSE;
6384 return TRUE;
6387 static bool
6388 stage_revert(struct view *view, struct line *line)
6390 struct line *chunk = NULL;
6392 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6393 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6395 if (chunk) {
6396 if (!prompt_yesno("Are you sure you want to revert changes?"))
6397 return FALSE;
6399 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6400 report("Failed to revert chunk");
6401 return FALSE;
6403 return TRUE;
6405 } else {
6406 return status_revert(stage_status.status ? &stage_status : NULL,
6407 stage_line_type, FALSE);
6412 static void
6413 stage_next(struct view *view, struct line *line)
6415 struct stage_state *state = view->private;
6416 int i;
6418 if (!state->chunks) {
6419 for (line = view->line; line < view->line + view->lines; line++) {
6420 if (line->type != LINE_DIFF_CHUNK)
6421 continue;
6423 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6424 report("Allocation failure");
6425 return;
6428 state->chunk[state->chunks++] = line - view->line;
6432 for (i = 0; i < state->chunks; i++) {
6433 if (state->chunk[i] > view->pos.lineno) {
6434 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6435 report("Chunk %d of %d", i + 1, state->chunks);
6436 return;
6440 report("No next chunk found");
6443 static enum request
6444 stage_request(struct view *view, enum request request, struct line *line)
6446 switch (request) {
6447 case REQ_STATUS_UPDATE:
6448 if (!stage_update(view, line, FALSE))
6449 return REQ_NONE;
6450 break;
6452 case REQ_STATUS_REVERT:
6453 if (!stage_revert(view, line))
6454 return REQ_NONE;
6455 break;
6457 case REQ_STAGE_UPDATE_LINE:
6458 if (stage_line_type == LINE_STAT_UNTRACKED ||
6459 stage_status.status == 'A') {
6460 report("Staging single lines is not supported for new files");
6461 return REQ_NONE;
6463 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6464 report("Please select a change to stage");
6465 return REQ_NONE;
6467 if (!stage_update(view, line, TRUE))
6468 return REQ_NONE;
6469 break;
6471 case REQ_STAGE_NEXT:
6472 if (stage_line_type == LINE_STAT_UNTRACKED) {
6473 report("File is untracked; press %s to add",
6474 get_view_key(view, REQ_STATUS_UPDATE));
6475 return REQ_NONE;
6477 stage_next(view, line);
6478 return REQ_NONE;
6480 case REQ_EDIT:
6481 if (!stage_status.new.name[0])
6482 return request;
6483 if (stage_status.status == 'D') {
6484 report("File has been deleted.");
6485 return REQ_NONE;
6488 open_editor(stage_status.new.name);
6489 break;
6491 case REQ_REFRESH:
6492 /* Reload everything ... */
6493 break;
6495 case REQ_VIEW_BLAME:
6496 if (stage_status.new.name[0]) {
6497 string_copy(opt_file, stage_status.new.name);
6498 opt_ref[0] = 0;
6500 return request;
6502 case REQ_ENTER:
6503 return diff_common_enter(view, request, line);
6505 case REQ_DIFF_CONTEXT_UP:
6506 case REQ_DIFF_CONTEXT_DOWN:
6507 if (!update_diff_context(request))
6508 return REQ_NONE;
6509 break;
6511 default:
6512 return request;
6515 refresh_view(view->parent);
6517 /* Check whether the staged entry still exists, and close the
6518 * stage view if it doesn't. */
6519 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6520 status_restore(view->parent);
6521 return REQ_VIEW_CLOSE;
6524 refresh_view(view);
6526 return REQ_NONE;
6529 static bool
6530 stage_open(struct view *view, enum open_flags flags)
6532 static const char *no_head_diff_argv[] = {
6533 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6534 stage_status.new.name)
6536 static const char *index_show_argv[] = {
6537 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6538 stage_status.old.name, stage_status.new.name)
6540 static const char *files_show_argv[] = {
6541 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6542 stage_status.old.name, stage_status.new.name)
6544 /* Diffs for unmerged entries are empty when passing the new
6545 * path, so leave out the new path. */
6546 static const char *files_unmerged_argv[] = {
6547 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6548 opt_diff_context_arg, opt_ignore_space_arg, "--",
6549 stage_status.old.name, NULL
6551 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6552 const char **argv = NULL;
6553 const char *info;
6555 if (!stage_line_type) {
6556 report("No stage content, press %s to open the status view and choose file",
6557 get_view_key(view, REQ_VIEW_STATUS));
6558 return FALSE;
6561 view->encoding = NULL;
6563 switch (stage_line_type) {
6564 case LINE_STAT_STAGED:
6565 if (is_initial_commit()) {
6566 argv = no_head_diff_argv;
6567 } else {
6568 argv = index_show_argv;
6570 if (stage_status.status)
6571 info = "Staged changes to %s";
6572 else
6573 info = "Staged changes";
6574 break;
6576 case LINE_STAT_UNSTAGED:
6577 if (stage_status.status != 'U')
6578 argv = files_show_argv;
6579 else
6580 argv = files_unmerged_argv;
6581 if (stage_status.status)
6582 info = "Unstaged changes to %s";
6583 else
6584 info = "Unstaged changes";
6585 break;
6587 case LINE_STAT_UNTRACKED:
6588 info = "Untracked file %s";
6589 argv = file_argv;
6590 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6591 break;
6593 case LINE_STAT_HEAD:
6594 default:
6595 die("line type %d not handled in switch", stage_line_type);
6598 if (!string_format(view->ref, info, stage_status.new.name)
6599 || !argv_copy(&view->argv, argv)) {
6600 report("Failed to open staged view");
6601 return FALSE;
6604 view->vid[0] = 0;
6605 view->dir = opt_cdup;
6606 return begin_update(view, NULL, NULL, flags);
6609 static bool
6610 stage_read(struct view *view, char *data)
6612 struct stage_state *state = view->private;
6614 if (data && diff_common_read(view, data, &state->diff))
6615 return TRUE;
6617 return pager_read(view, data);
6620 static struct view_ops stage_ops = {
6621 "line",
6622 { "stage" },
6623 VIEW_DIFF_LIKE,
6624 sizeof(struct stage_state),
6625 stage_open,
6626 stage_read,
6627 diff_common_draw,
6628 stage_request,
6629 pager_grep,
6630 pager_select,
6635 * Revision graph
6638 static const enum line_type graph_colors[] = {
6639 LINE_PALETTE_0,
6640 LINE_PALETTE_1,
6641 LINE_PALETTE_2,
6642 LINE_PALETTE_3,
6643 LINE_PALETTE_4,
6644 LINE_PALETTE_5,
6645 LINE_PALETTE_6,
6648 static enum line_type get_graph_color(struct graph_symbol *symbol)
6650 if (symbol->commit)
6651 return LINE_GRAPH_COMMIT;
6652 assert(symbol->color < ARRAY_SIZE(graph_colors));
6653 return graph_colors[symbol->color];
6656 static bool
6657 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6659 const char *chars = graph_symbol_to_utf8(symbol);
6661 return draw_text(view, color, chars + !!first);
6664 static bool
6665 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6667 const char *chars = graph_symbol_to_ascii(symbol);
6669 return draw_text(view, color, chars + !!first);
6672 static bool
6673 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6675 const chtype *chars = graph_symbol_to_chtype(symbol);
6677 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6680 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6682 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6684 static const draw_graph_fn fns[] = {
6685 draw_graph_ascii,
6686 draw_graph_chtype,
6687 draw_graph_utf8
6689 draw_graph_fn fn = fns[opt_line_graphics];
6690 int i;
6692 for (i = 0; i < canvas->size; i++) {
6693 struct graph_symbol *symbol = &canvas->symbols[i];
6694 enum line_type color = get_graph_color(symbol);
6696 if (fn(view, symbol, color, i == 0))
6697 return TRUE;
6700 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6704 * Main view backend
6707 struct commit {
6708 char id[SIZEOF_REV]; /* SHA1 ID. */
6709 char title[128]; /* First line of the commit message. */
6710 const char *author; /* Author of the commit. */
6711 struct time time; /* Date from the author ident. */
6712 struct ref_list *refs; /* Repository references. */
6713 struct graph_canvas graph; /* Ancestry chain graphics. */
6716 static struct commit *
6717 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6719 struct graph *graph = view->private;
6720 struct commit *commit;
6722 commit = calloc(1, sizeof(struct commit));
6723 if (!commit)
6724 return NULL;
6726 string_copy_rev(commit->id, ids);
6727 commit->refs = get_ref_list(commit->id);
6728 add_line_data(view, commit, type);
6729 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6730 return commit;
6733 bool
6734 main_has_changes(const char *argv[])
6736 struct io io;
6738 if (!io_run(&io, IO_BG, NULL, argv, -1))
6739 return FALSE;
6740 io_done(&io);
6741 return io.status == 1;
6744 static void
6745 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6747 char ids[SIZEOF_STR] = NULL_ID " ";
6748 struct graph *graph = view->private;
6749 struct commit *commit;
6750 struct timeval now;
6751 struct timezone tz;
6753 if (!parent)
6754 return;
6756 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6758 commit = main_add_commit(view, type, ids, FALSE);
6759 if (!commit)
6760 return;
6762 if (!gettimeofday(&now, &tz)) {
6763 commit->time.tz = tz.tz_minuteswest * 60;
6764 commit->time.sec = now.tv_sec - commit->time.tz;
6767 commit->author = "";
6768 string_ncopy(commit->title, title, strlen(title));
6769 graph_render_parents(graph);
6772 static void
6773 main_add_changes_commits(struct view *view, const char *parent)
6775 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6776 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6777 const char *staged_parent = NULL_ID;
6778 const char *unstaged_parent = parent;
6780 if (!main_has_changes(unstaged_argv)) {
6781 unstaged_parent = NULL;
6782 staged_parent = parent;
6785 if (!main_has_changes(staged_argv)) {
6786 staged_parent = NULL;
6789 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6790 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6793 static bool
6794 main_open(struct view *view, enum open_flags flags)
6796 static const char *main_argv[] = {
6797 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6798 opt_commit_order_arg, "%(diffargs)", "%(revargs)",
6799 "--", "%(fileargs)", NULL
6802 return begin_update(view, NULL, main_argv, flags);
6805 static bool
6806 main_draw(struct view *view, struct line *line, unsigned int lineno)
6808 struct commit *commit = line->data;
6810 if (!commit->author)
6811 return FALSE;
6813 if (draw_lineno(view, lineno))
6814 return TRUE;
6816 if (draw_date(view, &commit->time))
6817 return TRUE;
6819 if (draw_author(view, commit->author))
6820 return TRUE;
6822 if (opt_rev_graph && draw_graph(view, &commit->graph))
6823 return TRUE;
6825 if (draw_refs(view, commit->refs))
6826 return TRUE;
6828 draw_text(view, LINE_DEFAULT, commit->title);
6829 return TRUE;
6832 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6833 static bool
6834 main_read(struct view *view, char *line)
6836 struct graph *graph = view->private;
6837 enum line_type type;
6838 struct commit *commit;
6839 static bool in_header;
6841 if (!line) {
6842 if (!view->lines && !view->prev)
6843 die("No revisions match the given arguments.");
6844 if (view->lines > 0) {
6845 commit = view->line[view->lines - 1].data;
6846 view->line[view->lines - 1].dirty = 1;
6847 if (!commit->author) {
6848 view->lines--;
6849 free(commit);
6853 done_graph(graph);
6854 return TRUE;
6857 type = get_line_type(line);
6858 if (type == LINE_COMMIT) {
6859 bool is_boundary;
6861 in_header = TRUE;
6862 line += STRING_SIZE("commit ");
6863 is_boundary = *line == '-';
6864 if (is_boundary)
6865 line++;
6867 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6868 main_add_changes_commits(view, line);
6870 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6873 if (!view->lines)
6874 return TRUE;
6875 commit = view->line[view->lines - 1].data;
6877 /* Empty line separates the commit header from the log itself. */
6878 if (*line == '\0')
6879 in_header = FALSE;
6881 switch (type) {
6882 case LINE_PARENT:
6883 if (!graph->has_parents)
6884 graph_add_parent(graph, line + STRING_SIZE("parent "));
6885 break;
6887 case LINE_AUTHOR:
6888 parse_author_line(line + STRING_SIZE("author "),
6889 &commit->author, &commit->time);
6890 graph_render_parents(graph);
6891 break;
6893 default:
6894 /* Fill in the commit title if it has not already been set. */
6895 if (commit->title[0])
6896 break;
6898 /* Skip lines in the commit header. */
6899 if (in_header)
6900 break;
6902 /* Require titles to start with a non-space character at the
6903 * offset used by git log. */
6904 if (strncmp(line, " ", 4))
6905 break;
6906 line += 4;
6907 /* Well, if the title starts with a whitespace character,
6908 * try to be forgiving. Otherwise we end up with no title. */
6909 while (isspace(*line))
6910 line++;
6911 if (*line == '\0')
6912 break;
6913 /* FIXME: More graceful handling of titles; append "..." to
6914 * shortened titles, etc. */
6916 string_expand(commit->title, sizeof(commit->title), line, 1);
6917 view->line[view->lines - 1].dirty = 1;
6920 return TRUE;
6923 static enum request
6924 main_request(struct view *view, enum request request, struct line *line)
6926 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6928 switch (request) {
6929 case REQ_NEXT:
6930 case REQ_PREVIOUS:
6931 if (view_is_displayed(view) && display[0] != view)
6932 return request;
6933 /* Do not pass navigation requests to the branch view
6934 * when the main view is maximized. (GH #38) */
6935 move_view(view, request);
6936 break;
6938 case REQ_ENTER:
6939 if (view_is_displayed(view) && display[0] != view)
6940 maximize_view(view, TRUE);
6942 if (line->type == LINE_STAT_UNSTAGED
6943 || line->type == LINE_STAT_STAGED) {
6944 struct view *diff = VIEW(REQ_VIEW_DIFF);
6945 const char *diff_staged_argv[] = {
6946 GIT_DIFF_STAGED(opt_diff_context_arg,
6947 opt_ignore_space_arg, NULL, NULL)
6949 const char *diff_unstaged_argv[] = {
6950 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6951 opt_ignore_space_arg, NULL, NULL)
6953 const char **diff_argv = line->type == LINE_STAT_STAGED
6954 ? diff_staged_argv : diff_unstaged_argv;
6956 open_argv(view, diff, diff_argv, NULL, flags);
6957 break;
6960 open_view(view, REQ_VIEW_DIFF, flags);
6961 break;
6962 case REQ_REFRESH:
6963 load_refs();
6964 refresh_view(view);
6965 break;
6967 case REQ_JUMP_COMMIT:
6969 int lineno;
6971 for (lineno = 0; lineno < view->lines; lineno++) {
6972 struct commit *commit = view->line[lineno].data;
6974 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6975 select_view_line(view, lineno);
6976 report("");
6977 return REQ_NONE;
6981 report("Unable to find commit '%s'", opt_search);
6982 break;
6984 default:
6985 return request;
6988 return REQ_NONE;
6991 static bool
6992 grep_refs(struct ref_list *list, regex_t *regex)
6994 regmatch_t pmatch;
6995 size_t i;
6997 if (!opt_show_refs || !list)
6998 return FALSE;
7000 for (i = 0; i < list->size; i++) {
7001 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7002 return TRUE;
7005 return FALSE;
7008 static bool
7009 main_grep(struct view *view, struct line *line)
7011 struct commit *commit = line->data;
7012 const char *text[] = {
7013 commit->title,
7014 mkauthor(commit->author, opt_author_cols, opt_author),
7015 mkdate(&commit->time, opt_date),
7016 NULL
7019 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7022 static void
7023 main_select(struct view *view, struct line *line)
7025 struct commit *commit = line->data;
7027 string_copy_rev(view->ref, commit->id);
7028 string_copy_rev(ref_commit, view->ref);
7031 static struct view_ops main_ops = {
7032 "commit",
7033 { "main" },
7034 VIEW_NO_FLAGS,
7035 sizeof(struct graph),
7036 main_open,
7037 main_read,
7038 main_draw,
7039 main_request,
7040 main_grep,
7041 main_select,
7046 * Status management
7049 /* Whether or not the curses interface has been initialized. */
7050 static bool cursed = FALSE;
7052 /* Terminal hacks and workarounds. */
7053 static bool use_scroll_redrawwin;
7054 static bool use_scroll_status_wclear;
7056 /* The status window is used for polling keystrokes. */
7057 static WINDOW *status_win;
7059 /* Reading from the prompt? */
7060 static bool input_mode = FALSE;
7062 static bool status_empty = FALSE;
7064 /* Update status and title window. */
7065 static void
7066 report(const char *msg, ...)
7068 struct view *view = display[current_view];
7070 if (input_mode)
7071 return;
7073 if (!view) {
7074 char buf[SIZEOF_STR];
7075 int retval;
7077 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7078 die("%s", buf);
7081 if (!status_empty || *msg) {
7082 va_list args;
7084 va_start(args, msg);
7086 wmove(status_win, 0, 0);
7087 if (view->has_scrolled && use_scroll_status_wclear)
7088 wclear(status_win);
7089 if (*msg) {
7090 vwprintw(status_win, msg, args);
7091 status_empty = FALSE;
7092 } else {
7093 status_empty = TRUE;
7095 wclrtoeol(status_win);
7096 wnoutrefresh(status_win);
7098 va_end(args);
7101 update_view_title(view);
7104 static void
7105 init_display(void)
7107 const char *term;
7108 int x, y;
7110 /* Initialize the curses library */
7111 if (isatty(STDIN_FILENO)) {
7112 cursed = !!initscr();
7113 opt_tty = stdin;
7114 } else {
7115 /* Leave stdin and stdout alone when acting as a pager. */
7116 opt_tty = fopen("/dev/tty", "r+");
7117 if (!opt_tty)
7118 die("Failed to open /dev/tty");
7119 cursed = !!newterm(NULL, opt_tty, opt_tty);
7122 if (!cursed)
7123 die("Failed to initialize curses");
7125 nonl(); /* Disable conversion and detect newlines from input. */
7126 cbreak(); /* Take input chars one at a time, no wait for \n */
7127 noecho(); /* Don't echo input */
7128 leaveok(stdscr, FALSE);
7130 if (has_colors())
7131 init_colors();
7133 getmaxyx(stdscr, y, x);
7134 status_win = newwin(1, x, y - 1, 0);
7135 if (!status_win)
7136 die("Failed to create status window");
7138 /* Enable keyboard mapping */
7139 keypad(status_win, TRUE);
7140 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7142 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7143 set_tabsize(opt_tab_size);
7144 #else
7145 TABSIZE = opt_tab_size;
7146 #endif
7148 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7149 if (term && !strcmp(term, "gnome-terminal")) {
7150 /* In the gnome-terminal-emulator, the message from
7151 * scrolling up one line when impossible followed by
7152 * scrolling down one line causes corruption of the
7153 * status line. This is fixed by calling wclear. */
7154 use_scroll_status_wclear = TRUE;
7155 use_scroll_redrawwin = FALSE;
7157 } else if (term && !strcmp(term, "xrvt-xpm")) {
7158 /* No problems with full optimizations in xrvt-(unicode)
7159 * and aterm. */
7160 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7162 } else {
7163 /* When scrolling in (u)xterm the last line in the
7164 * scrolling direction will update slowly. */
7165 use_scroll_redrawwin = TRUE;
7166 use_scroll_status_wclear = FALSE;
7170 static int
7171 get_input(int prompt_position)
7173 struct view *view;
7174 int i, key, cursor_y, cursor_x;
7176 if (prompt_position)
7177 input_mode = TRUE;
7179 while (TRUE) {
7180 bool loading = FALSE;
7182 foreach_view (view, i) {
7183 update_view(view);
7184 if (view_is_displayed(view) && view->has_scrolled &&
7185 use_scroll_redrawwin)
7186 redrawwin(view->win);
7187 view->has_scrolled = FALSE;
7188 if (view->pipe)
7189 loading = TRUE;
7192 /* Update the cursor position. */
7193 if (prompt_position) {
7194 getbegyx(status_win, cursor_y, cursor_x);
7195 cursor_x = prompt_position;
7196 } else {
7197 view = display[current_view];
7198 getbegyx(view->win, cursor_y, cursor_x);
7199 cursor_x = view->width - 1;
7200 cursor_y += view->pos.lineno - view->pos.offset;
7202 setsyx(cursor_y, cursor_x);
7204 /* Refresh, accept single keystroke of input */
7205 doupdate();
7206 nodelay(status_win, loading);
7207 key = wgetch(status_win);
7209 /* wgetch() with nodelay() enabled returns ERR when
7210 * there's no input. */
7211 if (key == ERR) {
7213 } else if (key == KEY_RESIZE) {
7214 int height, width;
7216 getmaxyx(stdscr, height, width);
7218 wresize(status_win, 1, width);
7219 mvwin(status_win, height - 1, 0);
7220 wnoutrefresh(status_win);
7221 resize_display();
7222 redraw_display(TRUE);
7224 } else {
7225 input_mode = FALSE;
7226 if (key == erasechar())
7227 key = KEY_BACKSPACE;
7228 return key;
7233 static char *
7234 prompt_input(const char *prompt, input_handler handler, void *data)
7236 enum input_status status = INPUT_OK;
7237 static char buf[SIZEOF_STR];
7238 size_t pos = 0;
7240 buf[pos] = 0;
7242 while (status == INPUT_OK || status == INPUT_SKIP) {
7243 int key;
7245 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7246 wclrtoeol(status_win);
7248 key = get_input(pos + 1);
7249 switch (key) {
7250 case KEY_RETURN:
7251 case KEY_ENTER:
7252 case '\n':
7253 status = pos ? INPUT_STOP : INPUT_CANCEL;
7254 break;
7256 case KEY_BACKSPACE:
7257 if (pos > 0)
7258 buf[--pos] = 0;
7259 else
7260 status = INPUT_CANCEL;
7261 break;
7263 case KEY_ESC:
7264 status = INPUT_CANCEL;
7265 break;
7267 default:
7268 if (pos >= sizeof(buf)) {
7269 report("Input string too long");
7270 return NULL;
7273 status = handler(data, buf, key);
7274 if (status == INPUT_OK)
7275 buf[pos++] = (char) key;
7279 /* Clear the status window */
7280 status_empty = FALSE;
7281 report("");
7283 if (status == INPUT_CANCEL)
7284 return NULL;
7286 buf[pos++] = 0;
7288 return buf;
7291 static enum input_status
7292 prompt_yesno_handler(void *data, char *buf, int c)
7294 if (c == 'y' || c == 'Y')
7295 return INPUT_STOP;
7296 if (c == 'n' || c == 'N')
7297 return INPUT_CANCEL;
7298 return INPUT_SKIP;
7301 static bool
7302 prompt_yesno(const char *prompt)
7304 char prompt2[SIZEOF_STR];
7306 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7307 return FALSE;
7309 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7312 static enum input_status
7313 read_prompt_handler(void *data, char *buf, int c)
7315 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7318 static char *
7319 read_prompt(const char *prompt)
7321 return prompt_input(prompt, read_prompt_handler, NULL);
7324 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7326 enum input_status status = INPUT_OK;
7327 int size = 0;
7329 while (items[size].text)
7330 size++;
7332 assert(size > 0);
7334 while (status == INPUT_OK) {
7335 const struct menu_item *item = &items[*selected];
7336 int key;
7337 int i;
7339 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7340 prompt, *selected + 1, size);
7341 if (item->hotkey)
7342 wprintw(status_win, "[%c] ", (char) item->hotkey);
7343 wprintw(status_win, "%s", item->text);
7344 wclrtoeol(status_win);
7346 key = get_input(COLS - 1);
7347 switch (key) {
7348 case KEY_RETURN:
7349 case KEY_ENTER:
7350 case '\n':
7351 status = INPUT_STOP;
7352 break;
7354 case KEY_LEFT:
7355 case KEY_UP:
7356 *selected = *selected - 1;
7357 if (*selected < 0)
7358 *selected = size - 1;
7359 break;
7361 case KEY_RIGHT:
7362 case KEY_DOWN:
7363 *selected = (*selected + 1) % size;
7364 break;
7366 case KEY_ESC:
7367 status = INPUT_CANCEL;
7368 break;
7370 default:
7371 for (i = 0; items[i].text; i++)
7372 if (items[i].hotkey == key) {
7373 *selected = i;
7374 status = INPUT_STOP;
7375 break;
7380 /* Clear the status window */
7381 status_empty = FALSE;
7382 report("");
7384 return status != INPUT_CANCEL;
7388 * Repository properties
7392 static void
7393 set_remote_branch(const char *name, const char *value, size_t valuelen)
7395 if (!strcmp(name, ".remote")) {
7396 string_ncopy(opt_remote, value, valuelen);
7398 } else if (*opt_remote && !strcmp(name, ".merge")) {
7399 size_t from = strlen(opt_remote);
7401 if (!prefixcmp(value, "refs/heads/"))
7402 value += STRING_SIZE("refs/heads/");
7404 if (!string_format_from(opt_remote, &from, "/%s", value))
7405 opt_remote[0] = 0;
7409 static void
7410 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7412 const char *argv[SIZEOF_ARG] = { name, "=" };
7413 int argc = 1 + (cmd == option_set_command);
7414 enum option_code error;
7416 if (!argv_from_string(argv, &argc, value))
7417 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7418 else
7419 error = cmd(argc, argv);
7421 if (error != OPT_OK)
7422 warn("Option 'tig.%s': %s", name, option_errors[error]);
7425 static bool
7426 set_environment_variable(const char *name, const char *value)
7428 size_t len = strlen(name) + 1 + strlen(value) + 1;
7429 char *env = malloc(len);
7431 if (env &&
7432 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7433 putenv(env) == 0)
7434 return TRUE;
7435 free(env);
7436 return FALSE;
7439 static void
7440 set_work_tree(const char *value)
7442 char cwd[SIZEOF_STR];
7444 if (!getcwd(cwd, sizeof(cwd)))
7445 die("Failed to get cwd path: %s", strerror(errno));
7446 if (chdir(opt_git_dir) < 0)
7447 die("Failed to chdir(%s): %s", strerror(errno));
7448 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7449 die("Failed to get git path: %s", strerror(errno));
7450 if (chdir(cwd) < 0)
7451 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7452 if (chdir(value) < 0)
7453 die("Failed to chdir(%s): %s", value, strerror(errno));
7454 if (!getcwd(cwd, sizeof(cwd)))
7455 die("Failed to get cwd path: %s", strerror(errno));
7456 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7457 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7458 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7459 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7460 opt_is_inside_work_tree = TRUE;
7463 static void
7464 parse_git_color_option(enum line_type type, char *value)
7466 struct line_info *info = &line_info[type];
7467 const char *argv[SIZEOF_ARG];
7468 int argc = 0;
7469 bool first_color = TRUE;
7470 int i;
7472 if (!argv_from_string(argv, &argc, value))
7473 return;
7475 info->fg = COLOR_DEFAULT;
7476 info->bg = COLOR_DEFAULT;
7477 info->attr = 0;
7479 for (i = 0; i < argc; i++) {
7480 int attr = 0;
7482 if (set_attribute(&attr, argv[i])) {
7483 info->attr |= attr;
7485 } else if (set_color(&attr, argv[i])) {
7486 if (first_color)
7487 info->fg = attr;
7488 else
7489 info->bg = attr;
7490 first_color = FALSE;
7495 static void
7496 set_git_color_option(const char *name, char *value)
7498 static const struct enum_map color_option_map[] = {
7499 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7500 ENUM_MAP("branch.local", LINE_MAIN_REF),
7501 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7502 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7504 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7505 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7506 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7507 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7508 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7509 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7510 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7512 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7514 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7515 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7516 ENUM_MAP("status.added", LINE_STAT_STAGED),
7517 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7518 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7519 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7522 int type = LINE_NONE;
7524 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7525 parse_git_color_option(type, value);
7529 static int
7530 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7532 if (!strcmp(name, "gui.encoding"))
7533 parse_encoding(&opt_encoding, value, TRUE);
7535 else if (!strcmp(name, "core.editor"))
7536 string_ncopy(opt_editor, value, valuelen);
7538 else if (!strcmp(name, "core.worktree"))
7539 set_work_tree(value);
7541 else if (!prefixcmp(name, "tig.color."))
7542 set_repo_config_option(name + 10, value, option_color_command);
7544 else if (!prefixcmp(name, "tig.bind."))
7545 set_repo_config_option(name + 9, value, option_bind_command);
7547 else if (!prefixcmp(name, "tig."))
7548 set_repo_config_option(name + 4, value, option_set_command);
7550 else if (!prefixcmp(name, "color."))
7551 set_git_color_option(name + STRING_SIZE("color."), value);
7553 else if (*opt_head && !prefixcmp(name, "branch.") &&
7554 !strncmp(name + 7, opt_head, strlen(opt_head)))
7555 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7557 return OK;
7560 static int
7561 load_git_config(void)
7563 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7565 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7568 static int
7569 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7571 if (!opt_git_dir[0]) {
7572 string_ncopy(opt_git_dir, name, namelen);
7574 } else if (opt_is_inside_work_tree == -1) {
7575 /* This can be 3 different values depending on the
7576 * version of git being used. If git-rev-parse does not
7577 * understand --is-inside-work-tree it will simply echo
7578 * the option else either "true" or "false" is printed.
7579 * Default to true for the unknown case. */
7580 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7582 } else if (*name == '.') {
7583 string_ncopy(opt_cdup, name, namelen);
7585 } else {
7586 string_ncopy(opt_prefix, name, namelen);
7589 return OK;
7592 static int
7593 load_repo_info(void)
7595 const char *rev_parse_argv[] = {
7596 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7597 "--show-cdup", "--show-prefix", NULL
7600 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7605 * Main
7608 static const char usage[] =
7609 "tig " TIG_VERSION " (" __DATE__ ")\n"
7610 "\n"
7611 "Usage: tig [options] [revs] [--] [paths]\n"
7612 " or: tig show [options] [revs] [--] [paths]\n"
7613 " or: tig blame [options] [rev] [--] path\n"
7614 " or: tig status\n"
7615 " or: tig < [git command output]\n"
7616 "\n"
7617 "Options:\n"
7618 " +<number> Select line <number> in the first view\n"
7619 " -v, --version Show version and exit\n"
7620 " -h, --help Show help message and exit";
7622 static void __NORETURN
7623 quit(int sig)
7625 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7626 if (cursed)
7627 endwin();
7628 exit(0);
7631 static void __NORETURN
7632 die(const char *err, ...)
7634 va_list args;
7636 endwin();
7638 va_start(args, err);
7639 fputs("tig: ", stderr);
7640 vfprintf(stderr, err, args);
7641 fputs("\n", stderr);
7642 va_end(args);
7644 exit(1);
7647 static void
7648 warn(const char *msg, ...)
7650 va_list args;
7652 va_start(args, msg);
7653 fputs("tig warning: ", stderr);
7654 vfprintf(stderr, msg, args);
7655 fputs("\n", stderr);
7656 va_end(args);
7659 static int
7660 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7662 const char ***filter_args = data;
7664 return argv_append(filter_args, name) ? OK : ERR;
7667 static void
7668 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7670 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7671 const char **all_argv = NULL;
7673 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7674 !argv_append_array(&all_argv, argv) ||
7675 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7676 die("Failed to split arguments");
7677 argv_free(all_argv);
7678 free(all_argv);
7681 static void
7682 filter_options(const char *argv[], bool blame)
7684 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7686 if (blame)
7687 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7688 else
7689 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7691 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7694 static enum request
7695 parse_options(int argc, const char *argv[])
7697 enum request request = REQ_VIEW_MAIN;
7698 const char *subcommand;
7699 bool seen_dashdash = FALSE;
7700 const char **filter_argv = NULL;
7701 int i;
7703 if (!isatty(STDIN_FILENO))
7704 return REQ_VIEW_PAGER;
7706 if (argc <= 1)
7707 return REQ_VIEW_MAIN;
7709 subcommand = argv[1];
7710 if (!strcmp(subcommand, "status")) {
7711 if (argc > 2)
7712 warn("ignoring arguments after `%s'", subcommand);
7713 return REQ_VIEW_STATUS;
7715 } else if (!strcmp(subcommand, "blame")) {
7716 request = REQ_VIEW_BLAME;
7718 } else if (!strcmp(subcommand, "show")) {
7719 request = REQ_VIEW_DIFF;
7721 } else {
7722 subcommand = NULL;
7725 for (i = 1 + !!subcommand; i < argc; i++) {
7726 const char *opt = argv[i];
7728 // stop parsing our options after -- and let rev-parse handle the rest
7729 if (!seen_dashdash) {
7730 if (!strcmp(opt, "--")) {
7731 seen_dashdash = TRUE;
7732 continue;
7734 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7735 printf("tig version %s\n", TIG_VERSION);
7736 quit(0);
7738 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7739 printf("%s\n", usage);
7740 quit(0);
7742 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7743 opt_lineno = atoi(opt + 1);
7744 continue;
7749 if (!argv_append(&filter_argv, opt))
7750 die("command too long");
7753 if (filter_argv)
7754 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7756 /* Finish validating and setting up blame options */
7757 if (request == REQ_VIEW_BLAME) {
7758 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7759 die("invalid number of options to blame\n\n%s", usage);
7761 if (opt_rev_argv) {
7762 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7765 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7768 return request;
7772 main(int argc, const char *argv[])
7774 const char *codeset = ENCODING_UTF8;
7775 enum request request = parse_options(argc, argv);
7776 struct view *view;
7777 int i;
7779 signal(SIGINT, quit);
7780 signal(SIGPIPE, SIG_IGN);
7782 if (setlocale(LC_ALL, "")) {
7783 codeset = nl_langinfo(CODESET);
7786 foreach_view(view, i) {
7787 add_keymap(&view->ops->keymap);
7790 if (load_repo_info() == ERR)
7791 die("Failed to load repo info.");
7793 if (load_options() == ERR)
7794 die("Failed to load user config.");
7796 if (load_git_config() == ERR)
7797 die("Failed to load repo config.");
7799 /* Require a git repository unless when running in pager mode. */
7800 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7801 die("Not a git repository");
7803 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7804 char translit[SIZEOF_STR];
7806 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7807 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7808 else
7809 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7810 if (opt_iconv_out == ICONV_NONE)
7811 die("Failed to initialize character set conversion");
7814 if (load_refs() == ERR)
7815 die("Failed to load refs.");
7817 init_display();
7819 while (view_driver(display[current_view], request)) {
7820 int key = get_input(0);
7822 view = display[current_view];
7823 request = get_keybinding(&view->ops->keymap, key);
7825 /* Some low-level request handling. This keeps access to
7826 * status_win restricted. */
7827 switch (request) {
7828 case REQ_NONE:
7829 report("Unknown key, press %s for help",
7830 get_view_key(view, REQ_VIEW_HELP));
7831 break;
7832 case REQ_PROMPT:
7834 char *cmd = read_prompt(":");
7836 if (cmd && string_isnumber(cmd)) {
7837 int lineno = view->pos.lineno + 1;
7839 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7840 select_view_line(view, lineno - 1);
7841 report("");
7842 } else {
7843 report("Unable to parse '%s' as a line number", cmd);
7845 } else if (cmd && iscommit(cmd)) {
7846 string_ncopy(opt_search, cmd, strlen(cmd));
7848 request = view_request(view, REQ_JUMP_COMMIT);
7849 if (request == REQ_JUMP_COMMIT) {
7850 report("Jumping to commits is not supported by the '%s' view", view->name);
7853 } else if (cmd) {
7854 struct view *next = VIEW(REQ_VIEW_PAGER);
7855 const char *argv[SIZEOF_ARG] = { "git" };
7856 int argc = 1;
7858 /* When running random commands, initially show the
7859 * command in the title. However, it maybe later be
7860 * overwritten if a commit line is selected. */
7861 string_ncopy(next->ref, cmd, strlen(cmd));
7863 if (!argv_from_string(argv, &argc, cmd)) {
7864 report("Too many arguments");
7865 } else if (!format_argv(&next->argv, argv, FALSE)) {
7866 report("Argument formatting failed");
7867 } else {
7868 next->dir = NULL;
7869 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7873 request = REQ_NONE;
7874 break;
7876 case REQ_SEARCH:
7877 case REQ_SEARCH_BACK:
7879 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7880 char *search = read_prompt(prompt);
7882 if (search)
7883 string_ncopy(opt_search, search, strlen(search));
7884 else if (*opt_search)
7885 request = request == REQ_SEARCH ?
7886 REQ_FIND_NEXT :
7887 REQ_FIND_PREV;
7888 else
7889 request = REQ_NONE;
7890 break;
7892 default:
7893 break;
7897 quit(0);
7899 return 0;