Do not show deleted branch when reloading the branch view
[tig.git] / tig.c
blobaade2a37f145ea1cc3571b7e41d7e6fca7430867
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, ...) PRINTF_LIKE(1, 2);
21 static void warn(const char *msg, ...) PRINTF_LIKE(1, 2);
22 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
23 #define report_clear() report("%s", "")
26 enum input_status {
27 INPUT_OK,
28 INPUT_SKIP,
29 INPUT_STOP,
30 INPUT_CANCEL
33 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
35 static char *prompt_input(const char *prompt, input_handler handler, void *data);
36 static bool prompt_yesno(const char *prompt);
37 static char *read_prompt(const char *prompt);
39 struct menu_item {
40 int hotkey;
41 const char *text;
42 void *data;
45 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
47 #define GRAPHIC_ENUM(_) \
48 _(GRAPHIC, ASCII), \
49 _(GRAPHIC, DEFAULT), \
50 _(GRAPHIC, UTF_8)
52 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
54 #define DATE_ENUM(_) \
55 _(DATE, NO), \
56 _(DATE, DEFAULT), \
57 _(DATE, LOCAL), \
58 _(DATE, RELATIVE), \
59 _(DATE, SHORT)
61 DEFINE_ENUM(date, DATE_ENUM);
63 struct time {
64 time_t sec;
65 int tz;
68 static inline int timecmp(const struct time *t1, const struct time *t2)
70 return t1->sec - t2->sec;
73 static const char *
74 mkdate(const struct time *time, enum date date)
76 static char buf[DATE_WIDTH + 1];
77 static const struct enum_map reldate[] = {
78 { "second", 1, 60 * 2 },
79 { "minute", 60, 60 * 60 * 2 },
80 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
81 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
82 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
83 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
84 { "year", 60 * 60 * 24 * 365, 0 },
86 struct tm tm;
88 if (!date || !time || !time->sec)
89 return "";
91 if (date == DATE_RELATIVE) {
92 struct timeval now;
93 time_t date = time->sec + time->tz;
94 time_t seconds;
95 int i;
97 gettimeofday(&now, NULL);
98 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
99 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
100 if (seconds >= reldate[i].value && reldate[i].value)
101 continue;
103 seconds /= reldate[i].namelen;
104 if (!string_format(buf, "%ld %s%s %s",
105 seconds, reldate[i].name,
106 seconds > 1 ? "s" : "",
107 now.tv_sec >= date ? "ago" : "ahead"))
108 break;
109 return buf;
113 if (date == DATE_LOCAL) {
114 time_t date = time->sec + time->tz;
115 localtime_r(&date, &tm);
117 else {
118 gmtime_r(&time->sec, &tm);
120 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define AUTHOR_ENUM(_) \
125 _(AUTHOR, NO), \
126 _(AUTHOR, FULL), \
127 _(AUTHOR, ABBREVIATED)
129 DEFINE_ENUM(author, AUTHOR_ENUM);
131 static const char *
132 get_author_initials(const char *author)
134 static char initials[AUTHOR_WIDTH * 6 + 1];
135 size_t pos = 0;
136 const char *end = strchr(author, '\0');
138 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
140 memset(initials, 0, sizeof(initials));
141 while (author < end) {
142 unsigned char bytes;
143 size_t i;
145 while (author < end && is_initial_sep(*author))
146 author++;
148 bytes = utf8_char_length(author, end);
149 if (bytes >= sizeof(initials) - 1 - pos)
150 break;
151 while (bytes--) {
152 initials[pos++] = *author++;
155 i = pos;
156 while (author < end && !is_initial_sep(*author)) {
157 bytes = utf8_char_length(author, end);
158 if (bytes >= sizeof(initials) - 1 - i) {
159 while (author < end && !is_initial_sep(*author))
160 author++;
161 break;
163 while (bytes--) {
164 initials[i++] = *author++;
168 initials[i++] = 0;
171 return initials;
174 #define author_trim(cols) (cols == 0 || cols > 10)
176 static const char *
177 mkauthor(const char *text, int cols, enum author author)
179 bool trim = author_trim(cols);
180 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
182 if (author == AUTHOR_NO)
183 return "";
184 if (abbreviate && text)
185 return get_author_initials(text);
186 return text;
189 static const char *
190 mkmode(mode_t mode)
192 if (S_ISDIR(mode))
193 return "drwxr-xr-x";
194 else if (S_ISLNK(mode))
195 return "lrwxrwxrwx";
196 else if (S_ISGITLINK(mode))
197 return "m---------";
198 else if (S_ISREG(mode) && mode & S_IXUSR)
199 return "-rwxr-xr-x";
200 else if (S_ISREG(mode))
201 return "-rw-r--r--";
202 else
203 return "----------";
206 #define FILENAME_ENUM(_) \
207 _(FILENAME, NO), \
208 _(FILENAME, ALWAYS), \
209 _(FILENAME, AUTO)
211 DEFINE_ENUM(filename, FILENAME_ENUM);
213 #define IGNORE_SPACE_ENUM(_) \
214 _(IGNORE_SPACE, NO), \
215 _(IGNORE_SPACE, ALL), \
216 _(IGNORE_SPACE, SOME), \
217 _(IGNORE_SPACE, AT_EOL)
219 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
221 #define COMMIT_ORDER_ENUM(_) \
222 _(COMMIT_ORDER, DEFAULT), \
223 _(COMMIT_ORDER, TOPO), \
224 _(COMMIT_ORDER, DATE), \
225 _(COMMIT_ORDER, REVERSE)
227 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
229 #define VIEW_INFO(_) \
230 _(MAIN, main, ref_head), \
231 _(DIFF, diff, ref_commit), \
232 _(LOG, log, ref_head), \
233 _(TREE, tree, ref_commit), \
234 _(BLOB, blob, ref_blob), \
235 _(BLAME, blame, ref_commit), \
236 _(BRANCH, branch, ref_head), \
237 _(HELP, help, ""), \
238 _(PAGER, pager, ""), \
239 _(STATUS, status, "status"), \
240 _(STAGE, stage, ref_status)
242 static struct encoding *
243 get_path_encoding(const char *path, struct encoding *default_encoding)
245 const char *check_attr_argv[] = {
246 "git", "check-attr", "encoding", "--", path, NULL
248 char buf[SIZEOF_STR];
249 char *encoding;
251 /* <path>: encoding: <encoding> */
253 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
254 || !(encoding = strstr(buf, ENCODING_SEP)))
255 return default_encoding;
257 encoding += STRING_SIZE(ENCODING_SEP);
258 if (!strcmp(encoding, ENCODING_UTF8)
259 || !strcmp(encoding, "unspecified")
260 || !strcmp(encoding, "set"))
261 return default_encoding;
263 return encoding_open(encoding);
267 * User requests
270 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
272 #define REQ_INFO \
273 REQ_GROUP("View switching") \
274 VIEW_INFO(VIEW_REQ), \
276 REQ_GROUP("View manipulation") \
277 REQ_(ENTER, "Enter current line and scroll"), \
278 REQ_(NEXT, "Move to next"), \
279 REQ_(PREVIOUS, "Move to previous"), \
280 REQ_(PARENT, "Move to parent"), \
281 REQ_(VIEW_NEXT, "Move focus to next view"), \
282 REQ_(REFRESH, "Reload and refresh"), \
283 REQ_(MAXIMIZE, "Maximize the current view"), \
284 REQ_(VIEW_CLOSE, "Close the current view"), \
285 REQ_(QUIT, "Close all views and quit"), \
287 REQ_GROUP("View specific requests") \
288 REQ_(STATUS_UPDATE, "Update file status"), \
289 REQ_(STATUS_REVERT, "Revert file changes"), \
290 REQ_(STATUS_MERGE, "Merge file using external tool"), \
291 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
292 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
293 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
294 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
296 REQ_GROUP("Cursor navigation") \
297 REQ_(MOVE_UP, "Move cursor one line up"), \
298 REQ_(MOVE_DOWN, "Move cursor one line down"), \
299 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
300 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
301 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
302 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
304 REQ_GROUP("Scrolling") \
305 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
306 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
307 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
308 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
309 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
310 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
311 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
313 REQ_GROUP("Searching") \
314 REQ_(SEARCH, "Search the view"), \
315 REQ_(SEARCH_BACK, "Search backwards in the view"), \
316 REQ_(FIND_NEXT, "Find next search match"), \
317 REQ_(FIND_PREV, "Find previous search match"), \
319 REQ_GROUP("Option manipulation") \
320 REQ_(OPTIONS, "Open option menu"), \
321 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
322 REQ_(TOGGLE_DATE, "Toggle date display"), \
323 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
324 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
325 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
326 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
327 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
328 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
329 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
330 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
331 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
332 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
333 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
335 REQ_GROUP("Misc") \
336 REQ_(PROMPT, "Bring up the prompt"), \
337 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
338 REQ_(SHOW_VERSION, "Show version information"), \
339 REQ_(STOP_LOADING, "Stop all loading views"), \
340 REQ_(EDIT, "Open in editor"), \
341 REQ_(NONE, "Do nothing")
344 /* User action requests. */
345 enum request {
346 #define REQ_GROUP(help)
347 #define REQ_(req, help) REQ_##req
349 /* Offset all requests to avoid conflicts with ncurses getch values. */
350 REQ_UNKNOWN = KEY_MAX + 1,
351 REQ_OFFSET,
352 REQ_INFO,
354 /* Internal requests. */
355 REQ_JUMP_COMMIT,
357 #undef REQ_GROUP
358 #undef REQ_
361 struct request_info {
362 enum request request;
363 const char *name;
364 int namelen;
365 const char *help;
368 static const struct request_info req_info[] = {
369 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
370 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
371 REQ_INFO
372 #undef REQ_GROUP
373 #undef REQ_
376 static enum request
377 get_request(const char *name)
379 int namelen = strlen(name);
380 int i;
382 for (i = 0; i < ARRAY_SIZE(req_info); i++)
383 if (enum_equals(req_info[i], name, namelen))
384 return req_info[i].request;
386 return REQ_UNKNOWN;
391 * Options
394 /* Option and state variables. */
395 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
396 static enum date opt_date = DATE_DEFAULT;
397 static enum author opt_author = AUTHOR_FULL;
398 static enum filename opt_filename = FILENAME_AUTO;
399 static bool opt_rev_graph = TRUE;
400 static bool opt_line_number = FALSE;
401 static bool opt_show_refs = TRUE;
402 static bool opt_show_changes = TRUE;
403 static bool opt_untracked_dirs_content = TRUE;
404 static bool opt_read_git_colors = TRUE;
405 static bool opt_wrap_lines = FALSE;
406 static bool opt_ignore_case = FALSE;
407 static bool opt_stdin = FALSE;
408 static bool opt_focus_child = TRUE;
409 static int opt_diff_context = 3;
410 static char opt_diff_context_arg[9] = "";
411 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
412 static char opt_ignore_space_arg[22] = "";
413 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
414 static char opt_commit_order_arg[22] = "";
415 static bool opt_notes = TRUE;
416 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
417 static int opt_num_interval = 5;
418 static double opt_hscroll = 0.50;
419 static double opt_scale_split_view = 2.0 / 3.0;
420 static double opt_scale_vsplit_view = 0.5;
421 static bool opt_vsplit = FALSE;
422 static int opt_tab_size = 8;
423 static int opt_author_width = AUTHOR_WIDTH;
424 static int opt_filename_width = FILENAME_WIDTH;
425 static char opt_path[SIZEOF_STR] = "";
426 static char opt_file[SIZEOF_STR] = "";
427 static char opt_ref[SIZEOF_REF] = "";
428 static unsigned long opt_goto_line = 0;
429 static char opt_head[SIZEOF_REF] = "";
430 static char opt_remote[SIZEOF_REF] = "";
431 static struct encoding *opt_encoding = NULL;
432 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
433 static iconv_t opt_iconv_out = ICONV_NONE;
434 static char opt_search[SIZEOF_STR] = "";
435 static char opt_cdup[SIZEOF_STR] = "";
436 static char opt_prefix[SIZEOF_STR] = "";
437 static char opt_git_dir[SIZEOF_STR] = "";
438 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
439 static char opt_editor[SIZEOF_STR] = "";
440 static FILE *opt_tty = NULL;
441 static const char **opt_diff_argv = NULL;
442 static const char **opt_rev_argv = NULL;
443 static const char **opt_file_argv = NULL;
444 static const char **opt_blame_argv = NULL;
445 static int opt_lineno = 0;
446 static bool opt_show_id = FALSE;
447 static int opt_id_cols = ID_WIDTH;
449 #define is_initial_commit() (!get_ref_head())
450 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
451 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
453 static inline void
454 update_diff_context_arg(int diff_context)
456 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
457 string_ncopy(opt_diff_context_arg, "-U3", 3);
460 static inline void
461 update_ignore_space_arg()
463 if (opt_ignore_space == IGNORE_SPACE_ALL) {
464 string_copy(opt_ignore_space_arg, "--ignore-all-space");
465 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
466 string_copy(opt_ignore_space_arg, "--ignore-space-change");
467 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
468 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
469 } else {
470 string_copy(opt_ignore_space_arg, "");
474 static inline void
475 update_commit_order_arg()
477 if (opt_commit_order == COMMIT_ORDER_TOPO) {
478 string_copy(opt_commit_order_arg, "--topo-order");
479 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
480 string_copy(opt_commit_order_arg, "--date-order");
481 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
482 string_copy(opt_commit_order_arg, "--reverse");
483 } else {
484 string_copy(opt_commit_order_arg, "");
488 static inline void
489 update_notes_arg()
491 if (opt_notes) {
492 string_copy(opt_notes_arg, "--show-notes");
493 } else {
494 /* Notes are disabled by default when passing --pretty args. */
495 string_copy(opt_notes_arg, "");
500 * Line-oriented content detection.
503 #define LINE_INFO \
504 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
506 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
507 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
508 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
509 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
510 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
511 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
512 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(DIFF_DELETED_FILE_MODE, \
514 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
515 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
517 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
518 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
519 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
520 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
521 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
522 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
523 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
524 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
525 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
527 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
528 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
529 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
530 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
531 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
532 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
533 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
534 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
537 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
538 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
539 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
540 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
541 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
542 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
543 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
544 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
545 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
546 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
547 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
548 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
549 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
550 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
551 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
553 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
554 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
555 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
556 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
557 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
558 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
559 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
560 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
561 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
562 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
563 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
564 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
565 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
566 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
567 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
568 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
569 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
570 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
571 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
572 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
573 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
574 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
575 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
576 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
577 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
579 enum line_type {
580 #define LINE(type, line, fg, bg, attr) \
581 LINE_##type
582 LINE_INFO,
583 LINE_NONE
584 #undef LINE
587 struct line_info {
588 const char *name; /* Option name. */
589 int namelen; /* Size of option name. */
590 const char *line; /* The start of line to match. */
591 int linelen; /* Size of string to match. */
592 int fg, bg, attr; /* Color and text attributes for the lines. */
593 int color_pair;
596 static struct line_info line_info[] = {
597 #define LINE(type, line, fg, bg, attr) \
598 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
599 LINE_INFO
600 #undef LINE
603 static struct line_info **color_pair;
604 static size_t color_pairs;
606 static struct line_info *custom_color;
607 static size_t custom_colors;
609 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
610 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
612 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
613 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
615 /* Color IDs must be 1 or higher. [GH #15] */
616 #define COLOR_ID(line_type) ((line_type) + 1)
618 static enum line_type
619 get_line_type(const char *line)
621 int linelen = strlen(line);
622 enum line_type type;
624 for (type = 0; type < custom_colors; type++)
625 /* Case insensitive search matches Signed-off-by lines better. */
626 if (linelen >= custom_color[type].linelen &&
627 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
628 return TO_CUSTOM_COLOR_TYPE(type);
630 for (type = 0; type < ARRAY_SIZE(line_info); type++)
631 /* Case insensitive search matches Signed-off-by lines better. */
632 if (linelen >= line_info[type].linelen &&
633 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
634 return type;
636 return LINE_DEFAULT;
639 static enum line_type
640 get_line_type_from_ref(const struct ref *ref)
642 if (ref->head)
643 return LINE_MAIN_HEAD;
644 else if (ref->ltag)
645 return LINE_MAIN_LOCAL_TAG;
646 else if (ref->tag)
647 return LINE_MAIN_TAG;
648 else if (ref->tracked)
649 return LINE_MAIN_TRACKED;
650 else if (ref->remote)
651 return LINE_MAIN_REMOTE;
652 else if (ref->replace)
653 return LINE_MAIN_REPLACE;
655 return LINE_MAIN_REF;
658 static inline struct line_info *
659 get_line(enum line_type type)
661 if (type > LINE_NONE) {
662 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
663 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
664 } else {
665 assert(type < ARRAY_SIZE(line_info));
666 return &line_info[type];
670 static inline int
671 get_line_color(enum line_type type)
673 return COLOR_ID(get_line(type)->color_pair);
676 static inline int
677 get_line_attr(enum line_type type)
679 struct line_info *info = get_line(type);
681 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
684 static struct line_info *
685 get_line_info(const char *name)
687 size_t namelen = strlen(name);
688 enum line_type type;
690 for (type = 0; type < ARRAY_SIZE(line_info); type++)
691 if (enum_equals(line_info[type], name, namelen))
692 return &line_info[type];
694 return NULL;
697 static struct line_info *
698 add_custom_color(const char *quoted_line)
700 struct line_info *info;
701 char *line;
702 size_t linelen;
704 if (!realloc_custom_color(&custom_color, custom_colors, 1))
705 die("Failed to alloc custom line info");
707 linelen = strlen(quoted_line) - 1;
708 line = malloc(linelen);
709 if (!line)
710 return NULL;
712 strncpy(line, quoted_line + 1, linelen);
713 line[linelen - 1] = 0;
715 info = &custom_color[custom_colors++];
716 info->name = info->line = line;
717 info->namelen = info->linelen = strlen(line);
719 return info;
722 static void
723 init_line_info_color_pair(struct line_info *info, enum line_type type,
724 int default_bg, int default_fg)
726 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
727 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
728 int i;
730 for (i = 0; i < color_pairs; i++) {
731 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
732 info->color_pair = i;
733 return;
737 if (!realloc_color_pair(&color_pair, color_pairs, 1))
738 die("Failed to alloc color pair");
740 color_pair[color_pairs] = info;
741 info->color_pair = color_pairs++;
742 init_pair(COLOR_ID(info->color_pair), fg, bg);
745 static void
746 init_colors(void)
748 int default_bg = line_info[LINE_DEFAULT].bg;
749 int default_fg = line_info[LINE_DEFAULT].fg;
750 enum line_type type;
752 start_color();
754 if (assume_default_colors(default_fg, default_bg) == ERR) {
755 default_bg = COLOR_BLACK;
756 default_fg = COLOR_WHITE;
759 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
760 struct line_info *info = &line_info[type];
762 init_line_info_color_pair(info, type, default_bg, default_fg);
765 for (type = 0; type < custom_colors; type++) {
766 struct line_info *info = &custom_color[type];
768 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
769 default_bg, default_fg);
773 struct line {
774 enum line_type type;
775 unsigned int lineno:24;
777 /* State flags */
778 unsigned int selected:1;
779 unsigned int dirty:1;
780 unsigned int cleareol:1;
781 unsigned int dont_free:1;
782 unsigned int wrapped:1;
784 void *data; /* User data */
789 * Keys
792 struct keybinding {
793 int alias;
794 enum request request;
797 static struct keybinding default_keybindings[] = {
798 /* View switching */
799 { 'm', REQ_VIEW_MAIN },
800 { 'd', REQ_VIEW_DIFF },
801 { 'l', REQ_VIEW_LOG },
802 { 't', REQ_VIEW_TREE },
803 { 'f', REQ_VIEW_BLOB },
804 { 'B', REQ_VIEW_BLAME },
805 { 'H', REQ_VIEW_BRANCH },
806 { 'p', REQ_VIEW_PAGER },
807 { 'h', REQ_VIEW_HELP },
808 { 'S', REQ_VIEW_STATUS },
809 { 'c', REQ_VIEW_STAGE },
811 /* View manipulation */
812 { 'q', REQ_VIEW_CLOSE },
813 { KEY_TAB, REQ_VIEW_NEXT },
814 { KEY_RETURN, REQ_ENTER },
815 { KEY_UP, REQ_PREVIOUS },
816 { KEY_CTL('P'), REQ_PREVIOUS },
817 { KEY_DOWN, REQ_NEXT },
818 { KEY_CTL('N'), REQ_NEXT },
819 { 'R', REQ_REFRESH },
820 { KEY_F(5), REQ_REFRESH },
821 { 'O', REQ_MAXIMIZE },
822 { ',', REQ_PARENT },
824 /* View specific */
825 { 'u', REQ_STATUS_UPDATE },
826 { '!', REQ_STATUS_REVERT },
827 { 'M', REQ_STATUS_MERGE },
828 { '1', REQ_STAGE_UPDATE_LINE },
829 { '@', REQ_STAGE_NEXT },
830 { '[', REQ_DIFF_CONTEXT_DOWN },
831 { ']', REQ_DIFF_CONTEXT_UP },
833 /* Cursor navigation */
834 { 'k', REQ_MOVE_UP },
835 { 'j', REQ_MOVE_DOWN },
836 { KEY_HOME, REQ_MOVE_FIRST_LINE },
837 { KEY_END, REQ_MOVE_LAST_LINE },
838 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
839 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
840 { ' ', REQ_MOVE_PAGE_DOWN },
841 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
842 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
843 { 'b', REQ_MOVE_PAGE_UP },
844 { '-', REQ_MOVE_PAGE_UP },
846 /* Scrolling */
847 { '|', REQ_SCROLL_FIRST_COL },
848 { KEY_LEFT, REQ_SCROLL_LEFT },
849 { KEY_RIGHT, REQ_SCROLL_RIGHT },
850 { KEY_IC, REQ_SCROLL_LINE_UP },
851 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
852 { KEY_DC, REQ_SCROLL_LINE_DOWN },
853 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
854 { 'w', REQ_SCROLL_PAGE_UP },
855 { 's', REQ_SCROLL_PAGE_DOWN },
857 /* Searching */
858 { '/', REQ_SEARCH },
859 { '?', REQ_SEARCH_BACK },
860 { 'n', REQ_FIND_NEXT },
861 { 'N', REQ_FIND_PREV },
863 /* Misc */
864 { 'Q', REQ_QUIT },
865 { 'z', REQ_STOP_LOADING },
866 { 'v', REQ_SHOW_VERSION },
867 { 'r', REQ_SCREEN_REDRAW },
868 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
869 { 'o', REQ_OPTIONS },
870 { '.', REQ_TOGGLE_LINENO },
871 { 'D', REQ_TOGGLE_DATE },
872 { 'A', REQ_TOGGLE_AUTHOR },
873 { 'g', REQ_TOGGLE_REV_GRAPH },
874 { '~', REQ_TOGGLE_GRAPHIC },
875 { '#', REQ_TOGGLE_FILENAME },
876 { 'F', REQ_TOGGLE_REFS },
877 { 'I', REQ_TOGGLE_SORT_ORDER },
878 { 'i', REQ_TOGGLE_SORT_FIELD },
879 { 'W', REQ_TOGGLE_IGNORE_SPACE },
880 { 'X', REQ_TOGGLE_ID },
881 { ':', REQ_PROMPT },
882 { 'e', REQ_EDIT },
885 struct keymap {
886 const char *name;
887 struct keymap *next;
888 struct keybinding *data;
889 size_t size;
890 bool hidden;
893 static struct keymap generic_keymap = { "generic" };
894 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
896 static struct keymap *keymaps = &generic_keymap;
898 static void
899 add_keymap(struct keymap *keymap)
901 keymap->next = keymaps;
902 keymaps = keymap;
905 static struct keymap *
906 get_keymap(const char *name)
908 struct keymap *keymap = keymaps;
910 while (keymap) {
911 if (!strcasecmp(keymap->name, name))
912 return keymap;
913 keymap = keymap->next;
916 return NULL;
920 static void
921 add_keybinding(struct keymap *table, enum request request, int key)
923 size_t i;
925 for (i = 0; i < table->size; i++) {
926 if (table->data[i].alias == key) {
927 table->data[i].request = request;
928 return;
932 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
933 if (!table->data)
934 die("Failed to allocate keybinding");
935 table->data[table->size].alias = key;
936 table->data[table->size++].request = request;
938 if (request == REQ_NONE && is_generic_keymap(table)) {
939 int i;
941 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
942 if (default_keybindings[i].alias == key)
943 default_keybindings[i].request = REQ_NONE;
947 /* Looks for a key binding first in the given map, then in the generic map, and
948 * lastly in the default keybindings. */
949 static enum request
950 get_keybinding(struct keymap *keymap, int key)
952 size_t i;
954 for (i = 0; i < keymap->size; i++)
955 if (keymap->data[i].alias == key)
956 return keymap->data[i].request;
958 for (i = 0; i < generic_keymap.size; i++)
959 if (generic_keymap.data[i].alias == key)
960 return generic_keymap.data[i].request;
962 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
963 if (default_keybindings[i].alias == key)
964 return default_keybindings[i].request;
966 return (enum request) key;
970 struct key {
971 const char *name;
972 int value;
975 static const struct key key_table[] = {
976 { "Enter", KEY_RETURN },
977 { "Space", ' ' },
978 { "Backspace", KEY_BACKSPACE },
979 { "Tab", KEY_TAB },
980 { "Escape", KEY_ESC },
981 { "Left", KEY_LEFT },
982 { "Right", KEY_RIGHT },
983 { "Up", KEY_UP },
984 { "Down", KEY_DOWN },
985 { "Insert", KEY_IC },
986 { "Delete", KEY_DC },
987 { "Hash", '#' },
988 { "Home", KEY_HOME },
989 { "End", KEY_END },
990 { "PageUp", KEY_PPAGE },
991 { "PageDown", KEY_NPAGE },
992 { "F1", KEY_F(1) },
993 { "F2", KEY_F(2) },
994 { "F3", KEY_F(3) },
995 { "F4", KEY_F(4) },
996 { "F5", KEY_F(5) },
997 { "F6", KEY_F(6) },
998 { "F7", KEY_F(7) },
999 { "F8", KEY_F(8) },
1000 { "F9", KEY_F(9) },
1001 { "F10", KEY_F(10) },
1002 { "F11", KEY_F(11) },
1003 { "F12", KEY_F(12) },
1006 static int
1007 get_key_value(const char *name)
1009 int i;
1011 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1012 if (!strcasecmp(key_table[i].name, name))
1013 return key_table[i].value;
1015 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1016 return (int)name[1] & 0x1f;
1017 if (strlen(name) == 1 && isprint(*name))
1018 return (int) *name;
1019 return ERR;
1022 static const char *
1023 get_key_name(int key_value)
1025 static char key_char[] = "'X'\0";
1026 const char *seq = NULL;
1027 int key;
1029 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1030 if (key_table[key].value == key_value)
1031 seq = key_table[key].name;
1033 if (seq == NULL && key_value < 0x7f) {
1034 char *s = key_char + 1;
1036 if (key_value >= 0x20) {
1037 *s++ = key_value;
1038 } else {
1039 *s++ = '^';
1040 *s++ = 0x40 | (key_value & 0x1f);
1042 *s++ = '\'';
1043 *s++ = '\0';
1044 seq = key_char;
1047 return seq ? seq : "(no key)";
1050 static bool
1051 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1053 const char *sep = *pos > 0 ? ", " : "";
1054 const char *keyname = get_key_name(keybinding->alias);
1056 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1059 static bool
1060 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1061 struct keymap *keymap, bool all)
1063 int i;
1065 for (i = 0; i < keymap->size; i++) {
1066 if (keymap->data[i].request == request) {
1067 if (!append_key(buf, pos, &keymap->data[i]))
1068 return FALSE;
1069 if (!all)
1070 break;
1074 return TRUE;
1077 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1079 static const char *
1080 get_keys(struct keymap *keymap, enum request request, bool all)
1082 static char buf[BUFSIZ];
1083 size_t pos = 0;
1084 int i;
1086 buf[pos] = 0;
1088 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1089 return "Too many keybindings!";
1090 if (pos > 0 && !all)
1091 return buf;
1093 if (!is_generic_keymap(keymap)) {
1094 /* Only the generic keymap includes the default keybindings when
1095 * listing all keys. */
1096 if (all)
1097 return buf;
1099 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1100 return "Too many keybindings!";
1101 if (pos)
1102 return buf;
1105 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1106 if (default_keybindings[i].request == request) {
1107 if (!append_key(buf, &pos, &default_keybindings[i]))
1108 return "Too many keybindings!";
1109 if (!all)
1110 return buf;
1114 return buf;
1117 enum run_request_flag {
1118 RUN_REQUEST_DEFAULT = 0,
1119 RUN_REQUEST_FORCE = 1,
1120 RUN_REQUEST_SILENT = 2,
1121 RUN_REQUEST_CONFIRM = 4,
1122 RUN_REQUEST_EXIT = 8,
1125 struct run_request {
1126 struct keymap *keymap;
1127 int key;
1128 const char **argv;
1129 bool silent;
1130 bool confirm;
1131 bool exit;
1134 static struct run_request *run_request;
1135 static size_t run_requests;
1137 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1139 static bool
1140 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1142 bool force = flags & RUN_REQUEST_FORCE;
1143 struct run_request *req;
1145 if (!force && get_keybinding(keymap, key) != key)
1146 return TRUE;
1148 if (!realloc_run_requests(&run_request, run_requests, 1))
1149 return FALSE;
1151 if (!argv_copy(&run_request[run_requests].argv, argv))
1152 return FALSE;
1154 req = &run_request[run_requests++];
1155 req->silent = flags & RUN_REQUEST_SILENT;
1156 req->confirm = flags & RUN_REQUEST_CONFIRM;
1157 req->exit = flags & RUN_REQUEST_EXIT;
1158 req->keymap = keymap;
1159 req->key = key;
1161 add_keybinding(keymap, REQ_NONE + run_requests, key);
1162 return TRUE;
1165 static struct run_request *
1166 get_run_request(enum request request)
1168 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1169 return NULL;
1170 return &run_request[request - REQ_NONE - 1];
1173 static void
1174 add_builtin_run_requests(void)
1176 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1177 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1178 const char *commit[] = { "git", "commit", NULL };
1179 const char *gc[] = { "git", "gc", NULL };
1181 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1182 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1183 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1184 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1188 * User config file handling.
1191 #define OPT_ERR_INFO \
1192 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1193 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1194 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1195 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1196 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1197 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1198 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1199 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1200 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1201 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1202 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1203 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1204 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1205 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1206 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1207 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1208 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1209 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1211 enum option_code {
1212 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1213 OPT_ERR_INFO
1214 #undef OPT_ERR_
1215 OPT_OK
1218 static const char *option_errors[] = {
1219 #define OPT_ERR_(name, msg) msg
1220 OPT_ERR_INFO
1221 #undef OPT_ERR_
1224 static const struct enum_map color_map[] = {
1225 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1226 COLOR_MAP(DEFAULT),
1227 COLOR_MAP(BLACK),
1228 COLOR_MAP(BLUE),
1229 COLOR_MAP(CYAN),
1230 COLOR_MAP(GREEN),
1231 COLOR_MAP(MAGENTA),
1232 COLOR_MAP(RED),
1233 COLOR_MAP(WHITE),
1234 COLOR_MAP(YELLOW),
1237 static const struct enum_map attr_map[] = {
1238 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1239 ATTR_MAP(NORMAL),
1240 ATTR_MAP(BLINK),
1241 ATTR_MAP(BOLD),
1242 ATTR_MAP(DIM),
1243 ATTR_MAP(REVERSE),
1244 ATTR_MAP(STANDOUT),
1245 ATTR_MAP(UNDERLINE),
1248 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1250 static enum option_code
1251 parse_step(double *opt, const char *arg)
1253 *opt = atoi(arg);
1254 if (!strchr(arg, '%'))
1255 return OPT_OK;
1257 /* "Shift down" so 100% and 1 does not conflict. */
1258 *opt = (*opt - 1) / 100;
1259 if (*opt >= 1.0) {
1260 *opt = 0.99;
1261 return OPT_ERR_INVALID_STEP_VALUE;
1263 if (*opt < 0.0) {
1264 *opt = 1;
1265 return OPT_ERR_INVALID_STEP_VALUE;
1267 return OPT_OK;
1270 static enum option_code
1271 parse_int(int *opt, const char *arg, int min, int max)
1273 int value = atoi(arg);
1275 if (min <= value && value <= max) {
1276 *opt = value;
1277 return OPT_OK;
1280 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1283 #define parse_id(opt, arg) \
1284 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1286 static bool
1287 set_color(int *color, const char *name)
1289 if (map_enum(color, color_map, name))
1290 return TRUE;
1291 if (!prefixcmp(name, "color"))
1292 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1293 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1294 return parse_int(color, name, 0, 255) == OPT_OK;
1297 /* Wants: object fgcolor bgcolor [attribute] */
1298 static enum option_code
1299 option_color_command(int argc, const char *argv[])
1301 struct line_info *info;
1303 if (argc < 3)
1304 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1306 if (*argv[0] == '"' || *argv[0] == '\'') {
1307 info = add_custom_color(argv[0]);
1308 } else {
1309 info = get_line_info(argv[0]);
1311 if (!info) {
1312 static const struct enum_map obsolete[] = {
1313 ENUM_MAP("main-delim", LINE_DELIMITER),
1314 ENUM_MAP("main-date", LINE_DATE),
1315 ENUM_MAP("main-author", LINE_AUTHOR),
1316 ENUM_MAP("blame-id", LINE_ID),
1318 int index;
1320 if (!map_enum(&index, obsolete, argv[0]))
1321 return OPT_ERR_UNKNOWN_COLOR_NAME;
1322 info = &line_info[index];
1325 if (!set_color(&info->fg, argv[1]) ||
1326 !set_color(&info->bg, argv[2]))
1327 return OPT_ERR_UNKNOWN_COLOR;
1329 info->attr = 0;
1330 while (argc-- > 3) {
1331 int attr;
1333 if (!set_attribute(&attr, argv[argc]))
1334 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1335 info->attr |= attr;
1338 return OPT_OK;
1341 static enum option_code
1342 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1344 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1345 ? TRUE : FALSE;
1346 if (matched)
1347 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1348 return OPT_OK;
1351 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1353 static enum option_code
1354 parse_enum_do(unsigned int *opt, const char *arg,
1355 const struct enum_map *map, size_t map_size)
1357 bool is_true;
1359 assert(map_size > 1);
1361 if (map_enum_do(map, map_size, (int *) opt, arg))
1362 return OPT_OK;
1364 parse_bool(&is_true, arg);
1365 *opt = is_true ? map[1].value : map[0].value;
1366 return OPT_OK;
1369 #define parse_enum(opt, arg, map) \
1370 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1372 static enum option_code
1373 parse_string(char *opt, const char *arg, size_t optsize)
1375 int arglen = strlen(arg);
1377 switch (arg[0]) {
1378 case '\"':
1379 case '\'':
1380 if (arglen == 1 || arg[arglen - 1] != arg[0])
1381 return OPT_ERR_UNMATCHED_QUOTATION;
1382 arg += 1; arglen -= 2;
1383 default:
1384 string_ncopy_do(opt, optsize, arg, arglen);
1385 return OPT_OK;
1389 static enum option_code
1390 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1392 char buf[SIZEOF_STR];
1393 enum option_code code = parse_string(buf, arg, sizeof(buf));
1395 if (code == OPT_OK) {
1396 struct encoding *encoding = *encoding_ref;
1398 if (encoding && !priority)
1399 return code;
1400 encoding = encoding_open(buf);
1401 if (encoding)
1402 *encoding_ref = encoding;
1405 return code;
1408 static enum option_code
1409 parse_args(const char ***args, const char *argv[])
1411 if (*args == NULL && !argv_copy(args, argv))
1412 return OPT_ERR_OUT_OF_MEMORY;
1413 return OPT_OK;
1416 /* Wants: name = value */
1417 static enum option_code
1418 option_set_command(int argc, const char *argv[])
1420 if (argc < 3)
1421 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1423 if (strcmp(argv[1], "="))
1424 return OPT_ERR_NO_VALUE_ASSIGNED;
1426 if (!strcmp(argv[0], "blame-options"))
1427 return parse_args(&opt_blame_argv, argv + 2);
1429 if (argc != 3)
1430 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1432 if (!strcmp(argv[0], "show-author"))
1433 return parse_enum(&opt_author, argv[2], author_map);
1435 if (!strcmp(argv[0], "show-date"))
1436 return parse_enum(&opt_date, argv[2], date_map);
1438 if (!strcmp(argv[0], "show-rev-graph"))
1439 return parse_bool(&opt_rev_graph, argv[2]);
1441 if (!strcmp(argv[0], "show-refs"))
1442 return parse_bool(&opt_show_refs, argv[2]);
1444 if (!strcmp(argv[0], "show-changes"))
1445 return parse_bool(&opt_show_changes, argv[2]);
1447 if (!strcmp(argv[0], "show-notes")) {
1448 bool matched = FALSE;
1449 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1451 if (res == OPT_OK && matched) {
1452 update_notes_arg();
1453 return res;
1456 opt_notes = TRUE;
1457 strcpy(opt_notes_arg, "--show-notes=");
1458 res = parse_string(opt_notes_arg + 8, argv[2],
1459 sizeof(opt_notes_arg) - 8);
1460 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1461 opt_notes_arg[7] = '\0';
1462 return res;
1465 if (!strcmp(argv[0], "show-line-numbers"))
1466 return parse_bool(&opt_line_number, argv[2]);
1468 if (!strcmp(argv[0], "line-graphics"))
1469 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1471 if (!strcmp(argv[0], "line-number-interval"))
1472 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1474 if (!strcmp(argv[0], "author-width"))
1475 return parse_int(&opt_author_width, argv[2], 0, 1024);
1477 if (!strcmp(argv[0], "filename-width"))
1478 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1480 if (!strcmp(argv[0], "show-filename"))
1481 return parse_enum(&opt_filename, argv[2], filename_map);
1483 if (!strcmp(argv[0], "horizontal-scroll"))
1484 return parse_step(&opt_hscroll, argv[2]);
1486 if (!strcmp(argv[0], "split-view-height"))
1487 return parse_step(&opt_scale_split_view, argv[2]);
1489 if (!strcmp(argv[0], "vertical-split"))
1490 return parse_bool(&opt_vsplit, argv[2]);
1492 if (!strcmp(argv[0], "tab-size"))
1493 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1495 if (!strcmp(argv[0], "diff-context")) {
1496 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1498 if (code == OPT_OK)
1499 update_diff_context_arg(opt_diff_context);
1500 return code;
1503 if (!strcmp(argv[0], "ignore-space")) {
1504 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1506 if (code == OPT_OK)
1507 update_ignore_space_arg();
1508 return code;
1511 if (!strcmp(argv[0], "commit-order")) {
1512 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1514 if (code == OPT_OK)
1515 update_commit_order_arg();
1516 return code;
1519 if (!strcmp(argv[0], "status-untracked-dirs"))
1520 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1522 if (!strcmp(argv[0], "read-git-colors"))
1523 return parse_bool(&opt_read_git_colors, argv[2]);
1525 if (!strcmp(argv[0], "ignore-case"))
1526 return parse_bool(&opt_ignore_case, argv[2]);
1528 if (!strcmp(argv[0], "focus-child"))
1529 return parse_bool(&opt_focus_child, argv[2]);
1531 if (!strcmp(argv[0], "wrap-lines"))
1532 return parse_bool(&opt_wrap_lines, argv[2]);
1534 if (!strcmp(argv[0], "show-id"))
1535 return parse_bool(&opt_show_id, argv[2]);
1537 if (!strcmp(argv[0], "id-width"))
1538 return parse_id(&opt_id_cols, argv[2]);
1540 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1543 /* Wants: mode request key */
1544 static enum option_code
1545 option_bind_command(int argc, const char *argv[])
1547 enum request request;
1548 struct keymap *keymap;
1549 int key;
1551 if (argc < 3)
1552 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1554 if (!(keymap = get_keymap(argv[0])))
1555 return OPT_ERR_UNKNOWN_KEY_MAP;
1557 key = get_key_value(argv[1]);
1558 if (key == ERR)
1559 return OPT_ERR_UNKNOWN_KEY;
1561 request = get_request(argv[2]);
1562 if (request == REQ_UNKNOWN) {
1563 static const struct enum_map obsolete[] = {
1564 ENUM_MAP("cherry-pick", REQ_NONE),
1565 ENUM_MAP("screen-resize", REQ_NONE),
1566 ENUM_MAP("tree-parent", REQ_PARENT),
1568 int alias;
1570 if (map_enum(&alias, obsolete, argv[2])) {
1571 if (alias != REQ_NONE)
1572 add_keybinding(keymap, alias, key);
1573 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1576 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1577 enum run_request_flag flags = RUN_REQUEST_FORCE;
1579 while (*argv[2]) {
1580 if (*argv[2] == '@') {
1581 flags |= RUN_REQUEST_SILENT;
1582 } else if (*argv[2] == '?') {
1583 flags |= RUN_REQUEST_CONFIRM;
1584 } else if (*argv[2] == '<') {
1585 flags |= RUN_REQUEST_EXIT;
1586 } else {
1587 break;
1589 argv[2]++;
1592 return add_run_request(keymap, key, argv + 2, flags)
1593 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1595 if (request == REQ_UNKNOWN)
1596 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1598 add_keybinding(keymap, request, key);
1600 return OPT_OK;
1604 static enum option_code load_option_file(const char *path);
1606 static enum option_code
1607 option_source_command(int argc, const char *argv[])
1609 if (argc < 1)
1610 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1612 return load_option_file(argv[0]);
1615 static enum option_code
1616 set_option(const char *opt, char *value)
1618 const char *argv[SIZEOF_ARG];
1619 int argc = 0;
1621 if (!argv_from_string(argv, &argc, value))
1622 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1624 if (!strcmp(opt, "color"))
1625 return option_color_command(argc, argv);
1627 if (!strcmp(opt, "set"))
1628 return option_set_command(argc, argv);
1630 if (!strcmp(opt, "bind"))
1631 return option_bind_command(argc, argv);
1633 if (!strcmp(opt, "source"))
1634 return option_source_command(argc, argv);
1636 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1639 struct config_state {
1640 const char *path;
1641 int lineno;
1642 bool errors;
1645 static int
1646 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1648 struct config_state *config = data;
1649 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1651 config->lineno++;
1653 /* Check for comment markers, since read_properties() will
1654 * only ensure opt and value are split at first " \t". */
1655 optlen = strcspn(opt, "#");
1656 if (optlen == 0)
1657 return OK;
1659 if (opt[optlen] == 0) {
1660 /* Look for comment endings in the value. */
1661 size_t len = strcspn(value, "#");
1663 if (len < valuelen) {
1664 valuelen = len;
1665 value[valuelen] = 0;
1668 status = set_option(opt, value);
1671 if (status != OPT_OK) {
1672 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1673 option_errors[status], (int) optlen, opt);
1674 config->errors = TRUE;
1677 /* Always keep going if errors are encountered. */
1678 return OK;
1681 static enum option_code
1682 load_option_file(const char *path)
1684 struct config_state config = { path, 0, FALSE };
1685 struct io io;
1687 /* Do not read configuration from stdin if set to "" */
1688 if (!path || !strlen(path))
1689 return OPT_OK;
1691 /* It's OK that the file doesn't exist. */
1692 if (!io_open(&io, "%s", path))
1693 return OPT_ERR_FILE_DOES_NOT_EXIST;
1695 if (io_load(&io, " \t", read_option, &config) == ERR ||
1696 config.errors == TRUE)
1697 warn("Errors while loading %s.", path);
1698 return OPT_OK;
1701 static int
1702 load_options(void)
1704 const char *home = getenv("HOME");
1705 const char *tigrc_user = getenv("TIGRC_USER");
1706 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1707 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1708 char buf[SIZEOF_STR];
1710 if (!tigrc_system)
1711 tigrc_system = SYSCONFDIR "/tigrc";
1712 load_option_file(tigrc_system);
1714 if (!tigrc_user) {
1715 if (!home || !string_format(buf, "%s/.tigrc", home))
1716 return ERR;
1717 tigrc_user = buf;
1719 load_option_file(tigrc_user);
1721 /* Add _after_ loading config files to avoid adding run requests
1722 * that conflict with keybindings. */
1723 add_builtin_run_requests();
1725 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1726 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1727 int argc = 0;
1729 if (!string_format(buf, "%s", tig_diff_opts) ||
1730 !argv_from_string(diff_opts, &argc, buf))
1731 die("TIG_DIFF_OPTS contains too many arguments");
1732 else if (!argv_copy(&opt_diff_argv, diff_opts))
1733 die("Failed to format TIG_DIFF_OPTS arguments");
1736 return OK;
1741 * The viewer
1744 struct view;
1745 struct view_ops;
1747 /* The display array of active views and the index of the current view. */
1748 static struct view *display[2];
1749 static WINDOW *display_win[2];
1750 static WINDOW *display_title[2];
1751 static WINDOW *display_sep;
1753 static unsigned int current_view;
1755 #define foreach_displayed_view(view, i) \
1756 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1758 #define displayed_views() (display[1] != NULL ? 2 : 1)
1760 /* Current head and commit ID */
1761 static char ref_blob[SIZEOF_REF] = "";
1762 static char ref_commit[SIZEOF_REF] = "HEAD";
1763 static char ref_head[SIZEOF_REF] = "HEAD";
1764 static char ref_branch[SIZEOF_REF] = "";
1765 static char ref_status[SIZEOF_STR] = "";
1767 enum view_flag {
1768 VIEW_NO_FLAGS = 0,
1769 VIEW_ALWAYS_LINENO = 1 << 0,
1770 VIEW_CUSTOM_STATUS = 1 << 1,
1771 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1772 VIEW_ADD_PAGER_REFS = 1 << 3,
1773 VIEW_OPEN_DIFF = 1 << 4,
1774 VIEW_NO_REF = 1 << 5,
1775 VIEW_NO_GIT_DIR = 1 << 6,
1776 VIEW_DIFF_LIKE = 1 << 7,
1777 VIEW_STDIN = 1 << 8,
1778 VIEW_SEND_CHILD_ENTER = 1 << 9,
1781 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1783 struct position {
1784 unsigned long offset; /* Offset of the window top */
1785 unsigned long col; /* Offset from the window side. */
1786 unsigned long lineno; /* Current line number */
1789 struct view {
1790 const char *name; /* View name */
1791 const char *id; /* Points to either of ref_{head,commit,blob} */
1793 struct view_ops *ops; /* View operations */
1795 char ref[SIZEOF_REF]; /* Hovered commit reference */
1796 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1798 int height, width; /* The width and height of the main window */
1799 WINDOW *win; /* The main window */
1801 /* Navigation */
1802 struct position pos; /* Current position. */
1803 struct position prev_pos; /* Previous position. */
1805 /* Searching */
1806 char grep[SIZEOF_STR]; /* Search string */
1807 regex_t *regex; /* Pre-compiled regexp */
1809 /* If non-NULL, points to the view that opened this view. If this view
1810 * is closed tig will switch back to the parent view. */
1811 struct view *parent;
1812 struct view *prev;
1814 /* Buffering */
1815 size_t lines; /* Total number of lines */
1816 struct line *line; /* Line index */
1817 unsigned int digits; /* Number of digits in the lines member. */
1819 /* Number of lines with custom status, not to be counted in the
1820 * view title. */
1821 unsigned int custom_lines;
1823 /* Drawing */
1824 struct line *curline; /* Line currently being drawn. */
1825 enum line_type curtype; /* Attribute currently used for drawing. */
1826 unsigned long col; /* Column when drawing. */
1827 bool has_scrolled; /* View was scrolled. */
1829 /* Loading */
1830 const char **argv; /* Shell command arguments. */
1831 const char *dir; /* Directory from which to execute. */
1832 struct io io;
1833 struct io *pipe;
1834 time_t start_time;
1835 time_t update_secs;
1836 struct encoding *encoding;
1837 bool unrefreshable;
1839 /* Private data */
1840 void *private;
1843 enum open_flags {
1844 OPEN_DEFAULT = 0, /* Use default view switching. */
1845 OPEN_SPLIT = 1, /* Split current view. */
1846 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1847 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1848 OPEN_PREPARED = 32, /* Open already prepared command. */
1849 OPEN_EXTRA = 64, /* Open extra data from command. */
1852 struct view_ops {
1853 /* What type of content being displayed. Used in the title bar. */
1854 const char *type;
1855 /* What keymap does this view have */
1856 struct keymap keymap;
1857 /* Flags to control the view behavior. */
1858 enum view_flag flags;
1859 /* Size of private data. */
1860 size_t private_size;
1861 /* Open and reads in all view content. */
1862 bool (*open)(struct view *view, enum open_flags flags);
1863 /* Read one line; updates view->line. */
1864 bool (*read)(struct view *view, char *data);
1865 /* Draw one line; @lineno must be < view->height. */
1866 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1867 /* Depending on view handle a special requests. */
1868 enum request (*request)(struct view *view, enum request request, struct line *line);
1869 /* Search for regexp in a line. */
1870 bool (*grep)(struct view *view, struct line *line);
1871 /* Select line */
1872 void (*select)(struct view *view, struct line *line);
1875 #define VIEW_OPS(id, name, ref) name##_ops
1876 static struct view_ops VIEW_INFO(VIEW_OPS);
1878 static struct view views[] = {
1879 #define VIEW_DATA(id, name, ref) \
1880 { #name, ref, &name##_ops }
1881 VIEW_INFO(VIEW_DATA)
1884 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1886 #define foreach_view(view, i) \
1887 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1889 #define view_is_displayed(view) \
1890 (view == display[0] || view == display[1])
1892 #define view_has_line(view, line_) \
1893 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1895 static bool
1896 forward_request_to_child(struct view *child, enum request request)
1898 return displayed_views() == 2 && view_is_displayed(child) &&
1899 !strcmp(child->vid, child->id);
1902 static enum request
1903 view_request(struct view *view, enum request request)
1905 if (!view || !view->lines)
1906 return request;
1908 if (request == REQ_ENTER && !opt_focus_child &&
1909 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
1910 struct view *child = display[1];
1912 if (forward_request_to_child(child, request)) {
1913 view_request(child, request);
1914 return REQ_NONE;
1918 if (request == REQ_REFRESH && view->unrefreshable) {
1919 report("This view can not be refreshed");
1920 return REQ_NONE;
1923 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1927 * View drawing.
1930 static inline void
1931 set_view_attr(struct view *view, enum line_type type)
1933 if (!view->curline->selected && view->curtype != type) {
1934 (void) wattrset(view->win, get_line_attr(type));
1935 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1936 view->curtype = type;
1940 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1942 static bool
1943 draw_chars(struct view *view, enum line_type type, const char *string,
1944 int max_len, bool use_tilde)
1946 static char out_buffer[BUFSIZ * 2];
1947 int len = 0;
1948 int col = 0;
1949 int trimmed = FALSE;
1950 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1952 if (max_len <= 0)
1953 return VIEW_MAX_LEN(view) <= 0;
1955 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1957 set_view_attr(view, type);
1958 if (len > 0) {
1959 if (opt_iconv_out != ICONV_NONE) {
1960 size_t inlen = len + 1;
1961 char *instr = calloc(1, inlen);
1962 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1963 if (!instr)
1964 return VIEW_MAX_LEN(view) <= 0;
1966 strncpy(instr, string, len);
1968 char *outbuf = out_buffer;
1969 size_t outlen = sizeof(out_buffer);
1971 size_t ret;
1973 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1974 if (ret != (size_t) -1) {
1975 string = out_buffer;
1976 len = sizeof(out_buffer) - outlen;
1978 free(instr);
1981 waddnstr(view->win, string, len);
1983 if (trimmed && use_tilde) {
1984 set_view_attr(view, LINE_DELIMITER);
1985 waddch(view->win, '~');
1986 col++;
1990 view->col += col;
1991 return VIEW_MAX_LEN(view) <= 0;
1994 static bool
1995 draw_space(struct view *view, enum line_type type, int max, int spaces)
1997 static char space[] = " ";
1999 spaces = MIN(max, spaces);
2001 while (spaces > 0) {
2002 int len = MIN(spaces, sizeof(space) - 1);
2004 if (draw_chars(view, type, space, len, FALSE))
2005 return TRUE;
2006 spaces -= len;
2009 return VIEW_MAX_LEN(view) <= 0;
2012 static bool
2013 draw_text(struct view *view, enum line_type type, const char *string)
2015 static char text[SIZEOF_STR];
2017 do {
2018 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2020 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
2021 return TRUE;
2022 string += pos;
2023 } while (*string);
2025 return VIEW_MAX_LEN(view) <= 0;
2028 static bool PRINTF_LIKE(3, 4)
2029 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2031 char text[SIZEOF_STR];
2032 int retval;
2034 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2035 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2038 static bool
2039 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2041 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2042 int max = VIEW_MAX_LEN(view);
2043 int i;
2045 if (max < size)
2046 size = max;
2048 set_view_attr(view, type);
2049 /* Using waddch() instead of waddnstr() ensures that
2050 * they'll be rendered correctly for the cursor line. */
2051 for (i = skip; i < size; i++)
2052 waddch(view->win, graphic[i]);
2054 view->col += size;
2055 if (separator) {
2056 if (size < max && skip <= size)
2057 waddch(view->win, ' ');
2058 view->col++;
2061 return VIEW_MAX_LEN(view) <= 0;
2064 static bool
2065 draw_field(struct view *view, enum line_type type, const char *text, int width, bool trim)
2067 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2068 int col = view->col;
2070 if (!text)
2071 return draw_space(view, type, max, max);
2073 return draw_chars(view, type, text, max - 1, trim)
2074 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2077 static bool
2078 draw_date(struct view *view, struct time *time)
2080 const char *date = mkdate(time, opt_date);
2081 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2083 if (opt_date == DATE_NO)
2084 return FALSE;
2086 return draw_field(view, LINE_DATE, date, cols, FALSE);
2089 static bool
2090 draw_author(struct view *view, const char *author)
2092 bool trim = author_trim(opt_author_width);
2093 const char *text = mkauthor(author, opt_author_width, opt_author);
2095 if (opt_author == AUTHOR_NO)
2096 return FALSE;
2098 return draw_field(view, LINE_AUTHOR, text, opt_author_width, trim);
2101 static bool
2102 draw_id(struct view *view, enum line_type type, const char *id)
2104 return draw_field(view, type, id, opt_id_cols, FALSE);
2107 static bool
2108 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2110 bool trim = filename && strlen(filename) >= opt_filename_width;
2112 if (opt_filename == FILENAME_NO)
2113 return FALSE;
2115 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2116 return FALSE;
2118 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, trim);
2121 static bool
2122 draw_mode(struct view *view, mode_t mode)
2124 const char *str = mkmode(mode);
2126 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), FALSE);
2129 static bool
2130 draw_lineno(struct view *view, unsigned int lineno)
2132 char number[10];
2133 int digits3 = view->digits < 3 ? 3 : view->digits;
2134 int max = MIN(VIEW_MAX_LEN(view), digits3);
2135 char *text = NULL;
2136 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2138 if (!opt_line_number)
2139 return FALSE;
2141 lineno += view->pos.offset + 1;
2142 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2143 static char fmt[] = "%1ld";
2145 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2146 if (string_format(number, fmt, lineno))
2147 text = number;
2149 if (text)
2150 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2151 else
2152 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2153 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2156 static bool
2157 draw_refs(struct view *view, struct ref_list *refs)
2159 size_t i;
2161 if (!opt_show_refs || !refs)
2162 return FALSE;
2164 for (i = 0; i < refs->size; i++) {
2165 struct ref *ref = refs->refs[i];
2166 enum line_type type = get_line_type_from_ref(ref);
2168 if (draw_formatted(view, type, "[%s]", ref->name))
2169 return TRUE;
2171 if (draw_text(view, LINE_DEFAULT, " "))
2172 return TRUE;
2175 return FALSE;
2178 static bool
2179 draw_view_line(struct view *view, unsigned int lineno)
2181 struct line *line;
2182 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2184 assert(view_is_displayed(view));
2186 if (view->pos.offset + lineno >= view->lines)
2187 return FALSE;
2189 line = &view->line[view->pos.offset + lineno];
2191 wmove(view->win, lineno, 0);
2192 if (line->cleareol)
2193 wclrtoeol(view->win);
2194 view->col = 0;
2195 view->curline = line;
2196 view->curtype = LINE_NONE;
2197 line->selected = FALSE;
2198 line->dirty = line->cleareol = 0;
2200 if (selected) {
2201 set_view_attr(view, LINE_CURSOR);
2202 line->selected = TRUE;
2203 view->ops->select(view, line);
2206 return view->ops->draw(view, line, lineno);
2209 static void
2210 redraw_view_dirty(struct view *view)
2212 bool dirty = FALSE;
2213 int lineno;
2215 for (lineno = 0; lineno < view->height; lineno++) {
2216 if (view->pos.offset + lineno >= view->lines)
2217 break;
2218 if (!view->line[view->pos.offset + lineno].dirty)
2219 continue;
2220 dirty = TRUE;
2221 if (!draw_view_line(view, lineno))
2222 break;
2225 if (!dirty)
2226 return;
2227 wnoutrefresh(view->win);
2230 static void
2231 redraw_view_from(struct view *view, int lineno)
2233 assert(0 <= lineno && lineno < view->height);
2235 for (; lineno < view->height; lineno++) {
2236 if (!draw_view_line(view, lineno))
2237 break;
2240 wnoutrefresh(view->win);
2243 static void
2244 redraw_view(struct view *view)
2246 werase(view->win);
2247 redraw_view_from(view, 0);
2251 static void
2252 update_view_title(struct view *view)
2254 char buf[SIZEOF_STR];
2255 char state[SIZEOF_STR];
2256 size_t bufpos = 0, statelen = 0;
2257 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2258 struct line *line = &view->line[view->pos.lineno];
2260 assert(view_is_displayed(view));
2262 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2263 line->lineno) {
2264 unsigned int view_lines = view->pos.offset + view->height;
2265 unsigned int lines = view->lines
2266 ? MIN(view_lines, view->lines) * 100 / view->lines
2267 : 0;
2269 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2270 view->ops->type,
2271 line->lineno,
2272 view->lines - view->custom_lines,
2273 lines);
2277 if (view->pipe) {
2278 time_t secs = time(NULL) - view->start_time;
2280 /* Three git seconds are a long time ... */
2281 if (secs > 2)
2282 string_format_from(state, &statelen, " loading %lds", secs);
2285 string_format_from(buf, &bufpos, "[%s]", view->name);
2286 if (*view->ref && bufpos < view->width) {
2287 size_t refsize = strlen(view->ref);
2288 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2290 if (minsize < view->width)
2291 refsize = view->width - minsize + 7;
2292 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2295 if (statelen && bufpos < view->width) {
2296 string_format_from(buf, &bufpos, "%s", state);
2299 if (view == display[current_view])
2300 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2301 else
2302 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2304 mvwaddnstr(window, 0, 0, buf, bufpos);
2305 wclrtoeol(window);
2306 wnoutrefresh(window);
2309 static int
2310 apply_step(double step, int value)
2312 if (step >= 1)
2313 return (int) step;
2314 value *= step + 0.01;
2315 return value ? value : 1;
2318 static void
2319 apply_horizontal_split(struct view *base, struct view *view)
2321 view->width = base->width;
2322 view->height = apply_step(opt_scale_split_view, base->height);
2323 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2324 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2325 base->height -= view->height;
2328 static void
2329 apply_vertical_split(struct view *base, struct view *view)
2331 view->height = base->height;
2332 view->width = apply_step(opt_scale_vsplit_view, base->width);
2333 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2334 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2335 base->width -= view->width;
2338 static void
2339 redraw_display_separator(bool clear)
2341 if (displayed_views() > 1 && opt_vsplit) {
2342 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2344 if (clear)
2345 wclear(display_sep);
2346 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2347 wnoutrefresh(display_sep);
2351 static void
2352 resize_display(void)
2354 int x, y, i;
2355 struct view *base = display[0];
2356 struct view *view = display[1] ? display[1] : display[0];
2358 /* Setup window dimensions */
2360 getmaxyx(stdscr, base->height, base->width);
2362 /* Make room for the status window. */
2363 base->height -= 1;
2365 if (view != base) {
2366 if (opt_vsplit) {
2367 apply_vertical_split(base, view);
2369 /* Make room for the separator bar. */
2370 view->width -= 1;
2371 } else {
2372 apply_horizontal_split(base, view);
2375 /* Make room for the title bar. */
2376 view->height -= 1;
2379 /* Make room for the title bar. */
2380 base->height -= 1;
2382 x = y = 0;
2384 foreach_displayed_view (view, i) {
2385 if (!display_win[i]) {
2386 display_win[i] = newwin(view->height, view->width, y, x);
2387 if (!display_win[i])
2388 die("Failed to create %s view", view->name);
2390 scrollok(display_win[i], FALSE);
2392 display_title[i] = newwin(1, view->width, y + view->height, x);
2393 if (!display_title[i])
2394 die("Failed to create title window");
2396 } else {
2397 wresize(display_win[i], view->height, view->width);
2398 mvwin(display_win[i], y, x);
2399 wresize(display_title[i], 1, view->width);
2400 mvwin(display_title[i], y + view->height, x);
2403 if (i > 0 && opt_vsplit) {
2404 if (!display_sep) {
2405 display_sep = newwin(view->height, 1, 0, x - 1);
2406 if (!display_sep)
2407 die("Failed to create separator window");
2409 } else {
2410 wresize(display_sep, view->height, 1);
2411 mvwin(display_sep, 0, x - 1);
2415 view->win = display_win[i];
2417 if (opt_vsplit)
2418 x += view->width + 1;
2419 else
2420 y += view->height + 1;
2423 redraw_display_separator(FALSE);
2426 static void
2427 redraw_display(bool clear)
2429 struct view *view;
2430 int i;
2432 foreach_displayed_view (view, i) {
2433 if (clear)
2434 wclear(view->win);
2435 redraw_view(view);
2436 update_view_title(view);
2439 redraw_display_separator(clear);
2443 * Option management
2446 #define TOGGLE_MENU \
2447 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2448 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2449 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2450 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2451 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2452 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2453 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2454 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2455 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2456 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL) \
2457 TOGGLE_(ID, 'X', "commit ID display", &opt_show_id, NULL)
2459 static bool
2460 toggle_option(enum request request)
2462 const struct {
2463 enum request request;
2464 const struct enum_map *map;
2465 size_t map_size;
2466 } data[] = {
2467 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2468 TOGGLE_MENU
2469 #undef TOGGLE_
2471 const struct menu_item menu[] = {
2472 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2473 TOGGLE_MENU
2474 #undef TOGGLE_
2475 { 0 }
2477 int i = 0;
2479 if (request == REQ_OPTIONS) {
2480 if (!prompt_menu("Toggle option", menu, &i))
2481 return FALSE;
2482 } else {
2483 while (i < ARRAY_SIZE(data) && data[i].request != request)
2484 i++;
2485 if (i >= ARRAY_SIZE(data))
2486 die("Invalid request (%d)", request);
2489 if (data[i].map != NULL) {
2490 unsigned int *opt = menu[i].data;
2492 *opt = (*opt + 1) % data[i].map_size;
2493 if (data[i].map == ignore_space_map) {
2494 update_ignore_space_arg();
2495 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2496 return TRUE;
2498 } else if (data[i].map == commit_order_map) {
2499 update_commit_order_arg();
2500 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2501 return TRUE;
2504 redraw_display(FALSE);
2505 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2507 } else {
2508 bool *option = menu[i].data;
2510 *option = !*option;
2511 redraw_display(FALSE);
2512 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2515 return FALSE;
2520 * Navigation
2523 static bool
2524 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2526 if (lineno >= view->lines)
2527 lineno = view->lines > 0 ? view->lines - 1 : 0;
2529 if (offset > lineno || offset + view->height <= lineno) {
2530 unsigned long half = view->height / 2;
2532 if (lineno > half)
2533 offset = lineno - half;
2534 else
2535 offset = 0;
2538 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2539 view->pos.offset = offset;
2540 view->pos.lineno = lineno;
2541 return TRUE;
2544 return FALSE;
2547 /* Scrolling backend */
2548 static void
2549 do_scroll_view(struct view *view, int lines)
2551 bool redraw_current_line = FALSE;
2553 /* The rendering expects the new offset. */
2554 view->pos.offset += lines;
2556 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2557 assert(lines);
2559 /* Move current line into the view. */
2560 if (view->pos.lineno < view->pos.offset) {
2561 view->pos.lineno = view->pos.offset;
2562 redraw_current_line = TRUE;
2563 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2564 view->pos.lineno = view->pos.offset + view->height - 1;
2565 redraw_current_line = TRUE;
2568 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2570 /* Redraw the whole screen if scrolling is pointless. */
2571 if (view->height < ABS(lines)) {
2572 redraw_view(view);
2574 } else {
2575 int line = lines > 0 ? view->height - lines : 0;
2576 int end = line + ABS(lines);
2578 scrollok(view->win, TRUE);
2579 wscrl(view->win, lines);
2580 scrollok(view->win, FALSE);
2582 while (line < end && draw_view_line(view, line))
2583 line++;
2585 if (redraw_current_line)
2586 draw_view_line(view, view->pos.lineno - view->pos.offset);
2587 wnoutrefresh(view->win);
2590 view->has_scrolled = TRUE;
2591 report_clear();
2594 /* Scroll frontend */
2595 static void
2596 scroll_view(struct view *view, enum request request)
2598 int lines = 1;
2600 assert(view_is_displayed(view));
2602 switch (request) {
2603 case REQ_SCROLL_FIRST_COL:
2604 view->pos.col = 0;
2605 redraw_view_from(view, 0);
2606 report_clear();
2607 return;
2608 case REQ_SCROLL_LEFT:
2609 if (view->pos.col == 0) {
2610 report("Cannot scroll beyond the first column");
2611 return;
2613 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2614 view->pos.col = 0;
2615 else
2616 view->pos.col -= apply_step(opt_hscroll, view->width);
2617 redraw_view_from(view, 0);
2618 report_clear();
2619 return;
2620 case REQ_SCROLL_RIGHT:
2621 view->pos.col += apply_step(opt_hscroll, view->width);
2622 redraw_view(view);
2623 report_clear();
2624 return;
2625 case REQ_SCROLL_PAGE_DOWN:
2626 lines = view->height;
2627 case REQ_SCROLL_LINE_DOWN:
2628 if (view->pos.offset + lines > view->lines)
2629 lines = view->lines - view->pos.offset;
2631 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2632 report("Cannot scroll beyond the last line");
2633 return;
2635 break;
2637 case REQ_SCROLL_PAGE_UP:
2638 lines = view->height;
2639 case REQ_SCROLL_LINE_UP:
2640 if (lines > view->pos.offset)
2641 lines = view->pos.offset;
2643 if (lines == 0) {
2644 report("Cannot scroll beyond the first line");
2645 return;
2648 lines = -lines;
2649 break;
2651 default:
2652 die("request %d not handled in switch", request);
2655 do_scroll_view(view, lines);
2658 /* Cursor moving */
2659 static void
2660 move_view(struct view *view, enum request request)
2662 int scroll_steps = 0;
2663 int steps;
2665 switch (request) {
2666 case REQ_MOVE_FIRST_LINE:
2667 steps = -view->pos.lineno;
2668 break;
2670 case REQ_MOVE_LAST_LINE:
2671 steps = view->lines - view->pos.lineno - 1;
2672 break;
2674 case REQ_MOVE_PAGE_UP:
2675 steps = view->height > view->pos.lineno
2676 ? -view->pos.lineno : -view->height;
2677 break;
2679 case REQ_MOVE_PAGE_DOWN:
2680 steps = view->pos.lineno + view->height >= view->lines
2681 ? view->lines - view->pos.lineno - 1 : view->height;
2682 break;
2684 case REQ_MOVE_UP:
2685 case REQ_PREVIOUS:
2686 steps = -1;
2687 break;
2689 case REQ_MOVE_DOWN:
2690 case REQ_NEXT:
2691 steps = 1;
2692 break;
2694 default:
2695 die("request %d not handled in switch", request);
2698 if (steps <= 0 && view->pos.lineno == 0) {
2699 report("Cannot move beyond the first line");
2700 return;
2702 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2703 report("Cannot move beyond the last line");
2704 return;
2707 /* Move the current line */
2708 view->pos.lineno += steps;
2709 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2711 /* Check whether the view needs to be scrolled */
2712 if (view->pos.lineno < view->pos.offset ||
2713 view->pos.lineno >= view->pos.offset + view->height) {
2714 scroll_steps = steps;
2715 if (steps < 0 && -steps > view->pos.offset) {
2716 scroll_steps = -view->pos.offset;
2718 } else if (steps > 0) {
2719 if (view->pos.lineno == view->lines - 1 &&
2720 view->lines > view->height) {
2721 scroll_steps = view->lines - view->pos.offset - 1;
2722 if (scroll_steps >= view->height)
2723 scroll_steps -= view->height - 1;
2728 if (!view_is_displayed(view)) {
2729 view->pos.offset += scroll_steps;
2730 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2731 view->ops->select(view, &view->line[view->pos.lineno]);
2732 return;
2735 /* Repaint the old "current" line if we be scrolling */
2736 if (ABS(steps) < view->height)
2737 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2739 if (scroll_steps) {
2740 do_scroll_view(view, scroll_steps);
2741 return;
2744 /* Draw the current line */
2745 draw_view_line(view, view->pos.lineno - view->pos.offset);
2747 wnoutrefresh(view->win);
2748 report_clear();
2753 * Searching
2756 static void search_view(struct view *view, enum request request);
2758 static bool
2759 grep_text(struct view *view, const char *text[])
2761 regmatch_t pmatch;
2762 size_t i;
2764 for (i = 0; text[i]; i++)
2765 if (*text[i] &&
2766 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2767 return TRUE;
2768 return FALSE;
2771 static void
2772 select_view_line(struct view *view, unsigned long lineno)
2774 struct position old = view->pos;
2776 if (goto_view_line(view, view->pos.offset, lineno)) {
2777 if (view_is_displayed(view)) {
2778 if (old.offset != view->pos.offset) {
2779 redraw_view(view);
2780 } else {
2781 draw_view_line(view, old.lineno - view->pos.offset);
2782 draw_view_line(view, view->pos.lineno - view->pos.offset);
2783 wnoutrefresh(view->win);
2785 } else {
2786 view->ops->select(view, &view->line[view->pos.lineno]);
2791 static void
2792 find_next(struct view *view, enum request request)
2794 unsigned long lineno = view->pos.lineno;
2795 int direction;
2797 if (!*view->grep) {
2798 if (!*opt_search)
2799 report("No previous search");
2800 else
2801 search_view(view, request);
2802 return;
2805 switch (request) {
2806 case REQ_SEARCH:
2807 case REQ_FIND_NEXT:
2808 direction = 1;
2809 break;
2811 case REQ_SEARCH_BACK:
2812 case REQ_FIND_PREV:
2813 direction = -1;
2814 break;
2816 default:
2817 return;
2820 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2821 lineno += direction;
2823 /* Note, lineno is unsigned long so will wrap around in which case it
2824 * will become bigger than view->lines. */
2825 for (; lineno < view->lines; lineno += direction) {
2826 if (view->ops->grep(view, &view->line[lineno])) {
2827 select_view_line(view, lineno);
2828 report("Line %ld matches '%s'", lineno + 1, view->grep);
2829 return;
2833 report("No match found for '%s'", view->grep);
2836 static void
2837 search_view(struct view *view, enum request request)
2839 int regex_err;
2840 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
2842 if (view->regex) {
2843 regfree(view->regex);
2844 *view->grep = 0;
2845 } else {
2846 view->regex = calloc(1, sizeof(*view->regex));
2847 if (!view->regex)
2848 return;
2851 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
2852 if (regex_err != 0) {
2853 char buf[SIZEOF_STR] = "unknown error";
2855 regerror(regex_err, view->regex, buf, sizeof(buf));
2856 report("Search failed: %s", buf);
2857 return;
2860 string_copy(view->grep, opt_search);
2862 find_next(view, request);
2866 * Incremental updating
2869 static inline bool
2870 check_position(struct position *pos)
2872 return pos->lineno || pos->col || pos->offset;
2875 static inline void
2876 clear_position(struct position *pos)
2878 memset(pos, 0, sizeof(*pos));
2881 static void
2882 reset_view(struct view *view)
2884 int i;
2886 for (i = 0; i < view->lines; i++)
2887 if (!view->line[i].dont_free)
2888 free(view->line[i].data);
2889 free(view->line);
2891 view->prev_pos = view->pos;
2892 clear_position(&view->pos);
2894 view->line = NULL;
2895 view->lines = 0;
2896 view->vid[0] = 0;
2897 view->custom_lines = 0;
2898 view->update_secs = 0;
2901 static const char *
2902 format_arg(const char *name)
2904 static struct {
2905 const char *name;
2906 size_t namelen;
2907 const char *value;
2908 const char *value_if_empty;
2909 } vars[] = {
2910 #define FORMAT_VAR(name, value, value_if_empty) \
2911 { name, STRING_SIZE(name), value, value_if_empty }
2912 FORMAT_VAR("%(directory)", opt_path, "."),
2913 FORMAT_VAR("%(file)", opt_file, ""),
2914 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2915 FORMAT_VAR("%(head)", ref_head, ""),
2916 FORMAT_VAR("%(commit)", ref_commit, ""),
2917 FORMAT_VAR("%(blob)", ref_blob, ""),
2918 FORMAT_VAR("%(branch)", ref_branch, ""),
2920 int i;
2922 if (!prefixcmp(name, "%(prompt"))
2923 return read_prompt("Command argument: ");
2925 for (i = 0; i < ARRAY_SIZE(vars); i++)
2926 if (!strncmp(name, vars[i].name, vars[i].namelen))
2927 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2929 report("Unknown replacement: `%s`", name);
2930 return NULL;
2933 static bool
2934 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2936 char buf[SIZEOF_STR];
2937 int argc;
2939 argv_free(*dst_argv);
2941 for (argc = 0; src_argv[argc]; argc++) {
2942 const char *arg = src_argv[argc];
2943 size_t bufpos = 0;
2945 if (!strcmp(arg, "%(fileargs)")) {
2946 if (!argv_append_array(dst_argv, opt_file_argv))
2947 break;
2948 continue;
2950 } else if (!strcmp(arg, "%(diffargs)")) {
2951 if (!argv_append_array(dst_argv, opt_diff_argv))
2952 break;
2953 continue;
2955 } else if (!strcmp(arg, "%(blameargs)")) {
2956 if (!argv_append_array(dst_argv, opt_blame_argv))
2957 break;
2958 continue;
2960 } else if (!strcmp(arg, "%(revargs)") ||
2961 (first && !strcmp(arg, "%(commit)"))) {
2962 if (!argv_append_array(dst_argv, opt_rev_argv))
2963 break;
2964 continue;
2967 while (arg) {
2968 char *next = strstr(arg, "%(");
2969 int len = next - arg;
2970 const char *value;
2972 if (!next) {
2973 len = strlen(arg);
2974 value = "";
2976 } else {
2977 value = format_arg(next);
2979 if (!value) {
2980 return FALSE;
2984 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2985 return FALSE;
2987 arg = next ? strchr(next, ')') + 1 : NULL;
2990 if (!argv_append(dst_argv, buf))
2991 break;
2994 return src_argv[argc] == NULL;
2997 static bool
2998 restore_view_position(struct view *view)
3000 /* A view without a previous view is the first view */
3001 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3002 select_view_line(view, opt_lineno - 1);
3003 opt_lineno = 0;
3006 /* Ensure that the view position is in a valid state. */
3007 if (!check_position(&view->prev_pos) ||
3008 (view->pipe && view->lines <= view->prev_pos.lineno))
3009 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3011 /* Changing the view position cancels the restoring. */
3012 /* FIXME: Changing back to the first line is not detected. */
3013 if (check_position(&view->pos)) {
3014 clear_position(&view->prev_pos);
3015 return FALSE;
3018 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3019 view_is_displayed(view))
3020 werase(view->win);
3022 view->pos.col = view->prev_pos.col;
3023 clear_position(&view->prev_pos);
3025 return TRUE;
3028 static void
3029 end_update(struct view *view, bool force)
3031 if (!view->pipe)
3032 return;
3033 while (!view->ops->read(view, NULL))
3034 if (!force)
3035 return;
3036 if (force)
3037 io_kill(view->pipe);
3038 io_done(view->pipe);
3039 view->pipe = NULL;
3042 static void
3043 setup_update(struct view *view, const char *vid)
3045 reset_view(view);
3046 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3047 string_ncopy(view->vid, vid, strlen(vid));
3048 view->pipe = &view->io;
3049 view->start_time = time(NULL);
3052 static bool
3053 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3055 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3056 bool extra = !!(flags & (OPEN_EXTRA));
3057 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3058 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3059 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3061 opt_stdin = FALSE;
3063 if ((!reload && !strcmp(view->vid, view->id)) ||
3064 ((flags & OPEN_REFRESH) && view->unrefreshable))
3065 return TRUE;
3067 if (view->pipe) {
3068 if (extra)
3069 io_done(view->pipe);
3070 else
3071 end_update(view, TRUE);
3074 view->unrefreshable = use_stdin;
3076 if (!refresh && argv) {
3077 view->dir = dir;
3078 if (!format_argv(&view->argv, argv, !view->prev)) {
3079 report("Failed to format %s arguments", view->name);
3080 return FALSE;
3083 /* Put the current ref_* value to the view title ref
3084 * member. This is needed by the blob view. Most other
3085 * views sets it automatically after loading because the
3086 * first line is a commit line. */
3087 string_copy_rev(view->ref, view->id);
3090 if (view->argv && view->argv[0] &&
3091 !io_run(&view->io, io_type, view->dir, view->argv)) {
3092 report("Failed to open %s view", view->name);
3093 return FALSE;
3096 if (!extra)
3097 setup_update(view, view->id);
3099 return TRUE;
3102 static bool
3103 update_view(struct view *view)
3105 char *line;
3106 /* Clear the view and redraw everything since the tree sorting
3107 * might have rearranged things. */
3108 bool redraw = view->lines == 0;
3109 bool can_read = TRUE;
3110 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3112 if (!view->pipe)
3113 return TRUE;
3115 if (!io_can_read(view->pipe, FALSE)) {
3116 if (view->lines == 0 && view_is_displayed(view)) {
3117 time_t secs = time(NULL) - view->start_time;
3119 if (secs > 1 && secs > view->update_secs) {
3120 if (view->update_secs == 0)
3121 redraw_view(view);
3122 update_view_title(view);
3123 view->update_secs = secs;
3126 return TRUE;
3129 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3130 if (encoding) {
3131 line = encoding_convert(encoding, line);
3134 if (!view->ops->read(view, line)) {
3135 report("Allocation failure");
3136 end_update(view, TRUE);
3137 return FALSE;
3142 unsigned long lines = view->lines;
3143 int digits;
3145 for (digits = 0; lines; digits++)
3146 lines /= 10;
3148 /* Keep the displayed view in sync with line number scaling. */
3149 if (digits != view->digits) {
3150 view->digits = digits;
3151 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3152 redraw = TRUE;
3156 if (io_error(view->pipe)) {
3157 report("Failed to read: %s", io_strerror(view->pipe));
3158 end_update(view, TRUE);
3160 } else if (io_eof(view->pipe)) {
3161 if (view_is_displayed(view))
3162 report_clear();
3163 end_update(view, FALSE);
3166 if (restore_view_position(view))
3167 redraw = TRUE;
3169 if (!view_is_displayed(view))
3170 return TRUE;
3172 if (redraw)
3173 redraw_view_from(view, 0);
3174 else
3175 redraw_view_dirty(view);
3177 /* Update the title _after_ the redraw so that if the redraw picks up a
3178 * commit reference in view->ref it'll be available here. */
3179 update_view_title(view);
3180 return TRUE;
3183 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3185 static struct line *
3186 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3188 struct line *line;
3190 if (!realloc_lines(&view->line, view->lines, 1))
3191 return NULL;
3193 if (data_size) {
3194 void *alloc_data = calloc(1, data_size);
3196 if (!alloc_data)
3197 return NULL;
3199 if (data)
3200 memcpy(alloc_data, data, data_size);
3201 data = alloc_data;
3204 line = &view->line[view->lines++];
3205 memset(line, 0, sizeof(*line));
3206 line->type = type;
3207 line->data = (void *) data;
3208 line->dirty = 1;
3210 if (custom)
3211 view->custom_lines++;
3212 else
3213 line->lineno = view->lines - view->custom_lines;
3215 return line;
3218 static struct line *
3219 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3221 struct line *line = add_line(view, NULL, type, data_size, custom);
3223 if (line)
3224 *ptr = line->data;
3225 return line;
3228 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3229 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3231 static struct line *
3232 add_line_nodata(struct view *view, enum line_type type)
3234 return add_line(view, NULL, type, 0, FALSE);
3237 static struct line *
3238 add_line_static_data(struct view *view, const void *data, enum line_type type)
3240 struct line *line = add_line(view, data, type, 0, FALSE);
3242 if (line)
3243 line->dont_free = TRUE;
3244 return line;
3247 static struct line *
3248 add_line_text(struct view *view, const char *text, enum line_type type)
3250 return add_line(view, text, type, strlen(text) + 1, FALSE);
3253 static struct line * PRINTF_LIKE(3, 4)
3254 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3256 char buf[SIZEOF_STR];
3257 int retval;
3259 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3260 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3264 * View opening
3267 static void
3268 split_view(struct view *prev, struct view *view)
3270 display[1] = view;
3271 current_view = opt_focus_child ? 1 : 0;
3272 view->parent = prev;
3273 resize_display();
3275 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3276 /* Take the title line into account. */
3277 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3279 /* Scroll the view that was split if the current line is
3280 * outside the new limited view. */
3281 do_scroll_view(prev, lines);
3284 if (view != prev && view_is_displayed(prev)) {
3285 /* "Blur" the previous view. */
3286 update_view_title(prev);
3290 static void
3291 maximize_view(struct view *view, bool redraw)
3293 memset(display, 0, sizeof(display));
3294 current_view = 0;
3295 display[current_view] = view;
3296 resize_display();
3297 if (redraw) {
3298 redraw_display(FALSE);
3299 report_clear();
3303 static void
3304 load_view(struct view *view, struct view *prev, enum open_flags flags)
3306 if (view->pipe)
3307 end_update(view, TRUE);
3308 if (view->ops->private_size) {
3309 if (!view->private)
3310 view->private = calloc(1, view->ops->private_size);
3311 else
3312 memset(view->private, 0, view->ops->private_size);
3315 /* When prev == view it means this is the first loaded view. */
3316 if (prev && view != prev) {
3317 view->prev = prev;
3320 if (!view->ops->open(view, flags))
3321 return;
3323 if (prev) {
3324 bool split = !!(flags & OPEN_SPLIT);
3326 if (split) {
3327 split_view(prev, view);
3328 } else {
3329 maximize_view(view, FALSE);
3333 restore_view_position(view);
3335 if (view->pipe && view->lines == 0) {
3336 /* Clear the old view and let the incremental updating refill
3337 * the screen. */
3338 werase(view->win);
3339 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3340 clear_position(&view->prev_pos);
3341 report_clear();
3342 } else if (view_is_displayed(view)) {
3343 redraw_view(view);
3344 report_clear();
3348 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3349 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3351 static void
3352 open_view(struct view *prev, enum request request, enum open_flags flags)
3354 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3355 struct view *view = VIEW(request);
3356 int nviews = displayed_views();
3358 assert(flags ^ OPEN_REFRESH);
3360 if (view == prev && nviews == 1 && !reload) {
3361 report("Already in %s view", view->name);
3362 return;
3365 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3366 report("The %s view is disabled in pager view", view->name);
3367 return;
3370 load_view(view, prev ? prev : view, flags);
3373 static void
3374 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3376 enum request request = view - views + REQ_OFFSET + 1;
3378 if (view->pipe)
3379 end_update(view, TRUE);
3380 view->dir = dir;
3382 if (!argv_copy(&view->argv, argv)) {
3383 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3384 } else {
3385 open_view(prev, request, flags | OPEN_PREPARED);
3389 static void
3390 open_external_viewer(const char *argv[], const char *dir, bool confirm)
3392 def_prog_mode(); /* save current tty modes */
3393 endwin(); /* restore original tty modes */
3394 io_run_fg(argv, dir);
3395 if (confirm) {
3396 fprintf(stderr, "Press Enter to continue");
3397 getc(opt_tty);
3399 reset_prog_mode();
3400 redraw_display(TRUE);
3403 static void
3404 open_mergetool(const char *file)
3406 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3408 open_external_viewer(mergetool_argv, opt_cdup, TRUE);
3411 static void
3412 open_editor(const char *file)
3414 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3415 char editor_cmd[SIZEOF_STR];
3416 const char *editor;
3417 int argc = 0;
3419 editor = getenv("GIT_EDITOR");
3420 if (!editor && *opt_editor)
3421 editor = opt_editor;
3422 if (!editor)
3423 editor = getenv("VISUAL");
3424 if (!editor)
3425 editor = getenv("EDITOR");
3426 if (!editor)
3427 editor = "vi";
3429 string_ncopy(editor_cmd, editor, strlen(editor));
3430 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3431 report("Failed to read editor command");
3432 return;
3435 editor_argv[argc] = file;
3436 open_external_viewer(editor_argv, opt_cdup, TRUE);
3439 static bool
3440 open_run_request(enum request request)
3442 struct run_request *req = get_run_request(request);
3443 const char **argv = NULL;
3445 if (!req) {
3446 report("Unknown run request");
3447 return FALSE;
3450 if (format_argv(&argv, req->argv, FALSE)) {
3451 bool confirmed = !req->confirm;
3453 if (req->confirm) {
3454 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3456 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3457 string_format(prompt, "Run `%s`?", cmd) &&
3458 prompt_yesno(prompt)) {
3459 confirmed = TRUE;
3463 if (confirmed && argv_remove_quotes(argv)) {
3464 if (req->silent)
3465 io_run_bg(argv);
3466 else
3467 open_external_viewer(argv, NULL, !req->exit);
3471 if (argv)
3472 argv_free(argv);
3473 free(argv);
3475 return req->exit;
3479 * User request switch noodle
3482 static int
3483 view_driver(struct view *view, enum request request)
3485 int i;
3487 if (request == REQ_NONE)
3488 return TRUE;
3490 if (request > REQ_NONE) {
3491 if (open_run_request(request))
3492 return FALSE;
3493 if (!view->unrefreshable)
3494 view_request(view, REQ_REFRESH);
3495 return TRUE;
3498 request = view_request(view, request);
3499 if (request == REQ_NONE)
3500 return TRUE;
3502 switch (request) {
3503 case REQ_MOVE_UP:
3504 case REQ_MOVE_DOWN:
3505 case REQ_MOVE_PAGE_UP:
3506 case REQ_MOVE_PAGE_DOWN:
3507 case REQ_MOVE_FIRST_LINE:
3508 case REQ_MOVE_LAST_LINE:
3509 move_view(view, request);
3510 break;
3512 case REQ_SCROLL_FIRST_COL:
3513 case REQ_SCROLL_LEFT:
3514 case REQ_SCROLL_RIGHT:
3515 case REQ_SCROLL_LINE_DOWN:
3516 case REQ_SCROLL_LINE_UP:
3517 case REQ_SCROLL_PAGE_DOWN:
3518 case REQ_SCROLL_PAGE_UP:
3519 scroll_view(view, request);
3520 break;
3522 case REQ_VIEW_MAIN:
3523 case REQ_VIEW_DIFF:
3524 case REQ_VIEW_LOG:
3525 case REQ_VIEW_TREE:
3526 case REQ_VIEW_HELP:
3527 case REQ_VIEW_BRANCH:
3528 case REQ_VIEW_BLAME:
3529 case REQ_VIEW_BLOB:
3530 case REQ_VIEW_STATUS:
3531 case REQ_VIEW_STAGE:
3532 case REQ_VIEW_PAGER:
3533 open_view(view, request, OPEN_DEFAULT);
3534 break;
3536 case REQ_NEXT:
3537 case REQ_PREVIOUS:
3538 if (view->parent) {
3539 int line;
3541 view = view->parent;
3542 line = view->pos.lineno;
3543 move_view(view, request);
3544 if (view_is_displayed(view))
3545 update_view_title(view);
3546 if (line != view->pos.lineno)
3547 view_request(view, REQ_ENTER);
3548 } else {
3549 move_view(view, request);
3551 break;
3553 case REQ_VIEW_NEXT:
3555 int nviews = displayed_views();
3556 int next_view = (current_view + 1) % nviews;
3558 if (next_view == current_view) {
3559 report("Only one view is displayed");
3560 break;
3563 current_view = next_view;
3564 /* Blur out the title of the previous view. */
3565 update_view_title(view);
3566 report_clear();
3567 break;
3569 case REQ_REFRESH:
3570 report("Refreshing is not yet supported for the %s view", view->name);
3571 break;
3573 case REQ_MAXIMIZE:
3574 if (displayed_views() == 2)
3575 maximize_view(view, TRUE);
3576 break;
3578 case REQ_OPTIONS:
3579 case REQ_TOGGLE_LINENO:
3580 case REQ_TOGGLE_DATE:
3581 case REQ_TOGGLE_AUTHOR:
3582 case REQ_TOGGLE_FILENAME:
3583 case REQ_TOGGLE_GRAPHIC:
3584 case REQ_TOGGLE_REV_GRAPH:
3585 case REQ_TOGGLE_REFS:
3586 case REQ_TOGGLE_CHANGES:
3587 case REQ_TOGGLE_IGNORE_SPACE:
3588 case REQ_TOGGLE_ID:
3589 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3590 reload_view(view);
3591 break;
3593 case REQ_TOGGLE_SORT_FIELD:
3594 case REQ_TOGGLE_SORT_ORDER:
3595 report("Sorting is not yet supported for the %s view", view->name);
3596 break;
3598 case REQ_DIFF_CONTEXT_UP:
3599 case REQ_DIFF_CONTEXT_DOWN:
3600 report("Changing the diff context is not yet supported for the %s view", view->name);
3601 break;
3603 case REQ_SEARCH:
3604 case REQ_SEARCH_BACK:
3605 search_view(view, request);
3606 break;
3608 case REQ_FIND_NEXT:
3609 case REQ_FIND_PREV:
3610 find_next(view, request);
3611 break;
3613 case REQ_STOP_LOADING:
3614 foreach_view(view, i) {
3615 if (view->pipe)
3616 report("Stopped loading the %s view", view->name),
3617 end_update(view, TRUE);
3619 break;
3621 case REQ_SHOW_VERSION:
3622 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3623 return TRUE;
3625 case REQ_SCREEN_REDRAW:
3626 redraw_display(TRUE);
3627 break;
3629 case REQ_EDIT:
3630 report("Nothing to edit");
3631 break;
3633 case REQ_ENTER:
3634 report("Nothing to enter");
3635 break;
3637 case REQ_VIEW_CLOSE:
3638 /* XXX: Mark closed views by letting view->prev point to the
3639 * view itself. Parents to closed view should never be
3640 * followed. */
3641 if (view->prev && view->prev != view) {
3642 maximize_view(view->prev, TRUE);
3643 view->prev = view;
3644 break;
3646 /* Fall-through */
3647 case REQ_QUIT:
3648 return FALSE;
3650 default:
3651 report("Unknown key, press %s for help",
3652 get_view_key(view, REQ_VIEW_HELP));
3653 return TRUE;
3656 return TRUE;
3661 * View backend utilities
3664 enum sort_field {
3665 ORDERBY_NAME,
3666 ORDERBY_DATE,
3667 ORDERBY_AUTHOR,
3670 struct sort_state {
3671 const enum sort_field *fields;
3672 size_t size, current;
3673 bool reverse;
3676 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3677 #define get_sort_field(state) ((state).fields[(state).current])
3678 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3680 static void
3681 sort_view(struct view *view, enum request request, struct sort_state *state,
3682 int (*compare)(const void *, const void *))
3684 switch (request) {
3685 case REQ_TOGGLE_SORT_FIELD:
3686 state->current = (state->current + 1) % state->size;
3687 break;
3689 case REQ_TOGGLE_SORT_ORDER:
3690 state->reverse = !state->reverse;
3691 break;
3692 default:
3693 die("Not a sort request");
3696 qsort(view->line, view->lines, sizeof(*view->line), compare);
3697 redraw_view(view);
3700 static bool
3701 update_diff_context(enum request request)
3703 int diff_context = opt_diff_context;
3705 switch (request) {
3706 case REQ_DIFF_CONTEXT_UP:
3707 opt_diff_context += 1;
3708 update_diff_context_arg(opt_diff_context);
3709 break;
3711 case REQ_DIFF_CONTEXT_DOWN:
3712 if (opt_diff_context == 0) {
3713 report("Diff context cannot be less than zero");
3714 break;
3716 opt_diff_context -= 1;
3717 update_diff_context_arg(opt_diff_context);
3718 break;
3720 default:
3721 die("Not a diff context request");
3724 return diff_context != opt_diff_context;
3727 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3729 /* Small author cache to reduce memory consumption. It uses binary
3730 * search to lookup or find place to position new entries. No entries
3731 * are ever freed. */
3732 static const char *
3733 get_author(const char *name)
3735 static const char **authors;
3736 static size_t authors_size;
3737 int from = 0, to = authors_size - 1;
3739 while (from <= to) {
3740 size_t pos = (to + from) / 2;
3741 int cmp = strcmp(name, authors[pos]);
3743 if (!cmp)
3744 return authors[pos];
3746 if (cmp < 0)
3747 to = pos - 1;
3748 else
3749 from = pos + 1;
3752 if (!realloc_authors(&authors, authors_size, 1))
3753 return NULL;
3754 name = strdup(name);
3755 if (!name)
3756 return NULL;
3758 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3759 authors[from] = name;
3760 authors_size++;
3762 return name;
3765 static void
3766 parse_timesec(struct time *time, const char *sec)
3768 time->sec = (time_t) atol(sec);
3771 static void
3772 parse_timezone(struct time *time, const char *zone)
3774 long tz;
3776 tz = ('0' - zone[1]) * 60 * 60 * 10;
3777 tz += ('0' - zone[2]) * 60 * 60;
3778 tz += ('0' - zone[3]) * 60 * 10;
3779 tz += ('0' - zone[4]) * 60;
3781 if (zone[0] == '-')
3782 tz = -tz;
3784 time->tz = tz;
3785 time->sec -= tz;
3788 /* Parse author lines where the name may be empty:
3789 * author <email@address.tld> 1138474660 +0100
3791 static void
3792 parse_author_line(char *ident, const char **author, struct time *time)
3794 char *nameend = strchr(ident, '<');
3795 char *emailend = strchr(ident, '>');
3797 if (nameend && emailend)
3798 *nameend = *emailend = 0;
3799 ident = chomp_string(ident);
3800 if (!*ident) {
3801 if (nameend)
3802 ident = chomp_string(nameend + 1);
3803 if (!*ident)
3804 ident = "Unknown";
3807 *author = get_author(ident);
3809 /* Parse epoch and timezone */
3810 if (emailend && emailend[1] == ' ') {
3811 char *secs = emailend + 2;
3812 char *zone = strchr(secs, ' ');
3814 parse_timesec(time, secs);
3816 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3817 parse_timezone(time, zone + 1);
3821 static struct line *
3822 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3824 for (; view_has_line(view, line); line += direction)
3825 if (line->type == type)
3826 return line;
3828 return NULL;
3831 #define find_prev_line_by_type(view, line, type) \
3832 find_line_by_type(view, line, type, -1)
3834 #define find_next_line_by_type(view, line, type) \
3835 find_line_by_type(view, line, type, 1)
3838 * Blame
3841 struct blame_commit {
3842 char id[SIZEOF_REV]; /* SHA1 ID. */
3843 char title[128]; /* First line of the commit message. */
3844 const char *author; /* Author of the commit. */
3845 struct time time; /* Date from the author ident. */
3846 char filename[128]; /* Name of file. */
3847 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3848 char parent_filename[128]; /* Parent/previous name of file. */
3851 struct blame_header {
3852 char id[SIZEOF_REV]; /* SHA1 ID. */
3853 size_t orig_lineno;
3854 size_t lineno;
3855 size_t group;
3858 static bool
3859 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3861 const char *pos = *posref;
3863 *posref = NULL;
3864 pos = strchr(pos + 1, ' ');
3865 if (!pos || !isdigit(pos[1]))
3866 return FALSE;
3867 *number = atoi(pos + 1);
3868 if (*number < min || *number > max)
3869 return FALSE;
3871 *posref = pos;
3872 return TRUE;
3875 static bool
3876 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3878 const char *pos = text + SIZEOF_REV - 2;
3880 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3881 return FALSE;
3883 string_ncopy(header->id, text, SIZEOF_REV);
3885 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3886 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3887 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3888 return FALSE;
3890 return TRUE;
3893 static bool
3894 match_blame_header(const char *name, char **line)
3896 size_t namelen = strlen(name);
3897 bool matched = !strncmp(name, *line, namelen);
3899 if (matched)
3900 *line += namelen;
3902 return matched;
3905 static bool
3906 parse_blame_info(struct blame_commit *commit, char *line)
3908 if (match_blame_header("author ", &line)) {
3909 commit->author = get_author(line);
3911 } else if (match_blame_header("author-time ", &line)) {
3912 parse_timesec(&commit->time, line);
3914 } else if (match_blame_header("author-tz ", &line)) {
3915 parse_timezone(&commit->time, line);
3917 } else if (match_blame_header("summary ", &line)) {
3918 string_ncopy(commit->title, line, strlen(line));
3920 } else if (match_blame_header("previous ", &line)) {
3921 if (strlen(line) <= SIZEOF_REV)
3922 return FALSE;
3923 string_copy_rev(commit->parent_id, line);
3924 line += SIZEOF_REV;
3925 string_ncopy(commit->parent_filename, line, strlen(line));
3927 } else if (match_blame_header("filename ", &line)) {
3928 string_ncopy(commit->filename, line, strlen(line));
3929 return TRUE;
3932 return FALSE;
3936 * Pager backend
3939 static bool
3940 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3942 if (draw_lineno(view, lineno))
3943 return TRUE;
3945 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
3946 return TRUE;
3948 draw_text(view, line->type, line->data);
3949 return TRUE;
3952 static bool
3953 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3955 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3956 char ref[SIZEOF_STR];
3958 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3959 return TRUE;
3961 /* This is the only fatal call, since it can "corrupt" the buffer. */
3962 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3963 return FALSE;
3965 return TRUE;
3968 static void
3969 add_pager_refs(struct view *view, const char *commit_id)
3971 char buf[SIZEOF_STR];
3972 struct ref_list *list;
3973 size_t bufpos = 0, i;
3974 const char *sep = "Refs: ";
3975 bool is_tag = FALSE;
3977 list = get_ref_list(commit_id);
3978 if (!list) {
3979 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3980 goto try_add_describe_ref;
3981 return;
3984 for (i = 0; i < list->size; i++) {
3985 struct ref *ref = list->refs[i];
3986 const char *fmt = ref->tag ? "%s[%s]" :
3987 ref->remote ? "%s<%s>" : "%s%s";
3989 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3990 return;
3991 sep = ", ";
3992 if (ref->tag)
3993 is_tag = TRUE;
3996 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3997 try_add_describe_ref:
3998 /* Add <tag>-g<commit_id> "fake" reference. */
3999 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4000 return;
4003 if (bufpos == 0)
4004 return;
4006 add_line_text(view, buf, LINE_PP_REFS);
4009 static struct line *
4010 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4012 size_t first_line = 0;
4013 bool has_first_line = FALSE;
4014 size_t datalen = strlen(data);
4015 size_t lineno = 0;
4017 while (datalen > 0 || !has_first_line) {
4018 bool wrapped = !!first_line;
4019 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4020 struct line *line;
4021 char *text;
4023 line = add_line(view, NULL, type, linelen + 1, wrapped);
4024 if (!line)
4025 break;
4026 if (!has_first_line) {
4027 first_line = view->lines - 1;
4028 has_first_line = TRUE;
4031 if (!wrapped)
4032 lineno = line->lineno;
4034 line->wrapped = wrapped;
4035 line->lineno = lineno;
4036 text = line->data;
4037 if (linelen)
4038 strncpy(text, data, linelen);
4039 text[linelen] = 0;
4041 datalen -= linelen;
4042 data += linelen;
4045 return has_first_line ? &view->line[first_line] : NULL;
4048 static bool
4049 pager_common_read(struct view *view, const char *data, enum line_type type)
4051 struct line *line;
4053 if (!data)
4054 return TRUE;
4056 if (opt_wrap_lines) {
4057 line = pager_wrap_line(view, data, type);
4058 } else {
4059 line = add_line_text(view, data, type);
4062 if (!line)
4063 return FALSE;
4065 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4066 add_pager_refs(view, data + STRING_SIZE("commit "));
4068 return TRUE;
4071 static bool
4072 pager_read(struct view *view, char *data)
4074 if (!data)
4075 return TRUE;
4077 return pager_common_read(view, data, get_line_type(data));
4080 static enum request
4081 pager_request(struct view *view, enum request request, struct line *line)
4083 int split = 0;
4085 if (request != REQ_ENTER)
4086 return request;
4088 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4089 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4090 split = 1;
4093 /* Always scroll the view even if it was split. That way
4094 * you can use Enter to scroll through the log view and
4095 * split open each commit diff. */
4096 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4098 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4099 * but if we are scrolling a non-current view this won't properly
4100 * update the view title. */
4101 if (split)
4102 update_view_title(view);
4104 return REQ_NONE;
4107 static bool
4108 pager_grep(struct view *view, struct line *line)
4110 const char *text[] = { line->data, NULL };
4112 return grep_text(view, text);
4115 static void
4116 pager_select(struct view *view, struct line *line)
4118 if (line->type == LINE_COMMIT) {
4119 char *text = (char *)line->data + STRING_SIZE("commit ");
4121 if (!view_has_flags(view, VIEW_NO_REF))
4122 string_copy_rev(view->ref, text);
4123 string_copy_rev(ref_commit, text);
4127 static bool
4128 pager_open(struct view *view, enum open_flags flags)
4130 if (display[0] == NULL) {
4131 if (!io_open(&view->io, "%s", ""))
4132 die("Failed to open stdin");
4133 flags = OPEN_PREPARED;
4135 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4136 report("No pager content, press %s to run command from prompt",
4137 get_view_key(view, REQ_PROMPT));
4138 return FALSE;
4141 return begin_update(view, NULL, NULL, flags);
4144 static struct view_ops pager_ops = {
4145 "line",
4146 { "pager" },
4147 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4149 pager_open,
4150 pager_read,
4151 pager_draw,
4152 pager_request,
4153 pager_grep,
4154 pager_select,
4157 static bool
4158 log_open(struct view *view, enum open_flags flags)
4160 static const char *log_argv[] = {
4161 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4164 return begin_update(view, NULL, log_argv, flags);
4167 static enum request
4168 log_request(struct view *view, enum request request, struct line *line)
4170 switch (request) {
4171 case REQ_REFRESH:
4172 load_refs();
4173 refresh_view(view);
4174 return REQ_NONE;
4175 default:
4176 return pager_request(view, request, line);
4180 static struct view_ops log_ops = {
4181 "line",
4182 { "log" },
4183 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER,
4185 log_open,
4186 pager_read,
4187 pager_draw,
4188 log_request,
4189 pager_grep,
4190 pager_select,
4193 struct diff_state {
4194 bool reading_diff_stat;
4195 bool combined_diff;
4198 static bool
4199 diff_open(struct view *view, enum open_flags flags)
4201 static const char *diff_argv[] = {
4202 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4203 "--patch-with-stat",
4204 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4205 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4208 return begin_update(view, NULL, diff_argv, flags);
4211 static bool
4212 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4214 enum line_type type = get_line_type(data);
4216 if (!view->lines && type != LINE_COMMIT)
4217 state->reading_diff_stat = TRUE;
4219 if (state->reading_diff_stat) {
4220 size_t len = strlen(data);
4221 char *pipe = strchr(data, '|');
4222 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4223 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4224 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4226 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4227 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4228 } else {
4229 state->reading_diff_stat = FALSE;
4232 } else if (!strcmp(data, "---")) {
4233 state->reading_diff_stat = TRUE;
4236 if (type == LINE_DIFF_HEADER) {
4237 const int len = line_info[LINE_DIFF_HEADER].linelen;
4239 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4240 !strncmp(data + len, "cc ", strlen("cc ")))
4241 state->combined_diff = TRUE;
4244 /* ADD2 and DEL2 are only valid in combined diff hunks */
4245 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4246 type = LINE_DEFAULT;
4248 return pager_common_read(view, data, type);
4251 static bool
4252 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4254 struct line *marker = find_next_line_by_type(view, line, type);
4256 return marker &&
4257 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4260 static enum request
4261 diff_common_enter(struct view *view, enum request request, struct line *line)
4263 if (line->type == LINE_DIFF_STAT) {
4264 int file_number = 0;
4266 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4267 file_number++;
4268 line--;
4271 for (line = view->line; view_has_line(view, line); line++) {
4272 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4273 if (!line)
4274 break;
4276 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4277 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4278 if (file_number == 1) {
4279 break;
4281 file_number--;
4285 if (!line) {
4286 report("Failed to find file diff");
4287 return REQ_NONE;
4290 select_view_line(view, line - view->line);
4291 report_clear();
4292 return REQ_NONE;
4294 } else {
4295 return pager_request(view, request, line);
4299 static bool
4300 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4302 char *sep = strchr(*text, c);
4304 if (sep != NULL) {
4305 *sep = 0;
4306 draw_text(view, *type, *text);
4307 *sep = c;
4308 *text = sep;
4309 *type = next_type;
4312 return sep != NULL;
4315 static bool
4316 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4318 char *text = line->data;
4319 enum line_type type = line->type;
4321 if (draw_lineno(view, lineno))
4322 return TRUE;
4324 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4325 return TRUE;
4327 if (type == LINE_DIFF_STAT) {
4328 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4329 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4330 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4331 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4332 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4333 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4334 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4336 } else {
4337 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4338 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4342 draw_text(view, type, text);
4343 return TRUE;
4346 static bool
4347 diff_read(struct view *view, char *data)
4349 struct diff_state *state = view->private;
4351 if (!data) {
4352 /* Fall back to retry if no diff will be shown. */
4353 if (view->lines == 0 && opt_file_argv) {
4354 int pos = argv_size(view->argv)
4355 - argv_size(opt_file_argv) - 1;
4357 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4358 for (; view->argv[pos]; pos++) {
4359 free((void *) view->argv[pos]);
4360 view->argv[pos] = NULL;
4363 if (view->pipe)
4364 io_done(view->pipe);
4365 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4366 return FALSE;
4369 return TRUE;
4372 return diff_common_read(view, data, state);
4375 static bool
4376 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4377 struct blame_header *header, struct blame_commit *commit)
4379 char line_arg[SIZEOF_STR];
4380 const char *blame_argv[] = {
4381 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4383 struct io io;
4384 bool ok = FALSE;
4385 char *buf;
4387 if (!string_format(line_arg, "-L%ld,+1", lineno))
4388 return FALSE;
4390 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4391 return FALSE;
4393 while ((buf = io_get(&io, '\n', TRUE))) {
4394 if (header) {
4395 if (!parse_blame_header(header, buf, 9999999))
4396 break;
4397 header = NULL;
4399 } else if (parse_blame_info(commit, buf)) {
4400 ok = TRUE;
4401 break;
4405 if (io_error(&io))
4406 ok = FALSE;
4408 io_done(&io);
4409 return ok;
4412 static bool
4413 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4415 return prefixcmp(chunk, "@@ -") ||
4416 !(chunk = strchr(chunk, marker)) ||
4417 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4420 static enum request
4421 diff_trace_origin(struct view *view, struct line *line)
4423 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4424 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4425 const char *chunk_data;
4426 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4427 int lineno = 0;
4428 const char *file = NULL;
4429 char ref[SIZEOF_REF];
4430 struct blame_header header;
4431 struct blame_commit commit;
4433 if (!diff || !chunk || chunk == line) {
4434 report("The line to trace must be inside a diff chunk");
4435 return REQ_NONE;
4438 for (; diff < line && !file; diff++) {
4439 const char *data = diff->data;
4441 if (!prefixcmp(data, "--- a/")) {
4442 file = data + STRING_SIZE("--- a/");
4443 break;
4447 if (diff == line || !file) {
4448 report("Failed to read the file name");
4449 return REQ_NONE;
4452 chunk_data = chunk->data;
4454 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4455 report("Failed to read the line number");
4456 return REQ_NONE;
4459 if (lineno == 0) {
4460 report("This is the origin of the line");
4461 return REQ_NONE;
4464 for (chunk += 1; chunk < line; chunk++) {
4465 if (chunk->type == LINE_DIFF_ADD) {
4466 lineno += chunk_marker == '+';
4467 } else if (chunk->type == LINE_DIFF_DEL) {
4468 lineno += chunk_marker == '-';
4469 } else {
4470 lineno++;
4474 if (chunk_marker == '+')
4475 string_copy(ref, view->vid);
4476 else
4477 string_format(ref, "%s^", view->vid);
4479 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4480 report("Failed to read blame data");
4481 return REQ_NONE;
4484 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4485 string_copy(opt_ref, header.id);
4486 opt_goto_line = header.orig_lineno - 1;
4488 return REQ_VIEW_BLAME;
4491 static const char *
4492 diff_get_pathname(struct view *view, struct line *line)
4494 const struct line *header;
4495 const char *dst = NULL;
4496 const char *prefixes[] = { " b/", "cc ", "combined " };
4497 int i;
4499 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4500 if (!header)
4501 return NULL;
4503 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4504 dst = strstr(header->data, prefixes[i]);
4506 return dst ? dst + strlen(prefixes[--i]) : NULL;
4509 static enum request
4510 diff_request(struct view *view, enum request request, struct line *line)
4512 const char *file;
4514 switch (request) {
4515 case REQ_VIEW_BLAME:
4516 return diff_trace_origin(view, line);
4518 case REQ_DIFF_CONTEXT_UP:
4519 case REQ_DIFF_CONTEXT_DOWN:
4520 if (!update_diff_context(request))
4521 return REQ_NONE;
4522 reload_view(view);
4523 return REQ_NONE;
4525 case REQ_EDIT:
4526 file = diff_get_pathname(view, line);
4527 if (!file || access(file, R_OK))
4528 return pager_request(view, request, line);
4529 open_editor(file);
4530 return REQ_NONE;
4532 case REQ_ENTER:
4533 return diff_common_enter(view, request, line);
4535 default:
4536 return pager_request(view, request, line);
4540 static void
4541 diff_select(struct view *view, struct line *line)
4543 const char *s;
4545 if (line->type == LINE_DIFF_STAT) {
4546 s = get_view_key(view, REQ_ENTER);
4547 string_format(view->ref, "Press '%s' to jump to file diff", s);
4548 } else {
4549 s = diff_get_pathname(view, line);
4550 if (s) {
4551 string_format(view->ref, "Changes to '%s'", s);
4552 } else {
4553 string_ncopy(view->ref, view->id, strlen(view->id));
4554 pager_select(view, line);
4559 static struct view_ops diff_ops = {
4560 "line",
4561 { "diff" },
4562 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN,
4563 sizeof(struct diff_state),
4564 diff_open,
4565 diff_read,
4566 diff_common_draw,
4567 diff_request,
4568 pager_grep,
4569 diff_select,
4573 * Help backend
4576 static bool
4577 help_draw(struct view *view, struct line *line, unsigned int lineno)
4579 if (line->type == LINE_HELP_KEYMAP) {
4580 struct keymap *keymap = line->data;
4582 draw_formatted(view, line->type, "[%c] %s bindings",
4583 keymap->hidden ? '+' : '-', keymap->name);
4584 return TRUE;
4585 } else {
4586 return pager_draw(view, line, lineno);
4590 static bool
4591 help_open_keymap_title(struct view *view, struct keymap *keymap)
4593 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4594 return keymap->hidden;
4597 static void
4598 help_open_keymap(struct view *view, struct keymap *keymap)
4600 const char *group = NULL;
4601 char buf[SIZEOF_STR];
4602 bool add_title = TRUE;
4603 int i;
4605 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4606 const char *key = NULL;
4608 if (req_info[i].request == REQ_NONE)
4609 continue;
4611 if (!req_info[i].request) {
4612 group = req_info[i].help;
4613 continue;
4616 key = get_keys(keymap, req_info[i].request, TRUE);
4617 if (!key || !*key)
4618 continue;
4620 if (add_title && help_open_keymap_title(view, keymap))
4621 return;
4622 add_title = FALSE;
4624 if (group) {
4625 add_line_text(view, group, LINE_HELP_GROUP);
4626 group = NULL;
4629 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4630 enum_name(req_info[i]), req_info[i].help);
4633 group = "External commands:";
4635 for (i = 0; i < run_requests; i++) {
4636 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4637 const char *key;
4639 if (!req || req->keymap != keymap)
4640 continue;
4642 key = get_key_name(req->key);
4643 if (!*key)
4644 key = "(no key defined)";
4646 if (add_title && help_open_keymap_title(view, keymap))
4647 return;
4648 add_title = FALSE;
4650 if (group) {
4651 add_line_text(view, group, LINE_HELP_GROUP);
4652 group = NULL;
4655 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4656 return;
4658 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4662 static bool
4663 help_open(struct view *view, enum open_flags flags)
4665 struct keymap *keymap;
4667 reset_view(view);
4668 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4669 add_line_text(view, "", LINE_DEFAULT);
4671 for (keymap = keymaps; keymap; keymap = keymap->next)
4672 help_open_keymap(view, keymap);
4674 return TRUE;
4677 static enum request
4678 help_request(struct view *view, enum request request, struct line *line)
4680 switch (request) {
4681 case REQ_ENTER:
4682 if (line->type == LINE_HELP_KEYMAP) {
4683 struct keymap *keymap = line->data;
4685 keymap->hidden = !keymap->hidden;
4686 refresh_view(view);
4689 return REQ_NONE;
4690 default:
4691 return pager_request(view, request, line);
4695 static struct view_ops help_ops = {
4696 "line",
4697 { "help" },
4698 VIEW_NO_GIT_DIR,
4700 help_open,
4701 NULL,
4702 help_draw,
4703 help_request,
4704 pager_grep,
4705 pager_select,
4710 * Tree backend
4713 struct tree_stack_entry {
4714 struct tree_stack_entry *prev; /* Entry below this in the stack */
4715 unsigned long lineno; /* Line number to restore */
4716 char *name; /* Position of name in opt_path */
4719 /* The top of the path stack. */
4720 static struct tree_stack_entry *tree_stack = NULL;
4721 unsigned long tree_lineno = 0;
4723 static void
4724 pop_tree_stack_entry(void)
4726 struct tree_stack_entry *entry = tree_stack;
4728 tree_lineno = entry->lineno;
4729 entry->name[0] = 0;
4730 tree_stack = entry->prev;
4731 free(entry);
4734 static void
4735 push_tree_stack_entry(const char *name, unsigned long lineno)
4737 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4738 size_t pathlen = strlen(opt_path);
4740 if (!entry)
4741 return;
4743 entry->prev = tree_stack;
4744 entry->name = opt_path + pathlen;
4745 tree_stack = entry;
4747 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4748 pop_tree_stack_entry();
4749 return;
4752 /* Move the current line to the first tree entry. */
4753 tree_lineno = 1;
4754 entry->lineno = lineno;
4757 /* Parse output from git-ls-tree(1):
4759 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4762 #define SIZEOF_TREE_ATTR \
4763 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4765 #define SIZEOF_TREE_MODE \
4766 STRING_SIZE("100644 ")
4768 #define TREE_ID_OFFSET \
4769 STRING_SIZE("100644 blob ")
4771 #define tree_path_is_parent(path) (!strcmp("..", (path)))
4773 struct tree_entry {
4774 char id[SIZEOF_REV];
4775 char commit[SIZEOF_REV];
4776 mode_t mode;
4777 struct time time; /* Date from the author ident. */
4778 const char *author; /* Author of the commit. */
4779 char name[1];
4782 struct tree_state {
4783 char commit[SIZEOF_REV];
4784 const char *author_name;
4785 struct time author_time;
4786 bool read_date;
4789 static const char *
4790 tree_path(const struct line *line)
4792 return ((struct tree_entry *) line->data)->name;
4795 static int
4796 tree_compare_entry(const struct line *line1, const struct line *line2)
4798 if (line1->type != line2->type)
4799 return line1->type == LINE_TREE_DIR ? -1 : 1;
4800 return strcmp(tree_path(line1), tree_path(line2));
4803 static const enum sort_field tree_sort_fields[] = {
4804 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4806 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4808 static int
4809 tree_compare(const void *l1, const void *l2)
4811 const struct line *line1 = (const struct line *) l1;
4812 const struct line *line2 = (const struct line *) l2;
4813 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4814 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4816 if (line1->type == LINE_TREE_HEAD)
4817 return -1;
4818 if (line2->type == LINE_TREE_HEAD)
4819 return 1;
4821 switch (get_sort_field(tree_sort_state)) {
4822 case ORDERBY_DATE:
4823 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4825 case ORDERBY_AUTHOR:
4826 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4828 case ORDERBY_NAME:
4829 default:
4830 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4835 static struct line *
4836 tree_entry(struct view *view, enum line_type type, const char *path,
4837 const char *mode, const char *id)
4839 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
4840 struct tree_entry *entry;
4841 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
4843 if (!line)
4844 return NULL;
4846 strncpy(entry->name, path, strlen(path));
4847 if (mode)
4848 entry->mode = strtoul(mode, NULL, 8);
4849 if (id)
4850 string_copy_rev(entry->id, id);
4852 return line;
4855 static bool
4856 tree_read_date(struct view *view, char *text, struct tree_state *state)
4858 if (!text && state->read_date) {
4859 state->read_date = FALSE;
4860 return TRUE;
4862 } else if (!text) {
4863 /* Find next entry to process */
4864 const char *log_file[] = {
4865 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
4866 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4869 if (!view->lines) {
4870 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4871 report("Tree is empty");
4872 return TRUE;
4875 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4876 report("Failed to load tree data");
4877 return TRUE;
4880 state->read_date = TRUE;
4881 return FALSE;
4883 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
4884 string_copy_rev(state->commit, text + STRING_SIZE("commit "));
4886 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4887 parse_author_line(text + STRING_SIZE("author "),
4888 &state->author_name, &state->author_time);
4890 } else if (*text == ':') {
4891 char *pos;
4892 size_t annotated = 1;
4893 size_t i;
4895 pos = strchr(text, '\t');
4896 if (!pos)
4897 return TRUE;
4898 text = pos + 1;
4899 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4900 text += strlen(opt_path);
4901 pos = strchr(text, '/');
4902 if (pos)
4903 *pos = 0;
4905 for (i = 1; i < view->lines; i++) {
4906 struct line *line = &view->line[i];
4907 struct tree_entry *entry = line->data;
4909 annotated += !!entry->author;
4910 if (entry->author || strcmp(entry->name, text))
4911 continue;
4913 string_copy_rev(entry->commit, state->commit);
4914 entry->author = state->author_name;
4915 entry->time = state->author_time;
4916 line->dirty = 1;
4917 break;
4920 if (annotated == view->lines)
4921 io_kill(view->pipe);
4923 return TRUE;
4926 static bool
4927 tree_read(struct view *view, char *text)
4929 struct tree_state *state = view->private;
4930 struct tree_entry *data;
4931 struct line *entry, *line;
4932 enum line_type type;
4933 size_t textlen = text ? strlen(text) : 0;
4934 char *path = text + SIZEOF_TREE_ATTR;
4936 if (state->read_date || !text)
4937 return tree_read_date(view, text, state);
4939 if (textlen <= SIZEOF_TREE_ATTR)
4940 return FALSE;
4941 if (view->lines == 0 &&
4942 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4943 return FALSE;
4945 /* Strip the path part ... */
4946 if (*opt_path) {
4947 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4948 size_t striplen = strlen(opt_path);
4950 if (pathlen > striplen)
4951 memmove(path, path + striplen,
4952 pathlen - striplen + 1);
4954 /* Insert "link" to parent directory. */
4955 if (view->lines == 1 &&
4956 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4957 return FALSE;
4960 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4961 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4962 if (!entry)
4963 return FALSE;
4964 data = entry->data;
4966 /* Skip "Directory ..." and ".." line. */
4967 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4968 if (tree_compare_entry(line, entry) <= 0)
4969 continue;
4971 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4973 line->data = data;
4974 line->type = type;
4975 for (; line <= entry; line++)
4976 line->dirty = line->cleareol = 1;
4977 return TRUE;
4980 if (tree_lineno <= view->pos.lineno)
4981 tree_lineno = view->custom_lines;
4983 if (tree_lineno > view->pos.lineno) {
4984 view->pos.lineno = tree_lineno;
4985 tree_lineno = 0;
4988 return TRUE;
4991 static bool
4992 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4994 struct tree_entry *entry = line->data;
4996 if (line->type == LINE_TREE_HEAD) {
4997 if (draw_text(view, line->type, "Directory path /"))
4998 return TRUE;
4999 } else {
5000 if (draw_mode(view, entry->mode))
5001 return TRUE;
5003 if (draw_author(view, entry->author))
5004 return TRUE;
5006 if (draw_date(view, &entry->time))
5007 return TRUE;
5009 if (opt_show_id && draw_id(view, LINE_ID, entry->commit))
5010 return TRUE;
5013 draw_text(view, line->type, entry->name);
5014 return TRUE;
5017 static void
5018 open_blob_editor(const char *id)
5020 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5021 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
5022 int fd = mkstemp(file);
5024 if (fd == -1)
5025 report("Failed to create temporary file");
5026 else if (!io_run_append(blob_argv, fd))
5027 report("Failed to save blob data to file");
5028 else
5029 open_editor(file);
5030 if (fd != -1)
5031 unlink(file);
5034 static enum request
5035 tree_request(struct view *view, enum request request, struct line *line)
5037 enum open_flags flags;
5038 struct tree_entry *entry = line->data;
5040 switch (request) {
5041 case REQ_VIEW_BLAME:
5042 if (line->type != LINE_TREE_FILE) {
5043 report("Blame only supported for files");
5044 return REQ_NONE;
5047 string_copy(opt_ref, view->vid);
5048 return request;
5050 case REQ_EDIT:
5051 if (line->type != LINE_TREE_FILE) {
5052 report("Edit only supported for files");
5053 } else if (!is_head_commit(view->vid)) {
5054 open_blob_editor(entry->id);
5055 } else {
5056 open_editor(opt_file);
5058 return REQ_NONE;
5060 case REQ_TOGGLE_SORT_FIELD:
5061 case REQ_TOGGLE_SORT_ORDER:
5062 sort_view(view, request, &tree_sort_state, tree_compare);
5063 return REQ_NONE;
5065 case REQ_PARENT:
5066 if (!*opt_path) {
5067 /* quit view if at top of tree */
5068 return REQ_VIEW_CLOSE;
5070 /* fake 'cd ..' */
5071 line = &view->line[1];
5072 break;
5074 case REQ_ENTER:
5075 break;
5077 default:
5078 return request;
5081 /* Cleanup the stack if the tree view is at a different tree. */
5082 while (!*opt_path && tree_stack)
5083 pop_tree_stack_entry();
5085 switch (line->type) {
5086 case LINE_TREE_DIR:
5087 /* Depending on whether it is a subdirectory or parent link
5088 * mangle the path buffer. */
5089 if (line == &view->line[1] && *opt_path) {
5090 pop_tree_stack_entry();
5092 } else {
5093 const char *basename = tree_path(line);
5095 push_tree_stack_entry(basename, view->pos.lineno);
5098 /* Trees and subtrees share the same ID, so they are not not
5099 * unique like blobs. */
5100 flags = OPEN_RELOAD;
5101 request = REQ_VIEW_TREE;
5102 break;
5104 case LINE_TREE_FILE:
5105 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5106 request = REQ_VIEW_BLOB;
5107 break;
5109 default:
5110 return REQ_NONE;
5113 open_view(view, request, flags);
5114 if (request == REQ_VIEW_TREE)
5115 view->pos.lineno = tree_lineno;
5117 return REQ_NONE;
5120 static bool
5121 tree_grep(struct view *view, struct line *line)
5123 struct tree_entry *entry = line->data;
5124 const char *text[] = {
5125 entry->name,
5126 mkauthor(entry->author, opt_author_width, opt_author),
5127 mkdate(&entry->time, opt_date),
5128 NULL
5131 return grep_text(view, text);
5134 static void
5135 tree_select(struct view *view, struct line *line)
5137 struct tree_entry *entry = line->data;
5139 if (line->type == LINE_TREE_HEAD) {
5140 string_format(view->ref, "Files in /%s", opt_path);
5141 return;
5144 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5145 string_copy(view->ref, "Open parent directory");
5146 return;
5149 if (line->type == LINE_TREE_FILE) {
5150 string_copy_rev(ref_blob, entry->id);
5151 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5154 string_copy_rev(view->ref, entry->id);
5157 static bool
5158 tree_open(struct view *view, enum open_flags flags)
5160 static const char *tree_argv[] = {
5161 "git", "ls-tree", "%(commit)", "%(directory)", NULL
5164 if (string_rev_is_null(ref_commit)) {
5165 report("No tree exists for this commit");
5166 return FALSE;
5169 if (view->lines == 0 && opt_prefix[0]) {
5170 char *pos = opt_prefix;
5172 while (pos && *pos) {
5173 char *end = strchr(pos, '/');
5175 if (end)
5176 *end = 0;
5177 push_tree_stack_entry(pos, 0);
5178 pos = end;
5179 if (end) {
5180 *end = '/';
5181 pos++;
5185 } else if (strcmp(view->vid, view->id)) {
5186 opt_path[0] = 0;
5189 return begin_update(view, opt_cdup, tree_argv, flags);
5192 static struct view_ops tree_ops = {
5193 "file",
5194 { "tree" },
5195 VIEW_SEND_CHILD_ENTER,
5196 sizeof(struct tree_state),
5197 tree_open,
5198 tree_read,
5199 tree_draw,
5200 tree_request,
5201 tree_grep,
5202 tree_select,
5205 static bool
5206 blob_open(struct view *view, enum open_flags flags)
5208 static const char *blob_argv[] = {
5209 "git", "cat-file", "blob", "%(blob)", NULL
5212 if (!ref_blob[0]) {
5213 report("No file chosen, press %s to open tree view",
5214 get_view_key(view, REQ_VIEW_TREE));
5215 return FALSE;
5218 view->encoding = get_path_encoding(opt_file, opt_encoding);
5220 return begin_update(view, NULL, blob_argv, flags);
5223 static bool
5224 blob_read(struct view *view, char *line)
5226 if (!line)
5227 return TRUE;
5228 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5231 static enum request
5232 blob_request(struct view *view, enum request request, struct line *line)
5234 switch (request) {
5235 case REQ_EDIT:
5236 open_blob_editor(view->vid);
5237 return REQ_NONE;
5238 default:
5239 return pager_request(view, request, line);
5243 static struct view_ops blob_ops = {
5244 "line",
5245 { "blob" },
5246 VIEW_NO_FLAGS,
5248 blob_open,
5249 blob_read,
5250 pager_draw,
5251 blob_request,
5252 pager_grep,
5253 pager_select,
5257 * Blame backend
5259 * Loading the blame view is a two phase job:
5261 * 1. File content is read either using opt_file from the
5262 * filesystem or using git-cat-file.
5263 * 2. Then blame information is incrementally added by
5264 * reading output from git-blame.
5267 struct blame {
5268 struct blame_commit *commit;
5269 unsigned long lineno;
5270 char text[1];
5273 struct blame_state {
5274 struct blame_commit *commit;
5275 int blamed;
5276 bool done_reading;
5277 bool auto_filename_display;
5280 static bool
5281 blame_detect_filename_display(struct view *view)
5283 bool show_filenames = FALSE;
5284 const char *filename = NULL;
5285 int i;
5287 if (opt_blame_argv) {
5288 for (i = 0; opt_blame_argv[i]; i++) {
5289 if (prefixcmp(opt_blame_argv[i], "-C"))
5290 continue;
5292 show_filenames = TRUE;
5296 for (i = 0; i < view->lines; i++) {
5297 struct blame *blame = view->line[i].data;
5299 if (blame->commit && blame->commit->id[0]) {
5300 if (!filename)
5301 filename = blame->commit->filename;
5302 else if (strcmp(filename, blame->commit->filename))
5303 show_filenames = TRUE;
5307 return show_filenames;
5310 static bool
5311 blame_open(struct view *view, enum open_flags flags)
5313 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5314 char path[SIZEOF_STR];
5315 size_t i;
5317 if (!opt_file[0]) {
5318 report("No file chosen, press %s to open tree view",
5319 get_view_key(view, REQ_VIEW_TREE));
5320 return FALSE;
5323 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5324 string_copy(path, opt_file);
5325 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5326 report("Failed to setup the blame view");
5327 return FALSE;
5331 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5332 const char *blame_cat_file_argv[] = {
5333 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5336 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5337 return FALSE;
5340 /* First pass: remove multiple references to the same commit. */
5341 for (i = 0; i < view->lines; i++) {
5342 struct blame *blame = view->line[i].data;
5344 if (blame->commit && blame->commit->id[0])
5345 blame->commit->id[0] = 0;
5346 else
5347 blame->commit = NULL;
5350 /* Second pass: free existing references. */
5351 for (i = 0; i < view->lines; i++) {
5352 struct blame *blame = view->line[i].data;
5354 if (blame->commit)
5355 free(blame->commit);
5358 string_format(view->vid, "%s", opt_file);
5359 string_format(view->ref, "%s ...", opt_file);
5361 return TRUE;
5364 static struct blame_commit *
5365 get_blame_commit(struct view *view, const char *id)
5367 size_t i;
5369 for (i = 0; i < view->lines; i++) {
5370 struct blame *blame = view->line[i].data;
5372 if (!blame->commit)
5373 continue;
5375 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5376 return blame->commit;
5380 struct blame_commit *commit = calloc(1, sizeof(*commit));
5382 if (commit)
5383 string_ncopy(commit->id, id, SIZEOF_REV);
5384 return commit;
5388 static struct blame_commit *
5389 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5391 struct blame_header header;
5392 struct blame_commit *commit;
5393 struct blame *blame;
5395 if (!parse_blame_header(&header, text, view->lines))
5396 return NULL;
5398 commit = get_blame_commit(view, text);
5399 if (!commit)
5400 return NULL;
5402 state->blamed += header.group;
5403 while (header.group--) {
5404 struct line *line = &view->line[header.lineno + header.group - 1];
5406 blame = line->data;
5407 blame->commit = commit;
5408 blame->lineno = header.orig_lineno + header.group - 1;
5409 line->dirty = 1;
5412 return commit;
5415 static bool
5416 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5418 if (!text) {
5419 const char *blame_argv[] = {
5420 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5421 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5424 if (view->lines == 0 && !view->prev)
5425 die("No blame exist for %s", view->vid);
5427 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5428 report("Failed to load blame data");
5429 return TRUE;
5432 if (opt_goto_line > 0) {
5433 select_view_line(view, opt_goto_line);
5434 opt_goto_line = 0;
5437 state->done_reading = TRUE;
5438 return FALSE;
5440 } else {
5441 size_t textlen = strlen(text);
5442 struct blame *blame;
5444 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5445 return FALSE;
5447 blame->commit = NULL;
5448 strncpy(blame->text, text, textlen);
5449 blame->text[textlen] = 0;
5450 return TRUE;
5454 static bool
5455 blame_read(struct view *view, char *line)
5457 struct blame_state *state = view->private;
5459 if (!state->done_reading)
5460 return blame_read_file(view, line, state);
5462 if (!line) {
5463 state->auto_filename_display = blame_detect_filename_display(view);
5464 string_format(view->ref, "%s", view->vid);
5465 if (view_is_displayed(view)) {
5466 update_view_title(view);
5467 redraw_view_from(view, 0);
5469 return TRUE;
5472 if (!state->commit) {
5473 state->commit = read_blame_commit(view, line, state);
5474 string_format(view->ref, "%s %2zd%%", view->vid,
5475 view->lines ? state->blamed * 100 / view->lines : 0);
5477 } else if (parse_blame_info(state->commit, line)) {
5478 state->commit = NULL;
5481 return TRUE;
5484 static bool
5485 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5487 struct blame_state *state = view->private;
5488 struct blame *blame = line->data;
5489 struct time *time = NULL;
5490 const char *id = NULL, *author = NULL, *filename = NULL;
5491 enum line_type id_type = LINE_ID;
5492 static const enum line_type blame_colors[] = {
5493 LINE_PALETTE_0,
5494 LINE_PALETTE_1,
5495 LINE_PALETTE_2,
5496 LINE_PALETTE_3,
5497 LINE_PALETTE_4,
5498 LINE_PALETTE_5,
5499 LINE_PALETTE_6,
5502 #define BLAME_COLOR(i) \
5503 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5505 if (blame->commit && *blame->commit->filename) {
5506 id = blame->commit->id;
5507 author = blame->commit->author;
5508 filename = blame->commit->filename;
5509 time = &blame->commit->time;
5510 id_type = BLAME_COLOR((long) blame->commit);
5513 if (draw_date(view, time))
5514 return TRUE;
5516 if (draw_author(view, author))
5517 return TRUE;
5519 if (draw_filename(view, filename, state->auto_filename_display))
5520 return TRUE;
5522 if (draw_id(view, id_type, id))
5523 return TRUE;
5525 if (draw_lineno(view, lineno))
5526 return TRUE;
5528 draw_text(view, LINE_DEFAULT, blame->text);
5529 return TRUE;
5532 static bool
5533 check_blame_commit(struct blame *blame, bool check_null_id)
5535 if (!blame->commit)
5536 report("Commit data not loaded yet");
5537 else if (check_null_id && string_rev_is_null(blame->commit->id))
5538 report("No commit exist for the selected line");
5539 else
5540 return TRUE;
5541 return FALSE;
5544 static void
5545 setup_blame_parent_line(struct view *view, struct blame *blame)
5547 char from[SIZEOF_REF + SIZEOF_STR];
5548 char to[SIZEOF_REF + SIZEOF_STR];
5549 const char *diff_tree_argv[] = {
5550 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
5551 "--no-color", "-U0", from, to, "--", NULL
5553 struct io io;
5554 int parent_lineno = -1;
5555 int blamed_lineno = -1;
5556 char *line;
5558 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5559 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5560 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5561 return;
5563 while ((line = io_get(&io, '\n', TRUE))) {
5564 if (*line == '@') {
5565 char *pos = strchr(line, '+');
5567 parent_lineno = atoi(line + 4);
5568 if (pos)
5569 blamed_lineno = atoi(pos + 1);
5571 } else if (*line == '+' && parent_lineno != -1) {
5572 if (blame->lineno == blamed_lineno - 1 &&
5573 !strcmp(blame->text, line + 1)) {
5574 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5575 break;
5577 blamed_lineno++;
5581 io_done(&io);
5584 static enum request
5585 blame_request(struct view *view, enum request request, struct line *line)
5587 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5588 struct blame *blame = line->data;
5590 switch (request) {
5591 case REQ_VIEW_BLAME:
5592 if (check_blame_commit(blame, TRUE)) {
5593 string_copy(opt_ref, blame->commit->id);
5594 string_copy(opt_file, blame->commit->filename);
5595 if (blame->lineno)
5596 view->pos.lineno = blame->lineno;
5597 reload_view(view);
5599 break;
5601 case REQ_PARENT:
5602 if (!check_blame_commit(blame, TRUE))
5603 break;
5604 if (!*blame->commit->parent_id) {
5605 report("The selected commit has no parents");
5606 } else {
5607 string_copy_rev(opt_ref, blame->commit->parent_id);
5608 string_copy(opt_file, blame->commit->parent_filename);
5609 setup_blame_parent_line(view, blame);
5610 opt_goto_line = blame->lineno;
5611 reload_view(view);
5613 break;
5615 case REQ_ENTER:
5616 if (!check_blame_commit(blame, FALSE))
5617 break;
5619 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5620 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5621 break;
5623 if (string_rev_is_null(blame->commit->id)) {
5624 struct view *diff = VIEW(REQ_VIEW_DIFF);
5625 const char *diff_parent_argv[] = {
5626 GIT_DIFF_BLAME(opt_encoding_arg,
5627 opt_diff_context_arg,
5628 opt_ignore_space_arg, view->vid)
5630 const char *diff_no_parent_argv[] = {
5631 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
5632 opt_diff_context_arg,
5633 opt_ignore_space_arg, view->vid)
5635 const char **diff_index_argv = *blame->commit->parent_id
5636 ? diff_parent_argv : diff_no_parent_argv;
5638 open_argv(view, diff, diff_index_argv, NULL, flags);
5639 if (diff->pipe)
5640 string_copy_rev(diff->ref, NULL_ID);
5641 } else {
5642 open_view(view, REQ_VIEW_DIFF, flags);
5644 break;
5646 default:
5647 return request;
5650 return REQ_NONE;
5653 static bool
5654 blame_grep(struct view *view, struct line *line)
5656 struct blame *blame = line->data;
5657 struct blame_commit *commit = blame->commit;
5658 const char *text[] = {
5659 blame->text,
5660 commit ? commit->title : "",
5661 commit ? commit->id : "",
5662 commit && opt_author ? commit->author : "",
5663 commit ? mkdate(&commit->time, opt_date) : "",
5664 NULL
5667 return grep_text(view, text);
5670 static void
5671 blame_select(struct view *view, struct line *line)
5673 struct blame *blame = line->data;
5674 struct blame_commit *commit = blame->commit;
5676 if (!commit)
5677 return;
5679 if (string_rev_is_null(commit->id))
5680 string_ncopy(ref_commit, "HEAD", 4);
5681 else
5682 string_copy_rev(ref_commit, commit->id);
5685 static struct view_ops blame_ops = {
5686 "line",
5687 { "blame" },
5688 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
5689 sizeof(struct blame_state),
5690 blame_open,
5691 blame_read,
5692 blame_draw,
5693 blame_request,
5694 blame_grep,
5695 blame_select,
5699 * Branch backend
5702 struct branch {
5703 const char *author; /* Author of the last commit. */
5704 struct time time; /* Date of the last activity. */
5705 char title[128]; /* First line of the commit message. */
5706 const struct ref *ref; /* Name and commit ID information. */
5709 static const struct ref branch_all;
5710 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5712 static const enum sort_field branch_sort_fields[] = {
5713 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5715 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5717 struct branch_state {
5718 char id[SIZEOF_REV];
5719 size_t max_ref_length;
5722 static int
5723 branch_compare(const void *l1, const void *l2)
5725 const struct branch *branch1 = ((const struct line *) l1)->data;
5726 const struct branch *branch2 = ((const struct line *) l2)->data;
5728 if (branch_is_all(branch1))
5729 return -1;
5730 else if (branch_is_all(branch2))
5731 return 1;
5733 switch (get_sort_field(branch_sort_state)) {
5734 case ORDERBY_DATE:
5735 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5737 case ORDERBY_AUTHOR:
5738 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5740 case ORDERBY_NAME:
5741 default:
5742 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5746 static bool
5747 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5749 struct branch_state *state = view->private;
5750 struct branch *branch = line->data;
5751 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5752 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5754 if (draw_date(view, &branch->time))
5755 return TRUE;
5757 if (draw_author(view, branch->author))
5758 return TRUE;
5760 if (draw_field(view, type, branch_name, state->max_ref_length, FALSE))
5761 return TRUE;
5763 if (opt_show_id && draw_id(view, LINE_ID, branch->ref->id))
5764 return TRUE;
5766 draw_text(view, LINE_DEFAULT, branch->title);
5767 return TRUE;
5770 static enum request
5771 branch_request(struct view *view, enum request request, struct line *line)
5773 struct branch *branch = line->data;
5775 switch (request) {
5776 case REQ_REFRESH:
5777 load_refs();
5778 refresh_view(view);
5779 return REQ_NONE;
5781 case REQ_TOGGLE_SORT_FIELD:
5782 case REQ_TOGGLE_SORT_ORDER:
5783 sort_view(view, request, &branch_sort_state, branch_compare);
5784 return REQ_NONE;
5786 case REQ_ENTER:
5788 const struct ref *ref = branch->ref;
5789 const char *all_branches_argv[] = {
5790 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
5792 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5794 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5795 return REQ_NONE;
5797 case REQ_JUMP_COMMIT:
5799 int lineno;
5801 for (lineno = 0; lineno < view->lines; lineno++) {
5802 struct branch *branch = view->line[lineno].data;
5804 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5805 select_view_line(view, lineno);
5806 report_clear();
5807 return REQ_NONE;
5811 default:
5812 return request;
5816 static bool
5817 branch_read(struct view *view, char *line)
5819 struct branch_state *state = view->private;
5820 const char *title = NULL;
5821 const char *author = NULL;
5822 struct time time = {};
5823 size_t i;
5825 if (!line)
5826 return TRUE;
5828 switch (get_line_type(line)) {
5829 case LINE_COMMIT:
5830 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5831 return TRUE;
5833 case LINE_AUTHOR:
5834 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5836 default:
5837 title = line + STRING_SIZE("title ");
5840 for (i = 0; i < view->lines; i++) {
5841 struct branch *branch = view->line[i].data;
5843 if (strcmp(branch->ref->id, state->id))
5844 continue;
5846 if (author) {
5847 branch->author = author;
5848 branch->time = time;
5851 if (title)
5852 string_expand(branch->title, sizeof(branch->title), title, 1);
5854 view->line[i].dirty = TRUE;
5857 return TRUE;
5860 static bool
5861 branch_open_visitor(void *data, const struct ref *ref)
5863 struct view *view = data;
5864 struct branch_state *state = view->private;
5865 struct branch *branch;
5866 size_t ref_length;
5868 if (ref->tag || ref->ltag)
5869 return TRUE;
5871 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, ref == &branch_all))
5872 return FALSE;
5874 ref_length = strlen(ref->name);
5875 if (ref_length > state->max_ref_length)
5876 state->max_ref_length = ref_length;
5878 branch->ref = ref;
5879 return TRUE;
5882 static bool
5883 branch_open(struct view *view, enum open_flags flags)
5885 const char *branch_log[] = {
5886 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
5887 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5888 "--all", "--simplify-by-decoration", NULL
5891 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5892 report("Failed to load branch data");
5893 return FALSE;
5896 branch_open_visitor(view, &branch_all);
5897 foreach_ref(branch_open_visitor, view);
5899 return TRUE;
5902 static bool
5903 branch_grep(struct view *view, struct line *line)
5905 struct branch *branch = line->data;
5906 const char *text[] = {
5907 branch->ref->name,
5908 mkauthor(branch->author, opt_author_width, opt_author),
5909 NULL
5912 return grep_text(view, text);
5915 static void
5916 branch_select(struct view *view, struct line *line)
5918 struct branch *branch = line->data;
5920 if (branch_is_all(branch)) {
5921 string_copy(view->ref, "All branches");
5922 return;
5924 string_copy_rev(view->ref, branch->ref->id);
5925 string_copy_rev(ref_commit, branch->ref->id);
5926 string_copy_rev(ref_head, branch->ref->id);
5927 string_copy_rev(ref_branch, branch->ref->name);
5930 static struct view_ops branch_ops = {
5931 "branch",
5932 { "branch" },
5933 VIEW_NO_FLAGS,
5934 sizeof(struct branch_state),
5935 branch_open,
5936 branch_read,
5937 branch_draw,
5938 branch_request,
5939 branch_grep,
5940 branch_select,
5944 * Status backend
5947 struct status {
5948 char status;
5949 struct {
5950 mode_t mode;
5951 char rev[SIZEOF_REV];
5952 char name[SIZEOF_STR];
5953 } old;
5954 struct {
5955 mode_t mode;
5956 char rev[SIZEOF_REV];
5957 char name[SIZEOF_STR];
5958 } new;
5961 static char status_onbranch[SIZEOF_STR];
5962 static struct status stage_status;
5963 static enum line_type stage_line_type;
5965 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5967 /* This should work even for the "On branch" line. */
5968 static inline bool
5969 status_has_none(struct view *view, struct line *line)
5971 return view_has_line(view, line) && !line[1].data;
5974 /* Get fields from the diff line:
5975 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5977 static inline bool
5978 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5980 const char *old_mode = buf + 1;
5981 const char *new_mode = buf + 8;
5982 const char *old_rev = buf + 15;
5983 const char *new_rev = buf + 56;
5984 const char *status = buf + 97;
5986 if (bufsize < 98 ||
5987 old_mode[-1] != ':' ||
5988 new_mode[-1] != ' ' ||
5989 old_rev[-1] != ' ' ||
5990 new_rev[-1] != ' ' ||
5991 status[-1] != ' ')
5992 return FALSE;
5994 file->status = *status;
5996 string_copy_rev(file->old.rev, old_rev);
5997 string_copy_rev(file->new.rev, new_rev);
5999 file->old.mode = strtoul(old_mode, NULL, 8);
6000 file->new.mode = strtoul(new_mode, NULL, 8);
6002 file->old.name[0] = file->new.name[0] = 0;
6004 return TRUE;
6007 static bool
6008 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6010 struct status *unmerged = NULL;
6011 char *buf;
6012 struct io io;
6014 if (!io_run(&io, IO_RD, opt_cdup, argv))
6015 return FALSE;
6017 add_line_nodata(view, type);
6019 while ((buf = io_get(&io, 0, TRUE))) {
6020 struct status *file = unmerged;
6022 if (!file) {
6023 if (!add_line_alloc(view, &file, type, 0, FALSE))
6024 goto error_out;
6027 /* Parse diff info part. */
6028 if (status) {
6029 file->status = status;
6030 if (status == 'A')
6031 string_copy(file->old.rev, NULL_ID);
6033 } else if (!file->status || file == unmerged) {
6034 if (!status_get_diff(file, buf, strlen(buf)))
6035 goto error_out;
6037 buf = io_get(&io, 0, TRUE);
6038 if (!buf)
6039 break;
6041 /* Collapse all modified entries that follow an
6042 * associated unmerged entry. */
6043 if (unmerged == file) {
6044 unmerged->status = 'U';
6045 unmerged = NULL;
6046 } else if (file->status == 'U') {
6047 unmerged = file;
6051 /* Grab the old name for rename/copy. */
6052 if (!*file->old.name &&
6053 (file->status == 'R' || file->status == 'C')) {
6054 string_ncopy(file->old.name, buf, strlen(buf));
6056 buf = io_get(&io, 0, TRUE);
6057 if (!buf)
6058 break;
6061 /* git-ls-files just delivers a NUL separated list of
6062 * file names similar to the second half of the
6063 * git-diff-* output. */
6064 string_ncopy(file->new.name, buf, strlen(buf));
6065 if (!*file->old.name)
6066 string_copy(file->old.name, file->new.name);
6067 file = NULL;
6070 if (io_error(&io)) {
6071 error_out:
6072 io_done(&io);
6073 return FALSE;
6076 if (!view->line[view->lines - 1].data)
6077 add_line_nodata(view, LINE_STAT_NONE);
6079 io_done(&io);
6080 return TRUE;
6083 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6084 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6086 static const char *status_list_other_argv[] = {
6087 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6090 static const char *status_list_no_head_argv[] = {
6091 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6094 static const char *update_index_argv[] = {
6095 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6098 /* Restore the previous line number to stay in the context or select a
6099 * line with something that can be updated. */
6100 static void
6101 status_restore(struct view *view)
6103 if (!check_position(&view->prev_pos))
6104 return;
6106 if (view->prev_pos.lineno >= view->lines)
6107 view->prev_pos.lineno = view->lines - 1;
6108 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6109 view->prev_pos.lineno++;
6110 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6111 view->prev_pos.lineno--;
6113 /* If the above fails, always skip the "On branch" line. */
6114 if (view->prev_pos.lineno < view->lines)
6115 view->pos.lineno = view->prev_pos.lineno;
6116 else
6117 view->pos.lineno = 1;
6119 if (view->prev_pos.offset > view->pos.lineno)
6120 view->pos.offset = view->pos.lineno;
6121 else if (view->prev_pos.offset < view->lines)
6122 view->pos.offset = view->prev_pos.offset;
6124 clear_position(&view->prev_pos);
6127 static void
6128 status_update_onbranch(void)
6130 static const char *paths[][2] = {
6131 { "rebase-apply/rebasing", "Rebasing" },
6132 { "rebase-apply/applying", "Applying mailbox" },
6133 { "rebase-apply/", "Rebasing mailbox" },
6134 { "rebase-merge/interactive", "Interactive rebase" },
6135 { "rebase-merge/", "Rebase merge" },
6136 { "MERGE_HEAD", "Merging" },
6137 { "BISECT_LOG", "Bisecting" },
6138 { "HEAD", "On branch" },
6140 char buf[SIZEOF_STR];
6141 struct stat stat;
6142 int i;
6144 if (is_initial_commit()) {
6145 string_copy(status_onbranch, "Initial commit");
6146 return;
6149 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6150 char *head = opt_head;
6152 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6153 lstat(buf, &stat) < 0)
6154 continue;
6156 if (!*opt_head) {
6157 struct io io;
6159 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6160 io_read_buf(&io, buf, sizeof(buf))) {
6161 head = buf;
6162 if (!prefixcmp(head, "refs/heads/"))
6163 head += STRING_SIZE("refs/heads/");
6167 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6168 string_copy(status_onbranch, opt_head);
6169 return;
6172 string_copy(status_onbranch, "Not currently on any branch");
6175 /* First parse staged info using git-diff-index(1), then parse unstaged
6176 * info using git-diff-files(1), and finally untracked files using
6177 * git-ls-files(1). */
6178 static bool
6179 status_open(struct view *view, enum open_flags flags)
6181 const char **staged_argv = is_initial_commit() ?
6182 status_list_no_head_argv : status_diff_index_argv;
6183 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6185 if (opt_is_inside_work_tree == FALSE) {
6186 report("The status view requires a working tree");
6187 return FALSE;
6190 reset_view(view);
6192 add_line_nodata(view, LINE_STAT_HEAD);
6193 status_update_onbranch();
6195 io_run_bg(update_index_argv);
6197 if (!opt_untracked_dirs_content)
6198 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6200 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6201 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6202 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6203 report("Failed to load status data");
6204 return FALSE;
6207 /* Restore the exact position or use the specialized restore
6208 * mode? */
6209 status_restore(view);
6210 return TRUE;
6213 static bool
6214 status_draw(struct view *view, struct line *line, unsigned int lineno)
6216 struct status *status = line->data;
6217 enum line_type type;
6218 const char *text;
6220 if (!status) {
6221 switch (line->type) {
6222 case LINE_STAT_STAGED:
6223 type = LINE_STAT_SECTION;
6224 text = "Changes to be committed:";
6225 break;
6227 case LINE_STAT_UNSTAGED:
6228 type = LINE_STAT_SECTION;
6229 text = "Changed but not updated:";
6230 break;
6232 case LINE_STAT_UNTRACKED:
6233 type = LINE_STAT_SECTION;
6234 text = "Untracked files:";
6235 break;
6237 case LINE_STAT_NONE:
6238 type = LINE_DEFAULT;
6239 text = " (no files)";
6240 break;
6242 case LINE_STAT_HEAD:
6243 type = LINE_STAT_HEAD;
6244 text = status_onbranch;
6245 break;
6247 default:
6248 return FALSE;
6250 } else {
6251 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6253 buf[0] = status->status;
6254 if (draw_text(view, line->type, buf))
6255 return TRUE;
6256 type = LINE_DEFAULT;
6257 text = status->new.name;
6260 draw_text(view, type, text);
6261 return TRUE;
6264 static enum request
6265 status_enter(struct view *view, struct line *line)
6267 struct status *status = line->data;
6268 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6270 if (line->type == LINE_STAT_NONE ||
6271 (!status && line[1].type == LINE_STAT_NONE)) {
6272 report("No file to diff");
6273 return REQ_NONE;
6276 switch (line->type) {
6277 case LINE_STAT_STAGED:
6278 case LINE_STAT_UNSTAGED:
6279 break;
6281 case LINE_STAT_UNTRACKED:
6282 if (!status) {
6283 report("No file to show");
6284 return REQ_NONE;
6287 if (!suffixcmp(status->new.name, -1, "/")) {
6288 report("Cannot display a directory");
6289 return REQ_NONE;
6291 break;
6293 case LINE_STAT_HEAD:
6294 return REQ_NONE;
6296 default:
6297 die("line type %d not handled in switch", line->type);
6300 if (status) {
6301 stage_status = *status;
6302 } else {
6303 memset(&stage_status, 0, sizeof(stage_status));
6306 stage_line_type = line->type;
6308 open_view(view, REQ_VIEW_STAGE, flags);
6309 return REQ_NONE;
6312 static bool
6313 status_exists(struct view *view, struct status *status, enum line_type type)
6315 unsigned long lineno;
6317 for (lineno = 0; lineno < view->lines; lineno++) {
6318 struct line *line = &view->line[lineno];
6319 struct status *pos = line->data;
6321 if (line->type != type)
6322 continue;
6323 if (!pos && (!status || !status->status) && line[1].data) {
6324 select_view_line(view, lineno);
6325 return TRUE;
6327 if (pos && !strcmp(status->new.name, pos->new.name)) {
6328 select_view_line(view, lineno);
6329 return TRUE;
6333 return FALSE;
6337 static bool
6338 status_update_prepare(struct io *io, enum line_type type)
6340 const char *staged_argv[] = {
6341 "git", "update-index", "-z", "--index-info", NULL
6343 const char *others_argv[] = {
6344 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6347 switch (type) {
6348 case LINE_STAT_STAGED:
6349 return io_run(io, IO_WR, opt_cdup, staged_argv);
6351 case LINE_STAT_UNSTAGED:
6352 case LINE_STAT_UNTRACKED:
6353 return io_run(io, IO_WR, opt_cdup, others_argv);
6355 default:
6356 die("line type %d not handled in switch", type);
6357 return FALSE;
6361 static bool
6362 status_update_write(struct io *io, struct status *status, enum line_type type)
6364 switch (type) {
6365 case LINE_STAT_STAGED:
6366 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6367 status->old.rev, status->old.name, 0);
6369 case LINE_STAT_UNSTAGED:
6370 case LINE_STAT_UNTRACKED:
6371 return io_printf(io, "%s%c", status->new.name, 0);
6373 default:
6374 die("line type %d not handled in switch", type);
6375 return FALSE;
6379 static bool
6380 status_update_file(struct status *status, enum line_type type)
6382 struct io io;
6383 bool result;
6385 if (!status_update_prepare(&io, type))
6386 return FALSE;
6388 result = status_update_write(&io, status, type);
6389 return io_done(&io) && result;
6392 static bool
6393 status_update_files(struct view *view, struct line *line)
6395 char buf[sizeof(view->ref)];
6396 struct io io;
6397 bool result = TRUE;
6398 struct line *pos;
6399 int files = 0;
6400 int file, done;
6401 int cursor_y = -1, cursor_x = -1;
6403 if (!status_update_prepare(&io, line->type))
6404 return FALSE;
6406 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6407 files++;
6409 string_copy(buf, view->ref);
6410 getsyx(cursor_y, cursor_x);
6411 for (file = 0, done = 5; result && file < files; line++, file++) {
6412 int almost_done = file * 100 / files;
6414 if (almost_done > done) {
6415 done = almost_done;
6416 string_format(view->ref, "updating file %u of %u (%d%% done)",
6417 file, files, done);
6418 update_view_title(view);
6419 setsyx(cursor_y, cursor_x);
6420 doupdate();
6422 result = status_update_write(&io, line->data, line->type);
6424 string_copy(view->ref, buf);
6426 return io_done(&io) && result;
6429 static bool
6430 status_update(struct view *view)
6432 struct line *line = &view->line[view->pos.lineno];
6434 assert(view->lines);
6436 if (!line->data) {
6437 if (status_has_none(view, line)) {
6438 report("Nothing to update");
6439 return FALSE;
6442 if (!status_update_files(view, line + 1)) {
6443 report("Failed to update file status");
6444 return FALSE;
6447 } else if (!status_update_file(line->data, line->type)) {
6448 report("Failed to update file status");
6449 return FALSE;
6452 return TRUE;
6455 static bool
6456 status_revert(struct status *status, enum line_type type, bool has_none)
6458 if (!status || type != LINE_STAT_UNSTAGED) {
6459 if (type == LINE_STAT_STAGED) {
6460 report("Cannot revert changes to staged files");
6461 } else if (type == LINE_STAT_UNTRACKED) {
6462 report("Cannot revert changes to untracked files");
6463 } else if (has_none) {
6464 report("Nothing to revert");
6465 } else {
6466 report("Cannot revert changes to multiple files");
6469 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6470 char mode[10] = "100644";
6471 const char *reset_argv[] = {
6472 "git", "update-index", "--cacheinfo", mode,
6473 status->old.rev, status->old.name, NULL
6475 const char *checkout_argv[] = {
6476 "git", "checkout", "--", status->old.name, NULL
6479 if (status->status == 'U') {
6480 string_format(mode, "%5o", status->old.mode);
6482 if (status->old.mode == 0 && status->new.mode == 0) {
6483 reset_argv[2] = "--force-remove";
6484 reset_argv[3] = status->old.name;
6485 reset_argv[4] = NULL;
6488 if (!io_run_fg(reset_argv, opt_cdup))
6489 return FALSE;
6490 if (status->old.mode == 0 && status->new.mode == 0)
6491 return TRUE;
6494 return io_run_fg(checkout_argv, opt_cdup);
6497 return FALSE;
6500 static enum request
6501 status_request(struct view *view, enum request request, struct line *line)
6503 struct status *status = line->data;
6505 switch (request) {
6506 case REQ_STATUS_UPDATE:
6507 if (!status_update(view))
6508 return REQ_NONE;
6509 break;
6511 case REQ_STATUS_REVERT:
6512 if (!status_revert(status, line->type, status_has_none(view, line)))
6513 return REQ_NONE;
6514 break;
6516 case REQ_STATUS_MERGE:
6517 if (!status || status->status != 'U') {
6518 report("Merging only possible for files with unmerged status ('U').");
6519 return REQ_NONE;
6521 open_mergetool(status->new.name);
6522 break;
6524 case REQ_EDIT:
6525 if (!status)
6526 return request;
6527 if (status->status == 'D') {
6528 report("File has been deleted.");
6529 return REQ_NONE;
6532 open_editor(status->new.name);
6533 break;
6535 case REQ_VIEW_BLAME:
6536 if (status)
6537 opt_ref[0] = 0;
6538 return request;
6540 case REQ_ENTER:
6541 /* After returning the status view has been split to
6542 * show the stage view. No further reloading is
6543 * necessary. */
6544 return status_enter(view, line);
6546 case REQ_REFRESH:
6547 /* Simply reload the view. */
6548 break;
6550 default:
6551 return request;
6554 refresh_view(view);
6556 return REQ_NONE;
6559 static bool
6560 status_stage_info_(char *buf, size_t bufsize,
6561 enum line_type type, struct status *status)
6563 const char *info;
6565 switch (type) {
6566 case LINE_STAT_STAGED:
6567 if (status->status)
6568 info = "Staged changes to %s";
6569 else
6570 info = "Staged changes";
6571 break;
6573 case LINE_STAT_UNSTAGED:
6574 if (status->status)
6575 info = "Unstaged changes to %s";
6576 else
6577 info = "Unstaged changes";
6578 break;
6580 case LINE_STAT_UNTRACKED:
6581 info = "Untracked file %s";
6582 break;
6584 case LINE_STAT_HEAD:
6585 default:
6586 die("line type %d not handled in switch", stage_line_type);
6589 return string_nformat(buf, bufsize, NULL, info, status->new.name);
6591 #define status_stage_info(buf, type, status) \
6592 status_stage_info_(buf, sizeof(buf), type, status)
6594 static void
6595 status_select(struct view *view, struct line *line)
6597 struct status *status = line->data;
6598 char file[SIZEOF_STR] = "all files";
6599 const char *text;
6600 const char *key;
6602 if (status && !string_format(file, "'%s'", status->new.name))
6603 return;
6605 if (!status && line[1].type == LINE_STAT_NONE)
6606 line++;
6608 switch (line->type) {
6609 case LINE_STAT_STAGED:
6610 text = "Press %s to unstage %s for commit";
6611 break;
6613 case LINE_STAT_UNSTAGED:
6614 text = "Press %s to stage %s for commit";
6615 break;
6617 case LINE_STAT_UNTRACKED:
6618 text = "Press %s to stage %s for addition";
6619 break;
6621 case LINE_STAT_HEAD:
6622 case LINE_STAT_NONE:
6623 text = "Nothing to update";
6624 break;
6626 default:
6627 die("line type %d not handled in switch", line->type);
6630 if (status && status->status == 'U') {
6631 text = "Press %s to resolve conflict in %s";
6632 key = get_view_key(view, REQ_STATUS_MERGE);
6634 } else {
6635 key = get_view_key(view, REQ_STATUS_UPDATE);
6638 string_format(view->ref, text, key, file);
6639 if (status) {
6640 string_copy(opt_file, status->new.name);
6641 status_stage_info(ref_status, line->type, status);
6645 static bool
6646 status_grep(struct view *view, struct line *line)
6648 struct status *status = line->data;
6650 if (status) {
6651 const char buf[2] = { status->status, 0 };
6652 const char *text[] = { status->new.name, buf, NULL };
6654 return grep_text(view, text);
6657 return FALSE;
6660 static struct view_ops status_ops = {
6661 "file",
6662 { "status" },
6663 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER,
6665 status_open,
6666 NULL,
6667 status_draw,
6668 status_request,
6669 status_grep,
6670 status_select,
6674 struct stage_state {
6675 struct diff_state diff;
6676 size_t chunks;
6677 int *chunk;
6680 static bool
6681 stage_diff_write(struct io *io, struct line *line, struct line *end)
6683 while (line < end) {
6684 if (!io_write(io, line->data, strlen(line->data)) ||
6685 !io_write(io, "\n", 1))
6686 return FALSE;
6687 line++;
6688 if (line->type == LINE_DIFF_CHUNK ||
6689 line->type == LINE_DIFF_HEADER)
6690 break;
6693 return TRUE;
6696 static bool
6697 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6699 const char *apply_argv[SIZEOF_ARG] = {
6700 "git", "apply", "--whitespace=nowarn", NULL
6702 struct line *diff_hdr;
6703 struct io io;
6704 int argc = 3;
6706 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6707 if (!diff_hdr)
6708 return FALSE;
6710 if (!revert)
6711 apply_argv[argc++] = "--cached";
6712 if (line != NULL)
6713 apply_argv[argc++] = "--unidiff-zero";
6714 if (revert || stage_line_type == LINE_STAT_STAGED)
6715 apply_argv[argc++] = "-R";
6716 apply_argv[argc++] = "-";
6717 apply_argv[argc++] = NULL;
6718 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6719 return FALSE;
6721 if (line != NULL) {
6722 int lineno = 0;
6723 struct line *context = chunk + 1;
6724 const char *markers[] = {
6725 line->type == LINE_DIFF_DEL ? "" : ",0",
6726 line->type == LINE_DIFF_DEL ? ",0" : "",
6729 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6731 while (context < line) {
6732 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6733 break;
6734 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6735 lineno++;
6737 context++;
6740 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6741 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6742 lineno, markers[0], lineno, markers[1]) ||
6743 !stage_diff_write(&io, line, line + 1)) {
6744 chunk = NULL;
6746 } else {
6747 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6748 !stage_diff_write(&io, chunk, view->line + view->lines))
6749 chunk = NULL;
6752 io_done(&io);
6753 io_run_bg(update_index_argv);
6755 return chunk ? TRUE : FALSE;
6758 static bool
6759 stage_update(struct view *view, struct line *line, bool single)
6761 struct line *chunk = NULL;
6763 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6764 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6766 if (chunk) {
6767 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6768 report("Failed to apply chunk");
6769 return FALSE;
6772 } else if (!stage_status.status) {
6773 view = view->parent;
6775 for (line = view->line; view_has_line(view, line); line++)
6776 if (line->type == stage_line_type)
6777 break;
6779 if (!status_update_files(view, line + 1)) {
6780 report("Failed to update files");
6781 return FALSE;
6784 } else if (!status_update_file(&stage_status, stage_line_type)) {
6785 report("Failed to update file");
6786 return FALSE;
6789 return TRUE;
6792 static bool
6793 stage_revert(struct view *view, struct line *line)
6795 struct line *chunk = NULL;
6797 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6798 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6800 if (chunk) {
6801 if (!prompt_yesno("Are you sure you want to revert changes?"))
6802 return FALSE;
6804 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6805 report("Failed to revert chunk");
6806 return FALSE;
6808 return TRUE;
6810 } else {
6811 return status_revert(stage_status.status ? &stage_status : NULL,
6812 stage_line_type, FALSE);
6817 static void
6818 stage_next(struct view *view, struct line *line)
6820 struct stage_state *state = view->private;
6821 int i;
6823 if (!state->chunks) {
6824 for (line = view->line; view_has_line(view, line); line++) {
6825 if (line->type != LINE_DIFF_CHUNK)
6826 continue;
6828 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6829 report("Allocation failure");
6830 return;
6833 state->chunk[state->chunks++] = line - view->line;
6837 for (i = 0; i < state->chunks; i++) {
6838 if (state->chunk[i] > view->pos.lineno) {
6839 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6840 report("Chunk %d of %zd", i + 1, state->chunks);
6841 return;
6845 report("No next chunk found");
6848 static enum request
6849 stage_request(struct view *view, enum request request, struct line *line)
6851 switch (request) {
6852 case REQ_STATUS_UPDATE:
6853 if (!stage_update(view, line, FALSE))
6854 return REQ_NONE;
6855 break;
6857 case REQ_STATUS_REVERT:
6858 if (!stage_revert(view, line))
6859 return REQ_NONE;
6860 break;
6862 case REQ_STAGE_UPDATE_LINE:
6863 if (stage_line_type == LINE_STAT_UNTRACKED ||
6864 stage_status.status == 'A') {
6865 report("Staging single lines is not supported for new files");
6866 return REQ_NONE;
6868 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6869 report("Please select a change to stage");
6870 return REQ_NONE;
6872 if (!stage_update(view, line, TRUE))
6873 return REQ_NONE;
6874 break;
6876 case REQ_STAGE_NEXT:
6877 if (stage_line_type == LINE_STAT_UNTRACKED) {
6878 report("File is untracked; press %s to add",
6879 get_view_key(view, REQ_STATUS_UPDATE));
6880 return REQ_NONE;
6882 stage_next(view, line);
6883 return REQ_NONE;
6885 case REQ_EDIT:
6886 if (!stage_status.new.name[0])
6887 return request;
6888 if (stage_status.status == 'D') {
6889 report("File has been deleted.");
6890 return REQ_NONE;
6893 open_editor(stage_status.new.name);
6894 break;
6896 case REQ_REFRESH:
6897 /* Reload everything ... */
6898 break;
6900 case REQ_VIEW_BLAME:
6901 if (stage_status.new.name[0]) {
6902 string_copy(opt_file, stage_status.new.name);
6903 opt_ref[0] = 0;
6905 return request;
6907 case REQ_ENTER:
6908 return diff_common_enter(view, request, line);
6910 case REQ_DIFF_CONTEXT_UP:
6911 case REQ_DIFF_CONTEXT_DOWN:
6912 if (!update_diff_context(request))
6913 return REQ_NONE;
6914 break;
6916 default:
6917 return request;
6920 refresh_view(view->parent);
6922 /* Check whether the staged entry still exists, and close the
6923 * stage view if it doesn't. */
6924 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6925 status_restore(view->parent);
6926 return REQ_VIEW_CLOSE;
6929 refresh_view(view);
6931 return REQ_NONE;
6934 static bool
6935 stage_open(struct view *view, enum open_flags flags)
6937 static const char *no_head_diff_argv[] = {
6938 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6939 stage_status.new.name)
6941 static const char *index_show_argv[] = {
6942 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6943 stage_status.old.name, stage_status.new.name)
6945 static const char *files_show_argv[] = {
6946 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6947 stage_status.old.name, stage_status.new.name)
6949 /* Diffs for unmerged entries are empty when passing the new
6950 * path, so leave out the new path. */
6951 static const char *files_unmerged_argv[] = {
6952 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
6953 opt_diff_context_arg, opt_ignore_space_arg, "--",
6954 stage_status.old.name, NULL
6956 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6957 const char **argv = NULL;
6959 if (!stage_line_type) {
6960 report("No stage content, press %s to open the status view and choose file",
6961 get_view_key(view, REQ_VIEW_STATUS));
6962 return FALSE;
6965 view->encoding = NULL;
6967 switch (stage_line_type) {
6968 case LINE_STAT_STAGED:
6969 if (is_initial_commit()) {
6970 argv = no_head_diff_argv;
6971 } else {
6972 argv = index_show_argv;
6974 break;
6976 case LINE_STAT_UNSTAGED:
6977 if (stage_status.status != 'U')
6978 argv = files_show_argv;
6979 else
6980 argv = files_unmerged_argv;
6981 break;
6983 case LINE_STAT_UNTRACKED:
6984 argv = file_argv;
6985 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6986 break;
6988 case LINE_STAT_HEAD:
6989 default:
6990 die("line type %d not handled in switch", stage_line_type);
6993 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
6994 || !argv_copy(&view->argv, argv)) {
6995 report("Failed to open staged view");
6996 return FALSE;
6999 view->vid[0] = 0;
7000 view->dir = opt_cdup;
7001 return begin_update(view, NULL, NULL, flags);
7004 static bool
7005 stage_read(struct view *view, char *data)
7007 struct stage_state *state = view->private;
7009 if (data && diff_common_read(view, data, &state->diff))
7010 return TRUE;
7012 return pager_read(view, data);
7015 static struct view_ops stage_ops = {
7016 "line",
7017 { "stage" },
7018 VIEW_DIFF_LIKE,
7019 sizeof(struct stage_state),
7020 stage_open,
7021 stage_read,
7022 diff_common_draw,
7023 stage_request,
7024 pager_grep,
7025 pager_select,
7030 * Revision graph
7033 static const enum line_type graph_colors[] = {
7034 LINE_PALETTE_0,
7035 LINE_PALETTE_1,
7036 LINE_PALETTE_2,
7037 LINE_PALETTE_3,
7038 LINE_PALETTE_4,
7039 LINE_PALETTE_5,
7040 LINE_PALETTE_6,
7043 static enum line_type get_graph_color(struct graph_symbol *symbol)
7045 if (symbol->commit)
7046 return LINE_GRAPH_COMMIT;
7047 assert(symbol->color < ARRAY_SIZE(graph_colors));
7048 return graph_colors[symbol->color];
7051 static bool
7052 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7054 const char *chars = graph_symbol_to_utf8(symbol);
7056 return draw_text(view, color, chars + !!first);
7059 static bool
7060 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7062 const char *chars = graph_symbol_to_ascii(symbol);
7064 return draw_text(view, color, chars + !!first);
7067 static bool
7068 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7070 const chtype *chars = graph_symbol_to_chtype(symbol);
7072 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7075 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7077 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7079 static const draw_graph_fn fns[] = {
7080 draw_graph_ascii,
7081 draw_graph_chtype,
7082 draw_graph_utf8
7084 draw_graph_fn fn = fns[opt_line_graphics];
7085 int i;
7087 for (i = 0; i < canvas->size; i++) {
7088 struct graph_symbol *symbol = &canvas->symbols[i];
7089 enum line_type color = get_graph_color(symbol);
7091 if (fn(view, symbol, color, i == 0))
7092 return TRUE;
7095 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7099 * Main view backend
7102 struct commit {
7103 char id[SIZEOF_REV]; /* SHA1 ID. */
7104 char title[128]; /* First line of the commit message. */
7105 const char *author; /* Author of the commit. */
7106 struct time time; /* Date from the author ident. */
7107 struct ref_list *refs; /* Repository references. */
7108 struct graph_canvas graph; /* Ancestry chain graphics. */
7111 struct main_state {
7112 struct graph graph;
7113 struct commit *current;
7114 bool in_header;
7115 bool added_changes_commits;
7118 static struct commit *
7119 main_add_commit(struct view *view, enum line_type type, const char *ids,
7120 bool is_boundary, bool custom)
7122 struct main_state *state = view->private;
7123 struct commit *commit;
7125 if (!add_line_alloc(view, &commit, type, 0, custom))
7126 return NULL;
7128 string_copy_rev(commit->id, ids);
7129 commit->refs = get_ref_list(commit->id);
7130 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7131 return commit;
7134 bool
7135 main_has_changes(const char *argv[])
7137 struct io io;
7139 if (!io_run(&io, IO_BG, NULL, argv, -1))
7140 return FALSE;
7141 io_done(&io);
7142 return io.status == 1;
7145 static void
7146 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7148 char ids[SIZEOF_STR] = NULL_ID " ";
7149 struct main_state *state = view->private;
7150 struct commit *commit;
7151 struct timeval now;
7152 struct timezone tz;
7154 if (!parent)
7155 return;
7157 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7159 commit = main_add_commit(view, type, ids, FALSE, TRUE);
7160 if (!commit)
7161 return;
7163 if (!gettimeofday(&now, &tz)) {
7164 commit->time.tz = tz.tz_minuteswest * 60;
7165 commit->time.sec = now.tv_sec - commit->time.tz;
7168 commit->author = "";
7169 string_ncopy(commit->title, title, strlen(title));
7170 graph_render_parents(&state->graph);
7173 static void
7174 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7176 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7177 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7178 const char *staged_parent = NULL_ID;
7179 const char *unstaged_parent = parent;
7181 if (!is_head_commit(parent))
7182 return;
7184 state->added_changes_commits = TRUE;
7186 io_run_bg(update_index_argv);
7188 if (!main_has_changes(unstaged_argv)) {
7189 unstaged_parent = NULL;
7190 staged_parent = parent;
7193 if (!main_has_changes(staged_argv)) {
7194 staged_parent = NULL;
7197 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7198 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7201 static bool
7202 main_open(struct view *view, enum open_flags flags)
7204 static const char *main_argv[] = {
7205 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7208 return begin_update(view, NULL, main_argv, flags);
7211 static bool
7212 main_draw(struct view *view, struct line *line, unsigned int lineno)
7214 struct commit *commit = line->data;
7216 if (!commit->author)
7217 return FALSE;
7219 if (draw_lineno(view, lineno))
7220 return TRUE;
7222 if (opt_show_id && draw_id(view, LINE_ID, commit->id))
7223 return TRUE;
7225 if (draw_date(view, &commit->time))
7226 return TRUE;
7228 if (draw_author(view, commit->author))
7229 return TRUE;
7231 if (opt_rev_graph && draw_graph(view, &commit->graph))
7232 return TRUE;
7234 if (draw_refs(view, commit->refs))
7235 return TRUE;
7237 draw_text(view, LINE_DEFAULT, commit->title);
7238 return TRUE;
7241 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7242 static bool
7243 main_read(struct view *view, char *line)
7245 struct main_state *state = view->private;
7246 struct graph *graph = &state->graph;
7247 enum line_type type;
7248 struct commit *commit = state->current;
7250 if (!line) {
7251 if (!view->lines && !view->prev)
7252 die("No revisions match the given arguments.");
7253 if (view->lines > 0) {
7254 commit = view->line[view->lines - 1].data;
7255 view->line[view->lines - 1].dirty = 1;
7256 if (!commit->author) {
7257 view->lines--;
7258 free(commit);
7262 done_graph(graph);
7263 return TRUE;
7266 type = get_line_type(line);
7267 if (type == LINE_COMMIT) {
7268 bool is_boundary;
7270 state->in_header = TRUE;
7271 line += STRING_SIZE("commit ");
7272 is_boundary = *line == '-';
7273 if (is_boundary || !isalnum(*line))
7274 line++;
7276 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7277 main_add_changes_commits(view, state, line);
7279 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7280 return state->current != NULL;
7283 if (!view->lines || !commit)
7284 return TRUE;
7286 /* Empty line separates the commit header from the log itself. */
7287 if (*line == '\0')
7288 state->in_header = FALSE;
7290 switch (type) {
7291 case LINE_PARENT:
7292 if (!graph->has_parents)
7293 graph_add_parent(graph, line + STRING_SIZE("parent "));
7294 break;
7296 case LINE_AUTHOR:
7297 parse_author_line(line + STRING_SIZE("author "),
7298 &commit->author, &commit->time);
7299 graph_render_parents(graph);
7300 break;
7302 default:
7303 /* Fill in the commit title if it has not already been set. */
7304 if (commit->title[0])
7305 break;
7307 /* Skip lines in the commit header. */
7308 if (state->in_header)
7309 break;
7311 /* Require titles to start with a non-space character at the
7312 * offset used by git log. */
7313 if (strncmp(line, " ", 4))
7314 break;
7315 line += 4;
7316 /* Well, if the title starts with a whitespace character,
7317 * try to be forgiving. Otherwise we end up with no title. */
7318 while (isspace(*line))
7319 line++;
7320 if (*line == '\0')
7321 break;
7322 /* FIXME: More graceful handling of titles; append "..." to
7323 * shortened titles, etc. */
7325 string_expand(commit->title, sizeof(commit->title), line, 1);
7326 view->line[view->lines - 1].dirty = 1;
7329 return TRUE;
7332 static enum request
7333 main_request(struct view *view, enum request request, struct line *line)
7335 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7337 switch (request) {
7338 case REQ_NEXT:
7339 case REQ_PREVIOUS:
7340 if (view_is_displayed(view) && display[0] != view)
7341 return request;
7342 /* Do not pass navigation requests to the branch view
7343 * when the main view is maximized. (GH #38) */
7344 move_view(view, request);
7345 break;
7347 case REQ_ENTER:
7348 if (view_is_displayed(view) && display[0] != view)
7349 maximize_view(view, TRUE);
7351 if (line->type == LINE_STAT_UNSTAGED
7352 || line->type == LINE_STAT_STAGED) {
7353 struct view *diff = VIEW(REQ_VIEW_DIFF);
7354 const char *diff_staged_argv[] = {
7355 GIT_DIFF_STAGED(opt_encoding_arg,
7356 opt_diff_context_arg,
7357 opt_ignore_space_arg, NULL, NULL)
7359 const char *diff_unstaged_argv[] = {
7360 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7361 opt_diff_context_arg,
7362 opt_ignore_space_arg, NULL, NULL)
7364 const char **diff_argv = line->type == LINE_STAT_STAGED
7365 ? diff_staged_argv : diff_unstaged_argv;
7367 open_argv(view, diff, diff_argv, NULL, flags);
7368 break;
7371 open_view(view, REQ_VIEW_DIFF, flags);
7372 break;
7373 case REQ_REFRESH:
7374 load_refs();
7375 refresh_view(view);
7376 break;
7378 case REQ_JUMP_COMMIT:
7380 int lineno;
7382 for (lineno = 0; lineno < view->lines; lineno++) {
7383 struct commit *commit = view->line[lineno].data;
7385 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7386 select_view_line(view, lineno);
7387 report_clear();
7388 return REQ_NONE;
7392 report("Unable to find commit '%s'", opt_search);
7393 break;
7395 default:
7396 return request;
7399 return REQ_NONE;
7402 static bool
7403 grep_refs(struct ref_list *list, regex_t *regex)
7405 regmatch_t pmatch;
7406 size_t i;
7408 if (!opt_show_refs || !list)
7409 return FALSE;
7411 for (i = 0; i < list->size; i++) {
7412 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7413 return TRUE;
7416 return FALSE;
7419 static bool
7420 main_grep(struct view *view, struct line *line)
7422 struct commit *commit = line->data;
7423 const char *text[] = {
7424 commit->id,
7425 commit->title,
7426 mkauthor(commit->author, opt_author_width, opt_author),
7427 mkdate(&commit->time, opt_date),
7428 NULL
7431 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7434 static void
7435 main_select(struct view *view, struct line *line)
7437 struct commit *commit = line->data;
7439 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7440 string_copy(view->ref, commit->title);
7441 else
7442 string_copy_rev(view->ref, commit->id);
7443 string_copy_rev(ref_commit, commit->id);
7446 static struct view_ops main_ops = {
7447 "commit",
7448 { "main" },
7449 VIEW_STDIN | VIEW_SEND_CHILD_ENTER,
7450 sizeof(struct main_state),
7451 main_open,
7452 main_read,
7453 main_draw,
7454 main_request,
7455 main_grep,
7456 main_select,
7461 * Status management
7464 /* Whether or not the curses interface has been initialized. */
7465 static bool cursed = FALSE;
7467 /* Terminal hacks and workarounds. */
7468 static bool use_scroll_redrawwin;
7469 static bool use_scroll_status_wclear;
7471 /* The status window is used for polling keystrokes. */
7472 static WINDOW *status_win;
7474 /* Reading from the prompt? */
7475 static bool input_mode = FALSE;
7477 static bool status_empty = FALSE;
7479 /* Update status and title window. */
7480 static void
7481 report(const char *msg, ...)
7483 struct view *view = display[current_view];
7485 if (input_mode)
7486 return;
7488 if (!view) {
7489 char buf[SIZEOF_STR];
7490 int retval;
7492 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7493 die("%s", buf);
7496 if (!status_empty || *msg) {
7497 va_list args;
7499 va_start(args, msg);
7501 wmove(status_win, 0, 0);
7502 if (view->has_scrolled && use_scroll_status_wclear)
7503 wclear(status_win);
7504 if (*msg) {
7505 vwprintw(status_win, msg, args);
7506 status_empty = FALSE;
7507 } else {
7508 status_empty = TRUE;
7510 wclrtoeol(status_win);
7511 wnoutrefresh(status_win);
7513 va_end(args);
7516 update_view_title(view);
7519 static void
7520 init_display(void)
7522 const char *term;
7523 int x, y;
7525 /* Initialize the curses library */
7526 if (isatty(STDIN_FILENO)) {
7527 cursed = !!initscr();
7528 opt_tty = stdin;
7529 } else {
7530 /* Leave stdin and stdout alone when acting as a pager. */
7531 opt_tty = fopen("/dev/tty", "r+");
7532 if (!opt_tty)
7533 die("Failed to open /dev/tty");
7534 cursed = !!newterm(NULL, opt_tty, opt_tty);
7537 if (!cursed)
7538 die("Failed to initialize curses");
7540 nonl(); /* Disable conversion and detect newlines from input. */
7541 cbreak(); /* Take input chars one at a time, no wait for \n */
7542 noecho(); /* Don't echo input */
7543 leaveok(stdscr, FALSE);
7545 if (has_colors())
7546 init_colors();
7548 getmaxyx(stdscr, y, x);
7549 status_win = newwin(1, x, y - 1, 0);
7550 if (!status_win)
7551 die("Failed to create status window");
7553 /* Enable keyboard mapping */
7554 keypad(status_win, TRUE);
7555 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7557 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7558 set_tabsize(opt_tab_size);
7559 #else
7560 TABSIZE = opt_tab_size;
7561 #endif
7563 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7564 if (term && !strcmp(term, "gnome-terminal")) {
7565 /* In the gnome-terminal-emulator, the message from
7566 * scrolling up one line when impossible followed by
7567 * scrolling down one line causes corruption of the
7568 * status line. This is fixed by calling wclear. */
7569 use_scroll_status_wclear = TRUE;
7570 use_scroll_redrawwin = FALSE;
7572 } else if (term && !strcmp(term, "xrvt-xpm")) {
7573 /* No problems with full optimizations in xrvt-(unicode)
7574 * and aterm. */
7575 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7577 } else {
7578 /* When scrolling in (u)xterm the last line in the
7579 * scrolling direction will update slowly. */
7580 use_scroll_redrawwin = TRUE;
7581 use_scroll_status_wclear = FALSE;
7585 static int
7586 get_input(int prompt_position)
7588 struct view *view;
7589 int i, key, cursor_y, cursor_x;
7591 if (prompt_position)
7592 input_mode = TRUE;
7594 while (TRUE) {
7595 bool loading = FALSE;
7597 foreach_view (view, i) {
7598 update_view(view);
7599 if (view_is_displayed(view) && view->has_scrolled &&
7600 use_scroll_redrawwin)
7601 redrawwin(view->win);
7602 view->has_scrolled = FALSE;
7603 if (view->pipe)
7604 loading = TRUE;
7607 /* Update the cursor position. */
7608 if (prompt_position) {
7609 getbegyx(status_win, cursor_y, cursor_x);
7610 cursor_x = prompt_position;
7611 } else {
7612 view = display[current_view];
7613 getbegyx(view->win, cursor_y, cursor_x);
7614 cursor_x = view->width - 1;
7615 cursor_y += view->pos.lineno - view->pos.offset;
7617 setsyx(cursor_y, cursor_x);
7619 /* Refresh, accept single keystroke of input */
7620 doupdate();
7621 nodelay(status_win, loading);
7622 key = wgetch(status_win);
7624 /* wgetch() with nodelay() enabled returns ERR when
7625 * there's no input. */
7626 if (key == ERR) {
7628 } else if (key == KEY_RESIZE) {
7629 int height, width;
7631 getmaxyx(stdscr, height, width);
7633 wresize(status_win, 1, width);
7634 mvwin(status_win, height - 1, 0);
7635 wnoutrefresh(status_win);
7636 resize_display();
7637 redraw_display(TRUE);
7639 } else {
7640 input_mode = FALSE;
7641 if (key == erasechar())
7642 key = KEY_BACKSPACE;
7643 return key;
7648 static char *
7649 prompt_input(const char *prompt, input_handler handler, void *data)
7651 enum input_status status = INPUT_OK;
7652 static char buf[SIZEOF_STR];
7653 size_t pos = 0;
7655 buf[pos] = 0;
7657 while (status == INPUT_OK || status == INPUT_SKIP) {
7658 int key;
7660 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7661 wclrtoeol(status_win);
7663 key = get_input(pos + 1);
7664 switch (key) {
7665 case KEY_RETURN:
7666 case KEY_ENTER:
7667 case '\n':
7668 status = pos ? INPUT_STOP : INPUT_CANCEL;
7669 break;
7671 case KEY_BACKSPACE:
7672 if (pos > 0)
7673 buf[--pos] = 0;
7674 else
7675 status = INPUT_CANCEL;
7676 break;
7678 case KEY_ESC:
7679 status = INPUT_CANCEL;
7680 break;
7682 default:
7683 if (pos >= sizeof(buf)) {
7684 report("Input string too long");
7685 return NULL;
7688 status = handler(data, buf, key);
7689 if (status == INPUT_OK)
7690 buf[pos++] = (char) key;
7694 /* Clear the status window */
7695 status_empty = FALSE;
7696 report_clear();
7698 if (status == INPUT_CANCEL)
7699 return NULL;
7701 buf[pos++] = 0;
7703 return buf;
7706 static enum input_status
7707 prompt_yesno_handler(void *data, char *buf, int c)
7709 if (c == 'y' || c == 'Y')
7710 return INPUT_STOP;
7711 if (c == 'n' || c == 'N')
7712 return INPUT_CANCEL;
7713 return INPUT_SKIP;
7716 static bool
7717 prompt_yesno(const char *prompt)
7719 char prompt2[SIZEOF_STR];
7721 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7722 return FALSE;
7724 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7727 static enum input_status
7728 read_prompt_handler(void *data, char *buf, int c)
7730 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7733 static char *
7734 read_prompt(const char *prompt)
7736 return prompt_input(prompt, read_prompt_handler, NULL);
7739 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7741 enum input_status status = INPUT_OK;
7742 int size = 0;
7744 while (items[size].text)
7745 size++;
7747 assert(size > 0);
7749 while (status == INPUT_OK) {
7750 const struct menu_item *item = &items[*selected];
7751 int key;
7752 int i;
7754 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7755 prompt, *selected + 1, size);
7756 if (item->hotkey)
7757 wprintw(status_win, "[%c] ", (char) item->hotkey);
7758 wprintw(status_win, "%s", item->text);
7759 wclrtoeol(status_win);
7761 key = get_input(COLS - 1);
7762 switch (key) {
7763 case KEY_RETURN:
7764 case KEY_ENTER:
7765 case '\n':
7766 status = INPUT_STOP;
7767 break;
7769 case KEY_LEFT:
7770 case KEY_UP:
7771 *selected = *selected - 1;
7772 if (*selected < 0)
7773 *selected = size - 1;
7774 break;
7776 case KEY_RIGHT:
7777 case KEY_DOWN:
7778 *selected = (*selected + 1) % size;
7779 break;
7781 case KEY_ESC:
7782 status = INPUT_CANCEL;
7783 break;
7785 default:
7786 for (i = 0; items[i].text; i++)
7787 if (items[i].hotkey == key) {
7788 *selected = i;
7789 status = INPUT_STOP;
7790 break;
7795 /* Clear the status window */
7796 status_empty = FALSE;
7797 report_clear();
7799 return status != INPUT_CANCEL;
7803 * Repository properties
7807 static void
7808 set_remote_branch(const char *name, const char *value, size_t valuelen)
7810 if (!strcmp(name, ".remote")) {
7811 string_ncopy(opt_remote, value, valuelen);
7813 } else if (*opt_remote && !strcmp(name, ".merge")) {
7814 size_t from = strlen(opt_remote);
7816 if (!prefixcmp(value, "refs/heads/"))
7817 value += STRING_SIZE("refs/heads/");
7819 if (!string_format_from(opt_remote, &from, "/%s", value))
7820 opt_remote[0] = 0;
7824 static void
7825 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7827 const char *argv[SIZEOF_ARG] = { name, "=" };
7828 int argc = 1 + (cmd == option_set_command);
7829 enum option_code error;
7831 if (!argv_from_string(argv, &argc, value))
7832 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7833 else
7834 error = cmd(argc, argv);
7836 if (error != OPT_OK)
7837 warn("Option 'tig.%s': %s", name, option_errors[error]);
7840 static bool
7841 set_environment_variable(const char *name, const char *value)
7843 size_t len = strlen(name) + 1 + strlen(value) + 1;
7844 char *env = malloc(len);
7846 if (env &&
7847 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7848 putenv(env) == 0)
7849 return TRUE;
7850 free(env);
7851 return FALSE;
7854 static void
7855 set_work_tree(const char *value)
7857 char cwd[SIZEOF_STR];
7859 if (!getcwd(cwd, sizeof(cwd)))
7860 die("Failed to get cwd path: %s", strerror(errno));
7861 if (chdir(cwd) < 0)
7862 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7863 if (chdir(opt_git_dir) < 0)
7864 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
7865 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7866 die("Failed to get git path: %s", strerror(errno));
7867 if (chdir(value) < 0)
7868 die("Failed to chdir(%s): %s", value, strerror(errno));
7869 if (!getcwd(cwd, sizeof(cwd)))
7870 die("Failed to get cwd path: %s", strerror(errno));
7871 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7872 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7873 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7874 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7875 opt_is_inside_work_tree = TRUE;
7878 static void
7879 parse_git_color_option(enum line_type type, char *value)
7881 struct line_info *info = &line_info[type];
7882 const char *argv[SIZEOF_ARG];
7883 int argc = 0;
7884 bool first_color = TRUE;
7885 int i;
7887 if (!argv_from_string(argv, &argc, value))
7888 return;
7890 info->fg = COLOR_DEFAULT;
7891 info->bg = COLOR_DEFAULT;
7892 info->attr = 0;
7894 for (i = 0; i < argc; i++) {
7895 int attr = 0;
7897 if (set_attribute(&attr, argv[i])) {
7898 info->attr |= attr;
7900 } else if (set_color(&attr, argv[i])) {
7901 if (first_color)
7902 info->fg = attr;
7903 else
7904 info->bg = attr;
7905 first_color = FALSE;
7910 static void
7911 set_git_color_option(const char *name, char *value)
7913 static const struct enum_map color_option_map[] = {
7914 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7915 ENUM_MAP("branch.local", LINE_MAIN_REF),
7916 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7917 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7919 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7920 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7921 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7922 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7923 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7924 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7925 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7927 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7929 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7930 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7931 ENUM_MAP("status.added", LINE_STAT_STAGED),
7932 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7933 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7934 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7937 int type = LINE_NONE;
7939 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7940 parse_git_color_option(type, value);
7944 static void
7945 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
7947 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
7948 opt_encoding_arg[0] = 0;
7951 static int
7952 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7954 if (!strcmp(name, "i18n.commitencoding"))
7955 set_encoding(&opt_encoding, value, FALSE);
7957 else if (!strcmp(name, "gui.encoding"))
7958 set_encoding(&opt_encoding, value, TRUE);
7960 else if (!strcmp(name, "core.editor"))
7961 string_ncopy(opt_editor, value, valuelen);
7963 else if (!strcmp(name, "core.worktree"))
7964 set_work_tree(value);
7966 else if (!strcmp(name, "core.abbrev"))
7967 parse_id(&opt_id_cols, value);
7969 else if (!prefixcmp(name, "tig.color."))
7970 set_repo_config_option(name + 10, value, option_color_command);
7972 else if (!prefixcmp(name, "tig.bind."))
7973 set_repo_config_option(name + 9, value, option_bind_command);
7975 else if (!prefixcmp(name, "tig."))
7976 set_repo_config_option(name + 4, value, option_set_command);
7978 else if (!prefixcmp(name, "color."))
7979 set_git_color_option(name + STRING_SIZE("color."), value);
7981 else if (*opt_head && !prefixcmp(name, "branch.") &&
7982 !strncmp(name + 7, opt_head, strlen(opt_head)))
7983 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7985 return OK;
7988 static int
7989 load_git_config(void)
7991 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7993 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7996 static int
7997 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7999 if (!opt_git_dir[0]) {
8000 string_ncopy(opt_git_dir, name, namelen);
8002 } else if (opt_is_inside_work_tree == -1) {
8003 /* This can be 3 different values depending on the
8004 * version of git being used. If git-rev-parse does not
8005 * understand --is-inside-work-tree it will simply echo
8006 * the option else either "true" or "false" is printed.
8007 * Default to true for the unknown case. */
8008 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8010 } else if (*name == '.') {
8011 string_ncopy(opt_cdup, name, namelen);
8013 } else {
8014 string_ncopy(opt_prefix, name, namelen);
8017 return OK;
8020 static int
8021 load_repo_info(void)
8023 const char *rev_parse_argv[] = {
8024 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
8025 "--show-cdup", "--show-prefix", NULL
8028 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
8033 * Main
8036 static const char usage[] =
8037 "tig " TIG_VERSION " (" __DATE__ ")\n"
8038 "\n"
8039 "Usage: tig [options] [revs] [--] [paths]\n"
8040 " or: tig show [options] [revs] [--] [paths]\n"
8041 " or: tig blame [options] [rev] [--] path\n"
8042 " or: tig status\n"
8043 " or: tig < [git command output]\n"
8044 "\n"
8045 "Options:\n"
8046 " +<number> Select line <number> in the first view\n"
8047 " -v, --version Show version and exit\n"
8048 " -h, --help Show help message and exit";
8050 static void __NORETURN
8051 quit(int sig)
8053 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8054 if (cursed)
8055 endwin();
8056 exit(0);
8059 static void __NORETURN
8060 die(const char *err, ...)
8062 va_list args;
8064 endwin();
8066 va_start(args, err);
8067 fputs("tig: ", stderr);
8068 vfprintf(stderr, err, args);
8069 fputs("\n", stderr);
8070 va_end(args);
8072 exit(1);
8075 static void
8076 warn(const char *msg, ...)
8078 va_list args;
8080 va_start(args, msg);
8081 fputs("tig warning: ", stderr);
8082 vfprintf(stderr, msg, args);
8083 fputs("\n", stderr);
8084 va_end(args);
8087 static int
8088 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8090 const char ***filter_args = data;
8092 return argv_append(filter_args, name) ? OK : ERR;
8095 static void
8096 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8098 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8099 const char **all_argv = NULL;
8101 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8102 !argv_append_array(&all_argv, argv) ||
8103 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8104 die("Failed to split arguments");
8105 argv_free(all_argv);
8106 free(all_argv);
8109 static bool
8110 is_rev_flag(const char *flag)
8112 static const char *rev_flags[] = { GIT_REV_FLAGS };
8113 int i;
8115 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8116 if (!strcmp(flag, rev_flags[i]))
8117 return TRUE;
8119 return FALSE;
8122 static void
8123 filter_options(const char *argv[], bool blame)
8125 const char **flags = NULL;
8127 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8128 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8130 if (flags) {
8131 int next, flags_pos;
8133 for (next = flags_pos = 0; flags && flags[next]; next++) {
8134 const char *flag = flags[next];
8136 if (is_rev_flag(flag))
8137 argv_append(&opt_rev_argv, flag);
8138 else
8139 flags[flags_pos++] = flag;
8142 flags[flags_pos] = NULL;
8144 if (blame)
8145 opt_blame_argv = flags;
8146 else
8147 opt_diff_argv = flags;
8150 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8153 static enum request
8154 parse_options(int argc, const char *argv[])
8156 enum request request;
8157 const char *subcommand;
8158 bool seen_dashdash = FALSE;
8159 const char **filter_argv = NULL;
8160 int i;
8162 opt_stdin = !isatty(STDIN_FILENO);
8163 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8165 if (argc <= 1)
8166 return request;
8168 subcommand = argv[1];
8169 if (!strcmp(subcommand, "status")) {
8170 request = REQ_VIEW_STATUS;
8172 } else if (!strcmp(subcommand, "blame")) {
8173 request = REQ_VIEW_BLAME;
8175 } else if (!strcmp(subcommand, "show")) {
8176 request = REQ_VIEW_DIFF;
8178 } else {
8179 subcommand = NULL;
8182 for (i = 1 + !!subcommand; i < argc; i++) {
8183 const char *opt = argv[i];
8185 // stop parsing our options after -- and let rev-parse handle the rest
8186 if (!seen_dashdash) {
8187 if (!strcmp(opt, "--")) {
8188 seen_dashdash = TRUE;
8189 continue;
8191 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8192 printf("tig version %s\n", TIG_VERSION);
8193 quit(0);
8195 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8196 printf("%s\n", usage);
8197 quit(0);
8199 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8200 opt_lineno = atoi(opt + 1);
8201 continue;
8206 if (!argv_append(&filter_argv, opt))
8207 die("command too long");
8210 if (filter_argv)
8211 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8213 /* Finish validating and setting up blame options */
8214 if (request == REQ_VIEW_BLAME) {
8215 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8216 die("invalid number of options to blame\n\n%s", usage);
8218 if (opt_rev_argv) {
8219 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8222 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8224 } else if (request == REQ_VIEW_PAGER) {
8225 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8226 if (!strcmp("--stdin", opt_rev_argv[i])) {
8227 request = REQ_VIEW_MAIN;
8228 break;
8233 return request;
8237 main(int argc, const char *argv[])
8239 const char *codeset = ENCODING_UTF8;
8240 enum request request = parse_options(argc, argv);
8241 struct view *view;
8242 int i;
8244 signal(SIGINT, quit);
8245 signal(SIGPIPE, SIG_IGN);
8247 if (setlocale(LC_ALL, "")) {
8248 codeset = nl_langinfo(CODESET);
8251 foreach_view(view, i) {
8252 add_keymap(&view->ops->keymap);
8255 if (load_repo_info() == ERR)
8256 die("Failed to load repo info.");
8258 if (load_options() == ERR)
8259 die("Failed to load user config.");
8261 if (load_git_config() == ERR)
8262 die("Failed to load repo config.");
8264 /* Require a git repository unless when running in pager mode. */
8265 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8266 die("Not a git repository");
8268 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8269 char translit[SIZEOF_STR];
8271 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8272 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8273 else
8274 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8275 if (opt_iconv_out == ICONV_NONE)
8276 die("Failed to initialize character set conversion");
8279 if (load_refs() == ERR)
8280 die("Failed to load refs.");
8282 init_display();
8284 while (view_driver(display[current_view], request)) {
8285 int key = get_input(0);
8287 view = display[current_view];
8288 request = get_keybinding(&view->ops->keymap, key);
8290 /* Some low-level request handling. This keeps access to
8291 * status_win restricted. */
8292 switch (request) {
8293 case REQ_NONE:
8294 report("Unknown key, press %s for help",
8295 get_view_key(view, REQ_VIEW_HELP));
8296 break;
8297 case REQ_PROMPT:
8299 char *cmd = read_prompt(":");
8301 if (cmd && string_isnumber(cmd)) {
8302 int lineno = view->pos.lineno + 1;
8304 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8305 select_view_line(view, lineno - 1);
8306 report_clear();
8307 } else {
8308 report("Unable to parse '%s' as a line number", cmd);
8310 } else if (cmd && iscommit(cmd)) {
8311 string_ncopy(opt_search, cmd, strlen(cmd));
8313 request = view_request(view, REQ_JUMP_COMMIT);
8314 if (request == REQ_JUMP_COMMIT) {
8315 report("Jumping to commits is not supported by the '%s' view", view->name);
8318 } else if (cmd && strlen(cmd) == 1) {
8319 request = get_keybinding(&view->ops->keymap, cmd[0]);
8320 break;
8322 } else if (cmd && cmd[0] == '!') {
8323 struct view *next = VIEW(REQ_VIEW_PAGER);
8324 const char *argv[SIZEOF_ARG];
8325 int argc = 0;
8327 cmd++;
8328 /* When running random commands, initially show the
8329 * command in the title. However, it maybe later be
8330 * overwritten if a commit line is selected. */
8331 string_ncopy(next->ref, cmd, strlen(cmd));
8333 if (!argv_from_string(argv, &argc, cmd)) {
8334 report("Too many arguments");
8335 } else if (!format_argv(&next->argv, argv, FALSE)) {
8336 report("Argument formatting failed");
8337 } else {
8338 next->dir = NULL;
8339 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8342 } else if (cmd) {
8343 request = get_request(cmd);
8344 if (request != REQ_UNKNOWN)
8345 break;
8347 char *args = strchr(cmd, ' ');
8348 if (args) {
8349 *args++ = 0;
8350 if (set_option(cmd, args) == OPT_OK) {
8351 request = REQ_SCREEN_REDRAW;
8352 if (!strcmp(cmd, "color"))
8353 init_colors();
8356 break;
8359 request = REQ_NONE;
8360 break;
8362 case REQ_SEARCH:
8363 case REQ_SEARCH_BACK:
8365 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8366 char *search = read_prompt(prompt);
8368 if (search)
8369 string_ncopy(opt_search, search, strlen(search));
8370 else if (*opt_search)
8371 request = request == REQ_SEARCH ?
8372 REQ_FIND_NEXT :
8373 REQ_FIND_PREV;
8374 else
8375 request = REQ_NONE;
8376 break;
8378 default:
8379 break;
8383 quit(0);
8385 return 0;