Do not count the first line and parent accessor lines in the tree view
[tig.git] / tig.c
blobb47cc7bc8faf58bd3c4616dc80fb1cef5d4e4ee0
1 /* Copyright (c) 2006-2012 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include "tig.h"
15 #include "io.h"
16 #include "refs.h"
17 #include "graph.h"
18 #include "git.h"
20 static void __NORETURN die(const char *err, ...);
21 static void warn(const char *msg, ...);
22 static void report(const char *msg, ...);
25 enum input_status {
26 INPUT_OK,
27 INPUT_SKIP,
28 INPUT_STOP,
29 INPUT_CANCEL
32 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
34 static char *prompt_input(const char *prompt, input_handler handler, void *data);
35 static bool prompt_yesno(const char *prompt);
36 static char *read_prompt(const char *prompt);
38 struct menu_item {
39 int hotkey;
40 const char *text;
41 void *data;
44 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
46 #define GRAPHIC_ENUM(_) \
47 _(GRAPHIC, ASCII), \
48 _(GRAPHIC, DEFAULT), \
49 _(GRAPHIC, UTF_8)
51 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
53 #define DATE_ENUM(_) \
54 _(DATE, NO), \
55 _(DATE, DEFAULT), \
56 _(DATE, LOCAL), \
57 _(DATE, RELATIVE), \
58 _(DATE, SHORT)
60 DEFINE_ENUM(date, DATE_ENUM);
62 struct time {
63 time_t sec;
64 int tz;
67 static inline int timecmp(const struct time *t1, const struct time *t2)
69 return t1->sec - t2->sec;
72 static const char *
73 mkdate(const struct time *time, enum date date)
75 static char buf[DATE_COLS + 1];
76 static const struct enum_map reldate[] = {
77 { "second", 1, 60 * 2 },
78 { "minute", 60, 60 * 60 * 2 },
79 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
80 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
81 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
82 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
84 struct tm tm;
86 if (!date || !time || !time->sec)
87 return "";
89 if (date == DATE_RELATIVE) {
90 struct timeval now;
91 time_t date = time->sec + time->tz;
92 time_t seconds;
93 int i;
95 gettimeofday(&now, NULL);
96 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
97 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
98 if (seconds >= reldate[i].value)
99 continue;
101 seconds /= reldate[i].namelen;
102 if (!string_format(buf, "%ld %s%s %s",
103 seconds, reldate[i].name,
104 seconds > 1 ? "s" : "",
105 now.tv_sec >= date ? "ago" : "ahead"))
106 break;
107 return buf;
111 if (date == DATE_LOCAL) {
112 time_t date = time->sec + time->tz;
113 localtime_r(&date, &tm);
115 else {
116 gmtime_r(&time->sec, &tm);
118 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
122 #define AUTHOR_ENUM(_) \
123 _(AUTHOR, NO), \
124 _(AUTHOR, FULL), \
125 _(AUTHOR, ABBREVIATED)
127 DEFINE_ENUM(author, AUTHOR_ENUM);
129 static const char *
130 get_author_initials(const char *author)
132 static char initials[AUTHOR_COLS * 6 + 1];
133 size_t pos = 0;
134 const char *end = strchr(author, '\0');
136 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
138 memset(initials, 0, sizeof(initials));
139 while (author < end) {
140 unsigned char bytes;
141 size_t i;
143 while (author < end && is_initial_sep(*author))
144 author++;
146 bytes = utf8_char_length(author, end);
147 if (bytes >= sizeof(initials) - 1 - pos)
148 break;
149 while (bytes--) {
150 initials[pos++] = *author++;
153 i = pos;
154 while (author < end && !is_initial_sep(*author)) {
155 bytes = utf8_char_length(author, end);
156 if (bytes >= sizeof(initials) - 1 - i) {
157 while (author < end && !is_initial_sep(*author))
158 author++;
159 break;
161 while (bytes--) {
162 initials[i++] = *author++;
166 initials[i++] = 0;
169 return initials;
172 #define author_trim(cols) (cols == 0 || cols > 5)
174 static const char *
175 mkauthor(const char *text, int cols, enum author author)
177 bool trim = author_trim(cols);
178 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
180 if (author == AUTHOR_NO)
181 return "";
182 if (abbreviate && text)
183 return get_author_initials(text);
184 return text;
187 static const char *
188 mkmode(mode_t mode)
190 if (S_ISDIR(mode))
191 return "drwxr-xr-x";
192 else if (S_ISLNK(mode))
193 return "lrwxrwxrwx";
194 else if (S_ISGITLINK(mode))
195 return "m---------";
196 else if (S_ISREG(mode) && mode & S_IXUSR)
197 return "-rwxr-xr-x";
198 else if (S_ISREG(mode))
199 return "-rw-r--r--";
200 else
201 return "----------";
204 #define FILENAME_ENUM(_) \
205 _(FILENAME, NO), \
206 _(FILENAME, ALWAYS), \
207 _(FILENAME, AUTO)
209 DEFINE_ENUM(filename, FILENAME_ENUM);
211 #define IGNORE_SPACE_ENUM(_) \
212 _(IGNORE_SPACE, NO), \
213 _(IGNORE_SPACE, ALL), \
214 _(IGNORE_SPACE, SOME), \
215 _(IGNORE_SPACE, AT_EOL)
217 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
219 #define COMMIT_ORDER_ENUM(_) \
220 _(COMMIT_ORDER, DEFAULT), \
221 _(COMMIT_ORDER, TOPO), \
222 _(COMMIT_ORDER, DATE), \
223 _(COMMIT_ORDER, REVERSE)
225 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
227 #define VIEW_INFO(_) \
228 _(MAIN, main, ref_head), \
229 _(DIFF, diff, ref_commit), \
230 _(LOG, log, ref_head), \
231 _(TREE, tree, ref_commit), \
232 _(BLOB, blob, ref_blob), \
233 _(BLAME, blame, ref_commit), \
234 _(BRANCH, branch, ref_head), \
235 _(HELP, help, ""), \
236 _(PAGER, pager, ""), \
237 _(STATUS, status, "status"), \
238 _(STAGE, stage, "stage")
240 static struct encoding *
241 get_path_encoding(const char *path, struct encoding *default_encoding)
243 const char *check_attr_argv[] = {
244 "git", "check-attr", "encoding", "--", path, NULL
246 char buf[SIZEOF_STR];
247 char *encoding;
249 /* <path>: encoding: <encoding> */
251 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
252 || !(encoding = strstr(buf, ENCODING_SEP)))
253 return default_encoding;
255 encoding += STRING_SIZE(ENCODING_SEP);
256 if (!strcmp(encoding, ENCODING_UTF8)
257 || !strcmp(encoding, "unspecified")
258 || !strcmp(encoding, "set"))
259 return default_encoding;
261 return encoding_open(encoding);
265 * User requests
268 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
270 #define REQ_INFO \
271 REQ_GROUP("View switching") \
272 VIEW_INFO(VIEW_REQ), \
274 REQ_GROUP("View manipulation") \
275 REQ_(ENTER, "Enter current line and scroll"), \
276 REQ_(NEXT, "Move to next"), \
277 REQ_(PREVIOUS, "Move to previous"), \
278 REQ_(PARENT, "Move to parent"), \
279 REQ_(VIEW_NEXT, "Move focus to next view"), \
280 REQ_(REFRESH, "Reload and refresh"), \
281 REQ_(MAXIMIZE, "Maximize the current view"), \
282 REQ_(VIEW_CLOSE, "Close the current view"), \
283 REQ_(QUIT, "Close all views and quit"), \
285 REQ_GROUP("View specific requests") \
286 REQ_(STATUS_UPDATE, "Update file status"), \
287 REQ_(STATUS_REVERT, "Revert file changes"), \
288 REQ_(STATUS_MERGE, "Merge file using external tool"), \
289 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
290 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
291 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
292 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
294 REQ_GROUP("Cursor navigation") \
295 REQ_(MOVE_UP, "Move cursor one line up"), \
296 REQ_(MOVE_DOWN, "Move cursor one line down"), \
297 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
298 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
299 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
300 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
302 REQ_GROUP("Scrolling") \
303 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
304 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
305 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
306 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
307 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
308 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
309 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
311 REQ_GROUP("Searching") \
312 REQ_(SEARCH, "Search the view"), \
313 REQ_(SEARCH_BACK, "Search backwards in the view"), \
314 REQ_(FIND_NEXT, "Find next search match"), \
315 REQ_(FIND_PREV, "Find previous search match"), \
317 REQ_GROUP("Option manipulation") \
318 REQ_(OPTIONS, "Open option menu"), \
319 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
320 REQ_(TOGGLE_DATE, "Toggle date display"), \
321 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
322 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
323 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
324 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
325 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
326 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
327 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
328 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
329 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
330 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
332 REQ_GROUP("Misc") \
333 REQ_(PROMPT, "Bring up the prompt"), \
334 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
335 REQ_(SHOW_VERSION, "Show version information"), \
336 REQ_(STOP_LOADING, "Stop all loading views"), \
337 REQ_(EDIT, "Open in editor"), \
338 REQ_(NONE, "Do nothing")
341 /* User action requests. */
342 enum request {
343 #define REQ_GROUP(help)
344 #define REQ_(req, help) REQ_##req
346 /* Offset all requests to avoid conflicts with ncurses getch values. */
347 REQ_UNKNOWN = KEY_MAX + 1,
348 REQ_OFFSET,
349 REQ_INFO,
351 /* Internal requests. */
352 REQ_JUMP_COMMIT,
354 #undef REQ_GROUP
355 #undef REQ_
358 struct request_info {
359 enum request request;
360 const char *name;
361 int namelen;
362 const char *help;
365 static const struct request_info req_info[] = {
366 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
367 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
368 REQ_INFO
369 #undef REQ_GROUP
370 #undef REQ_
373 static enum request
374 get_request(const char *name)
376 int namelen = strlen(name);
377 int i;
379 for (i = 0; i < ARRAY_SIZE(req_info); i++)
380 if (enum_equals(req_info[i], name, namelen))
381 return req_info[i].request;
383 return REQ_UNKNOWN;
388 * Options
391 /* Option and state variables. */
392 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
393 static enum date opt_date = DATE_DEFAULT;
394 static enum author opt_author = AUTHOR_FULL;
395 static enum filename opt_filename = FILENAME_AUTO;
396 static bool opt_rev_graph = TRUE;
397 static bool opt_line_number = FALSE;
398 static bool opt_show_refs = TRUE;
399 static bool opt_show_changes = TRUE;
400 static bool opt_untracked_dirs_content = TRUE;
401 static bool opt_read_git_colors = TRUE;
402 static int opt_diff_context = 3;
403 static char opt_diff_context_arg[9] = "";
404 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
405 static char opt_ignore_space_arg[22] = "";
406 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
407 static char opt_commit_order_arg[22] = "";
408 static bool opt_notes = TRUE;
409 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
410 static int opt_num_interval = 5;
411 static double opt_hscroll = 0.50;
412 static double opt_scale_split_view = 2.0 / 3.0;
413 static int opt_tab_size = 8;
414 static int opt_author_cols = AUTHOR_COLS;
415 static int opt_filename_cols = FILENAME_COLS;
416 static char opt_path[SIZEOF_STR] = "";
417 static char opt_file[SIZEOF_STR] = "";
418 static char opt_ref[SIZEOF_REF] = "";
419 static unsigned long opt_goto_line = 0;
420 static char opt_head[SIZEOF_REF] = "";
421 static char opt_remote[SIZEOF_REF] = "";
422 static struct encoding *opt_encoding = NULL;
423 static iconv_t opt_iconv_out = ICONV_NONE;
424 static char opt_search[SIZEOF_STR] = "";
425 static char opt_cdup[SIZEOF_STR] = "";
426 static char opt_prefix[SIZEOF_STR] = "";
427 static char opt_git_dir[SIZEOF_STR] = "";
428 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
429 static char opt_editor[SIZEOF_STR] = "";
430 static FILE *opt_tty = NULL;
431 static const char **opt_diff_argv = NULL;
432 static const char **opt_rev_argv = NULL;
433 static const char **opt_file_argv = NULL;
434 static const char **opt_blame_argv = NULL;
435 static int opt_lineno = 0;
437 #define is_initial_commit() (!get_ref_head())
438 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
439 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
441 static inline void
442 update_diff_context_arg(int diff_context)
444 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
445 string_ncopy(opt_diff_context_arg, "-U3", 3);
448 static inline void
449 update_ignore_space_arg()
451 if (opt_ignore_space == IGNORE_SPACE_ALL) {
452 string_copy(opt_ignore_space_arg, "--ignore-all-space");
453 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
454 string_copy(opt_ignore_space_arg, "--ignore-space-change");
455 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
456 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
457 } else {
458 string_copy(opt_ignore_space_arg, "");
462 static inline void
463 update_commit_order_arg()
465 if (opt_commit_order == COMMIT_ORDER_TOPO) {
466 string_copy(opt_commit_order_arg, "--topo-order");
467 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
468 string_copy(opt_commit_order_arg, "--date-order");
469 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
470 string_copy(opt_commit_order_arg, "--reverse");
471 } else {
472 string_copy(opt_commit_order_arg, "");
476 static inline void
477 update_notes_arg()
479 if (opt_notes) {
480 string_copy(opt_notes_arg, "--show-notes");
481 } else {
482 /* Notes are disabled by default when passing --pretty args. */
483 string_copy(opt_notes_arg, "");
488 * Line-oriented content detection.
491 #define LINE_INFO \
492 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
493 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
494 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
495 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
496 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
497 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
498 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
499 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
500 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
506 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
507 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
508 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
509 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
510 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
511 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
512 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
515 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
516 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
517 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
518 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
519 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
520 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
521 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
525 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
526 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
527 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
528 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
529 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
530 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
531 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
532 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
533 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
534 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
535 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
536 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
537 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
538 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
539 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
540 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
541 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
542 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
543 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
544 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
545 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
546 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
547 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
548 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
549 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
550 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
551 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
553 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
554 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
555 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
556 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
557 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
558 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
559 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
560 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
561 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
562 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
563 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
565 enum line_type {
566 #define LINE(type, line, fg, bg, attr) \
567 LINE_##type
568 LINE_INFO,
569 LINE_NONE
570 #undef LINE
573 struct line_info {
574 const char *name; /* Option name. */
575 int namelen; /* Size of option name. */
576 const char *line; /* The start of line to match. */
577 int linelen; /* Size of string to match. */
578 int fg, bg, attr; /* Color and text attributes for the lines. */
579 int color_pair;
582 static struct line_info line_info[] = {
583 #define LINE(type, line, fg, bg, attr) \
584 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
585 LINE_INFO
586 #undef LINE
589 static struct line_info **color_pair;
590 static size_t color_pairs;
592 static struct line_info *custom_color;
593 static size_t custom_colors;
595 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
596 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
598 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
599 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
601 /* Color IDs must be 1 or higher. [GH #15] */
602 #define COLOR_ID(line_type) ((line_type) + 1)
604 static enum line_type
605 get_line_type(const char *line)
607 int linelen = strlen(line);
608 enum line_type type;
610 for (type = 0; type < custom_colors; type++)
611 /* Case insensitive search matches Signed-off-by lines better. */
612 if (linelen >= custom_color[type].linelen &&
613 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
614 return TO_CUSTOM_COLOR_TYPE(type);
616 for (type = 0; type < ARRAY_SIZE(line_info); type++)
617 /* Case insensitive search matches Signed-off-by lines better. */
618 if (linelen >= line_info[type].linelen &&
619 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
620 return type;
622 return LINE_DEFAULT;
625 static enum line_type
626 get_line_type_from_ref(const struct ref *ref)
628 if (ref->head)
629 return LINE_MAIN_HEAD;
630 else if (ref->ltag)
631 return LINE_MAIN_LOCAL_TAG;
632 else if (ref->tag)
633 return LINE_MAIN_TAG;
634 else if (ref->tracked)
635 return LINE_MAIN_TRACKED;
636 else if (ref->remote)
637 return LINE_MAIN_REMOTE;
638 else if (ref->replace)
639 return LINE_MAIN_REPLACE;
641 return LINE_MAIN_REF;
644 static inline struct line_info *
645 get_line(enum line_type type)
647 if (type > LINE_NONE) {
648 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
649 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
650 } else {
651 assert(type < ARRAY_SIZE(line_info));
652 return &line_info[type];
656 static inline int
657 get_line_color(enum line_type type)
659 return COLOR_ID(get_line(type)->color_pair);
662 static inline int
663 get_line_attr(enum line_type type)
665 struct line_info *info = get_line(type);
667 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
670 static struct line_info *
671 get_line_info(const char *name)
673 size_t namelen = strlen(name);
674 enum line_type type;
676 for (type = 0; type < ARRAY_SIZE(line_info); type++)
677 if (enum_equals(line_info[type], name, namelen))
678 return &line_info[type];
680 return NULL;
683 static struct line_info *
684 add_custom_color(const char *quoted_line)
686 struct line_info *info;
687 char *line;
688 size_t linelen;
690 if (!realloc_custom_color(&custom_color, custom_colors, 1))
691 die("Failed to alloc custom line info");
693 linelen = strlen(quoted_line) - 1;
694 line = malloc(linelen);
695 if (!line)
696 return NULL;
698 strncpy(line, quoted_line + 1, linelen);
699 line[linelen - 1] = 0;
701 info = &custom_color[custom_colors++];
702 info->name = info->line = line;
703 info->namelen = info->linelen = strlen(line);
705 return info;
708 static void
709 init_line_info_color_pair(struct line_info *info, enum line_type type,
710 int default_bg, int default_fg)
712 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
713 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
714 int i;
716 for (i = 0; i < color_pairs; i++) {
717 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
718 info->color_pair = i;
719 return;
723 if (!realloc_color_pair(&color_pair, color_pairs, 1))
724 die("Failed to alloc color pair");
726 color_pair[color_pairs] = info;
727 info->color_pair = color_pairs++;
728 init_pair(COLOR_ID(info->color_pair), fg, bg);
731 static void
732 init_colors(void)
734 int default_bg = line_info[LINE_DEFAULT].bg;
735 int default_fg = line_info[LINE_DEFAULT].fg;
736 enum line_type type;
738 start_color();
740 if (assume_default_colors(default_fg, default_bg) == ERR) {
741 default_bg = COLOR_BLACK;
742 default_fg = COLOR_WHITE;
745 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
746 struct line_info *info = &line_info[type];
748 init_line_info_color_pair(info, type, default_bg, default_fg);
751 for (type = 0; type < custom_colors; type++) {
752 struct line_info *info = &custom_color[type];
754 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
755 default_bg, default_fg);
759 struct line {
760 enum line_type type;
762 /* State flags */
763 unsigned int selected:1;
764 unsigned int dirty:1;
765 unsigned int cleareol:1;
766 unsigned int dont_free:1;
767 unsigned int other:16;
769 void *data; /* User data */
774 * Keys
777 struct keybinding {
778 int alias;
779 enum request request;
782 static struct keybinding default_keybindings[] = {
783 /* View switching */
784 { 'm', REQ_VIEW_MAIN },
785 { 'd', REQ_VIEW_DIFF },
786 { 'l', REQ_VIEW_LOG },
787 { 't', REQ_VIEW_TREE },
788 { 'f', REQ_VIEW_BLOB },
789 { 'B', REQ_VIEW_BLAME },
790 { 'H', REQ_VIEW_BRANCH },
791 { 'p', REQ_VIEW_PAGER },
792 { 'h', REQ_VIEW_HELP },
793 { 'S', REQ_VIEW_STATUS },
794 { 'c', REQ_VIEW_STAGE },
796 /* View manipulation */
797 { 'q', REQ_VIEW_CLOSE },
798 { KEY_TAB, REQ_VIEW_NEXT },
799 { KEY_RETURN, REQ_ENTER },
800 { KEY_UP, REQ_PREVIOUS },
801 { KEY_CTL('P'), REQ_PREVIOUS },
802 { KEY_DOWN, REQ_NEXT },
803 { KEY_CTL('N'), REQ_NEXT },
804 { 'R', REQ_REFRESH },
805 { KEY_F(5), REQ_REFRESH },
806 { 'O', REQ_MAXIMIZE },
807 { ',', REQ_PARENT },
809 /* View specific */
810 { 'u', REQ_STATUS_UPDATE },
811 { '!', REQ_STATUS_REVERT },
812 { 'M', REQ_STATUS_MERGE },
813 { '1', REQ_STAGE_UPDATE_LINE },
814 { '@', REQ_STAGE_NEXT },
815 { '[', REQ_DIFF_CONTEXT_DOWN },
816 { ']', REQ_DIFF_CONTEXT_UP },
818 /* Cursor navigation */
819 { 'k', REQ_MOVE_UP },
820 { 'j', REQ_MOVE_DOWN },
821 { KEY_HOME, REQ_MOVE_FIRST_LINE },
822 { KEY_END, REQ_MOVE_LAST_LINE },
823 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
824 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
825 { ' ', REQ_MOVE_PAGE_DOWN },
826 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
827 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
828 { 'b', REQ_MOVE_PAGE_UP },
829 { '-', REQ_MOVE_PAGE_UP },
831 /* Scrolling */
832 { '|', REQ_SCROLL_FIRST_COL },
833 { KEY_LEFT, REQ_SCROLL_LEFT },
834 { KEY_RIGHT, REQ_SCROLL_RIGHT },
835 { KEY_IC, REQ_SCROLL_LINE_UP },
836 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
837 { KEY_DC, REQ_SCROLL_LINE_DOWN },
838 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
839 { 'w', REQ_SCROLL_PAGE_UP },
840 { 's', REQ_SCROLL_PAGE_DOWN },
842 /* Searching */
843 { '/', REQ_SEARCH },
844 { '?', REQ_SEARCH_BACK },
845 { 'n', REQ_FIND_NEXT },
846 { 'N', REQ_FIND_PREV },
848 /* Misc */
849 { 'Q', REQ_QUIT },
850 { 'z', REQ_STOP_LOADING },
851 { 'v', REQ_SHOW_VERSION },
852 { 'r', REQ_SCREEN_REDRAW },
853 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
854 { 'o', REQ_OPTIONS },
855 { '.', REQ_TOGGLE_LINENO },
856 { 'D', REQ_TOGGLE_DATE },
857 { 'A', REQ_TOGGLE_AUTHOR },
858 { 'g', REQ_TOGGLE_REV_GRAPH },
859 { '~', REQ_TOGGLE_GRAPHIC },
860 { '#', REQ_TOGGLE_FILENAME },
861 { 'F', REQ_TOGGLE_REFS },
862 { 'I', REQ_TOGGLE_SORT_ORDER },
863 { 'i', REQ_TOGGLE_SORT_FIELD },
864 { 'W', REQ_TOGGLE_IGNORE_SPACE },
865 { ':', REQ_PROMPT },
866 { 'e', REQ_EDIT },
869 struct keymap {
870 const char *name;
871 struct keymap *next;
872 struct keybinding *data;
873 size_t size;
874 bool hidden;
877 static struct keymap generic_keymap = { "generic" };
878 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
880 static struct keymap *keymaps = &generic_keymap;
882 static void
883 add_keymap(struct keymap *keymap)
885 keymap->next = keymaps;
886 keymaps = keymap;
889 static struct keymap *
890 get_keymap(const char *name)
892 struct keymap *keymap = keymaps;
894 while (keymap) {
895 if (!strcasecmp(keymap->name, name))
896 return keymap;
897 keymap = keymap->next;
900 return NULL;
904 static void
905 add_keybinding(struct keymap *table, enum request request, int key)
907 size_t i;
909 for (i = 0; i < table->size; i++) {
910 if (table->data[i].alias == key) {
911 table->data[i].request = request;
912 return;
916 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
917 if (!table->data)
918 die("Failed to allocate keybinding");
919 table->data[table->size].alias = key;
920 table->data[table->size++].request = request;
922 if (request == REQ_NONE && is_generic_keymap(table)) {
923 int i;
925 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
926 if (default_keybindings[i].alias == key)
927 default_keybindings[i].request = REQ_NONE;
931 /* Looks for a key binding first in the given map, then in the generic map, and
932 * lastly in the default keybindings. */
933 static enum request
934 get_keybinding(struct keymap *keymap, int key)
936 size_t i;
938 for (i = 0; i < keymap->size; i++)
939 if (keymap->data[i].alias == key)
940 return keymap->data[i].request;
942 for (i = 0; i < generic_keymap.size; i++)
943 if (generic_keymap.data[i].alias == key)
944 return generic_keymap.data[i].request;
946 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
947 if (default_keybindings[i].alias == key)
948 return default_keybindings[i].request;
950 return (enum request) key;
954 struct key {
955 const char *name;
956 int value;
959 static const struct key key_table[] = {
960 { "Enter", KEY_RETURN },
961 { "Space", ' ' },
962 { "Backspace", KEY_BACKSPACE },
963 { "Tab", KEY_TAB },
964 { "Escape", KEY_ESC },
965 { "Left", KEY_LEFT },
966 { "Right", KEY_RIGHT },
967 { "Up", KEY_UP },
968 { "Down", KEY_DOWN },
969 { "Insert", KEY_IC },
970 { "Delete", KEY_DC },
971 { "Hash", '#' },
972 { "Home", KEY_HOME },
973 { "End", KEY_END },
974 { "PageUp", KEY_PPAGE },
975 { "PageDown", KEY_NPAGE },
976 { "F1", KEY_F(1) },
977 { "F2", KEY_F(2) },
978 { "F3", KEY_F(3) },
979 { "F4", KEY_F(4) },
980 { "F5", KEY_F(5) },
981 { "F6", KEY_F(6) },
982 { "F7", KEY_F(7) },
983 { "F8", KEY_F(8) },
984 { "F9", KEY_F(9) },
985 { "F10", KEY_F(10) },
986 { "F11", KEY_F(11) },
987 { "F12", KEY_F(12) },
990 static int
991 get_key_value(const char *name)
993 int i;
995 for (i = 0; i < ARRAY_SIZE(key_table); i++)
996 if (!strcasecmp(key_table[i].name, name))
997 return key_table[i].value;
999 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1000 return (int)name[1] & 0x1f;
1001 if (strlen(name) == 1 && isprint(*name))
1002 return (int) *name;
1003 return ERR;
1006 static const char *
1007 get_key_name(int key_value)
1009 static char key_char[] = "'X'\0";
1010 const char *seq = NULL;
1011 int key;
1013 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1014 if (key_table[key].value == key_value)
1015 seq = key_table[key].name;
1017 if (seq == NULL && key_value < 0x7f) {
1018 char *s = key_char + 1;
1020 if (key_value >= 0x20) {
1021 *s++ = key_value;
1022 } else {
1023 *s++ = '^';
1024 *s++ = 0x40 | (key_value & 0x1f);
1026 *s++ = '\'';
1027 *s++ = '\0';
1028 seq = key_char;
1031 return seq ? seq : "(no key)";
1034 static bool
1035 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1037 const char *sep = *pos > 0 ? ", " : "";
1038 const char *keyname = get_key_name(keybinding->alias);
1040 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1043 static bool
1044 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1045 struct keymap *keymap, bool all)
1047 int i;
1049 for (i = 0; i < keymap->size; i++) {
1050 if (keymap->data[i].request == request) {
1051 if (!append_key(buf, pos, &keymap->data[i]))
1052 return FALSE;
1053 if (!all)
1054 break;
1058 return TRUE;
1061 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1063 static const char *
1064 get_keys(struct keymap *keymap, enum request request, bool all)
1066 static char buf[BUFSIZ];
1067 size_t pos = 0;
1068 int i;
1070 buf[pos] = 0;
1072 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1073 return "Too many keybindings!";
1074 if (pos > 0 && !all)
1075 return buf;
1077 if (!is_generic_keymap(keymap)) {
1078 /* Only the generic keymap includes the default keybindings when
1079 * listing all keys. */
1080 if (all)
1081 return buf;
1083 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1084 return "Too many keybindings!";
1085 if (pos)
1086 return buf;
1089 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1090 if (default_keybindings[i].request == request) {
1091 if (!append_key(buf, &pos, &default_keybindings[i]))
1092 return "Too many keybindings!";
1093 if (!all)
1094 return buf;
1098 return buf;
1101 struct run_request {
1102 struct keymap *keymap;
1103 int key;
1104 const char **argv;
1105 bool silent;
1108 static struct run_request *run_request;
1109 static size_t run_requests;
1111 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1113 static bool
1114 add_run_request(struct keymap *keymap, int key, const char **argv, bool silent, bool force)
1116 struct run_request *req;
1118 if (!force && get_keybinding(keymap, key) != key)
1119 return TRUE;
1121 if (!realloc_run_requests(&run_request, run_requests, 1))
1122 return FALSE;
1124 if (!argv_copy(&run_request[run_requests].argv, argv))
1125 return FALSE;
1127 req = &run_request[run_requests++];
1128 req->silent = silent;
1129 req->keymap = keymap;
1130 req->key = key;
1132 add_keybinding(keymap, REQ_NONE + run_requests, key);
1133 return TRUE;
1136 static struct run_request *
1137 get_run_request(enum request request)
1139 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1140 return NULL;
1141 return &run_request[request - REQ_NONE - 1];
1144 static void
1145 add_builtin_run_requests(void)
1147 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1148 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1149 const char *commit[] = { "git", "commit", NULL };
1150 const char *gc[] = { "git", "gc", NULL };
1152 add_run_request(get_keymap("main"), 'C', cherry_pick, FALSE, FALSE);
1153 add_run_request(get_keymap("status"), 'C', commit, FALSE, FALSE);
1154 add_run_request(get_keymap("branch"), 'C', checkout, FALSE, FALSE);
1155 add_run_request(get_keymap("generic"), 'G', gc, FALSE, FALSE);
1159 * User config file handling.
1162 #define OPT_ERR_INFO \
1163 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1164 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1165 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1166 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1167 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1168 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1169 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1170 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1171 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1172 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1173 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1174 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1175 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1176 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1177 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1178 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1179 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1180 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1181 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1183 enum option_code {
1184 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1185 OPT_ERR_INFO
1186 #undef OPT_ERR_
1187 OPT_OK
1190 static const char *option_errors[] = {
1191 #define OPT_ERR_(name, msg) msg
1192 OPT_ERR_INFO
1193 #undef OPT_ERR_
1196 static const struct enum_map color_map[] = {
1197 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1198 COLOR_MAP(DEFAULT),
1199 COLOR_MAP(BLACK),
1200 COLOR_MAP(BLUE),
1201 COLOR_MAP(CYAN),
1202 COLOR_MAP(GREEN),
1203 COLOR_MAP(MAGENTA),
1204 COLOR_MAP(RED),
1205 COLOR_MAP(WHITE),
1206 COLOR_MAP(YELLOW),
1209 static const struct enum_map attr_map[] = {
1210 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1211 ATTR_MAP(NORMAL),
1212 ATTR_MAP(BLINK),
1213 ATTR_MAP(BOLD),
1214 ATTR_MAP(DIM),
1215 ATTR_MAP(REVERSE),
1216 ATTR_MAP(STANDOUT),
1217 ATTR_MAP(UNDERLINE),
1220 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1222 static enum option_code
1223 parse_step(double *opt, const char *arg)
1225 *opt = atoi(arg);
1226 if (!strchr(arg, '%'))
1227 return OPT_OK;
1229 /* "Shift down" so 100% and 1 does not conflict. */
1230 *opt = (*opt - 1) / 100;
1231 if (*opt >= 1.0) {
1232 *opt = 0.99;
1233 return OPT_ERR_INVALID_STEP_VALUE;
1235 if (*opt < 0.0) {
1236 *opt = 1;
1237 return OPT_ERR_INVALID_STEP_VALUE;
1239 return OPT_OK;
1242 static enum option_code
1243 parse_int(int *opt, const char *arg, int min, int max)
1245 int value = atoi(arg);
1247 if (min <= value && value <= max) {
1248 *opt = value;
1249 return OPT_OK;
1252 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1255 static bool
1256 set_color(int *color, const char *name)
1258 if (map_enum(color, color_map, name))
1259 return TRUE;
1260 if (!prefixcmp(name, "color"))
1261 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1262 return FALSE;
1265 /* Wants: object fgcolor bgcolor [attribute] */
1266 static enum option_code
1267 option_color_command(int argc, const char *argv[])
1269 struct line_info *info;
1271 if (argc < 3)
1272 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1274 if (*argv[0] == '"' || *argv[0] == '\'') {
1275 info = add_custom_color(argv[0]);
1276 } else {
1277 info = get_line_info(argv[0]);
1279 if (!info) {
1280 static const struct enum_map obsolete[] = {
1281 ENUM_MAP("main-delim", LINE_DELIMITER),
1282 ENUM_MAP("main-date", LINE_DATE),
1283 ENUM_MAP("main-author", LINE_AUTHOR),
1285 int index;
1287 if (!map_enum(&index, obsolete, argv[0]))
1288 return OPT_ERR_UNKNOWN_COLOR_NAME;
1289 info = &line_info[index];
1292 if (!set_color(&info->fg, argv[1]) ||
1293 !set_color(&info->bg, argv[2]))
1294 return OPT_ERR_UNKNOWN_COLOR;
1296 info->attr = 0;
1297 while (argc-- > 3) {
1298 int attr;
1300 if (!set_attribute(&attr, argv[argc]))
1301 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1302 info->attr |= attr;
1305 return OPT_OK;
1308 static enum option_code
1309 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1311 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1312 ? TRUE : FALSE;
1313 if (matched)
1314 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1315 return OPT_OK;
1318 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1320 static enum option_code
1321 parse_enum_do(unsigned int *opt, const char *arg,
1322 const struct enum_map *map, size_t map_size)
1324 bool is_true;
1326 assert(map_size > 1);
1328 if (map_enum_do(map, map_size, (int *) opt, arg))
1329 return OPT_OK;
1331 parse_bool(&is_true, arg);
1332 *opt = is_true ? map[1].value : map[0].value;
1333 return OPT_OK;
1336 #define parse_enum(opt, arg, map) \
1337 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1339 static enum option_code
1340 parse_string(char *opt, const char *arg, size_t optsize)
1342 int arglen = strlen(arg);
1344 switch (arg[0]) {
1345 case '\"':
1346 case '\'':
1347 if (arglen == 1 || arg[arglen - 1] != arg[0])
1348 return OPT_ERR_UNMATCHED_QUOTATION;
1349 arg += 1; arglen -= 2;
1350 default:
1351 string_ncopy_do(opt, optsize, arg, arglen);
1352 return OPT_OK;
1356 static enum option_code
1357 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1359 char buf[SIZEOF_STR];
1360 enum option_code code = parse_string(buf, arg, sizeof(buf));
1362 if (code == OPT_OK) {
1363 struct encoding *encoding = *encoding_ref;
1365 if (encoding && !priority)
1366 return code;
1367 encoding = encoding_open(buf);
1368 if (encoding)
1369 *encoding_ref = encoding;
1372 return code;
1375 static enum option_code
1376 parse_args(const char ***args, const char *argv[])
1378 if (*args == NULL && !argv_copy(args, argv))
1379 return OPT_ERR_OUT_OF_MEMORY;
1380 return OPT_OK;
1383 /* Wants: name = value */
1384 static enum option_code
1385 option_set_command(int argc, const char *argv[])
1387 if (argc < 3)
1388 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1390 if (strcmp(argv[1], "="))
1391 return OPT_ERR_NO_VALUE_ASSIGNED;
1393 if (!strcmp(argv[0], "blame-options"))
1394 return parse_args(&opt_blame_argv, argv + 2);
1396 if (argc != 3)
1397 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1399 if (!strcmp(argv[0], "show-author"))
1400 return parse_enum(&opt_author, argv[2], author_map);
1402 if (!strcmp(argv[0], "show-date"))
1403 return parse_enum(&opt_date, argv[2], date_map);
1405 if (!strcmp(argv[0], "show-rev-graph"))
1406 return parse_bool(&opt_rev_graph, argv[2]);
1408 if (!strcmp(argv[0], "show-refs"))
1409 return parse_bool(&opt_show_refs, argv[2]);
1411 if (!strcmp(argv[0], "show-changes"))
1412 return parse_bool(&opt_show_changes, argv[2]);
1414 if (!strcmp(argv[0], "show-notes")) {
1415 bool matched = FALSE;
1416 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1418 if (res == OPT_OK && matched) {
1419 update_notes_arg();
1420 return res;
1423 opt_notes = TRUE;
1424 strcpy(opt_notes_arg, "--show-notes=");
1425 res = parse_string(opt_notes_arg + 8, argv[2],
1426 sizeof(opt_notes_arg) - 8);
1427 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1428 opt_notes_arg[7] = '\0';
1429 return res;
1432 if (!strcmp(argv[0], "show-line-numbers"))
1433 return parse_bool(&opt_line_number, argv[2]);
1435 if (!strcmp(argv[0], "line-graphics"))
1436 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1438 if (!strcmp(argv[0], "line-number-interval"))
1439 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1441 if (!strcmp(argv[0], "author-width"))
1442 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1444 if (!strcmp(argv[0], "filename-width"))
1445 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1447 if (!strcmp(argv[0], "show-filename"))
1448 return parse_enum(&opt_filename, argv[2], filename_map);
1450 if (!strcmp(argv[0], "horizontal-scroll"))
1451 return parse_step(&opt_hscroll, argv[2]);
1453 if (!strcmp(argv[0], "split-view-height"))
1454 return parse_step(&opt_scale_split_view, argv[2]);
1456 if (!strcmp(argv[0], "tab-size"))
1457 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1459 if (!strcmp(argv[0], "diff-context")) {
1460 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1462 if (code == OPT_OK)
1463 update_diff_context_arg(opt_diff_context);
1464 return code;
1467 if (!strcmp(argv[0], "ignore-space")) {
1468 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1470 if (code == OPT_OK)
1471 update_ignore_space_arg();
1472 return code;
1475 if (!strcmp(argv[0], "commit-order")) {
1476 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1478 if (code == OPT_OK)
1479 update_commit_order_arg();
1480 return code;
1483 if (!strcmp(argv[0], "status-untracked-dirs"))
1484 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1486 if (!strcmp(argv[0], "use-git-colors"))
1487 return parse_bool(&opt_read_git_colors, argv[2]);
1489 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1492 /* Wants: mode request key */
1493 static enum option_code
1494 option_bind_command(int argc, const char *argv[])
1496 enum request request;
1497 struct keymap *keymap;
1498 int key;
1500 if (argc < 3)
1501 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1503 if (!(keymap = get_keymap(argv[0])))
1504 return OPT_ERR_UNKNOWN_KEY_MAP;
1506 key = get_key_value(argv[1]);
1507 if (key == ERR)
1508 return OPT_ERR_UNKNOWN_KEY;
1510 request = get_request(argv[2]);
1511 if (request == REQ_UNKNOWN) {
1512 static const struct enum_map obsolete[] = {
1513 ENUM_MAP("cherry-pick", REQ_NONE),
1514 ENUM_MAP("screen-resize", REQ_NONE),
1515 ENUM_MAP("tree-parent", REQ_PARENT),
1517 int alias;
1519 if (map_enum(&alias, obsolete, argv[2])) {
1520 if (alias != REQ_NONE)
1521 add_keybinding(keymap, alias, key);
1522 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1525 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1526 bool silent = *argv[2] == '@';
1528 if (silent)
1529 argv[2]++;
1530 return add_run_request(keymap, key, argv + 2, silent, TRUE)
1531 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1533 if (request == REQ_UNKNOWN)
1534 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1536 add_keybinding(keymap, request, key);
1538 return OPT_OK;
1542 static enum option_code load_option_file(const char *path);
1544 static enum option_code
1545 option_source_command(int argc, const char *argv[])
1547 if (argc < 1)
1548 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1550 return load_option_file(argv[0]);
1553 static enum option_code
1554 set_option(const char *opt, char *value)
1556 const char *argv[SIZEOF_ARG];
1557 int argc = 0;
1559 if (!argv_from_string(argv, &argc, value))
1560 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1562 if (!strcmp(opt, "color"))
1563 return option_color_command(argc, argv);
1565 if (!strcmp(opt, "set"))
1566 return option_set_command(argc, argv);
1568 if (!strcmp(opt, "bind"))
1569 return option_bind_command(argc, argv);
1571 if (!strcmp(opt, "source"))
1572 return option_source_command(argc, argv);
1574 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1577 struct config_state {
1578 const char *path;
1579 int lineno;
1580 bool errors;
1583 static int
1584 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1586 struct config_state *config = data;
1587 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1589 config->lineno++;
1591 /* Check for comment markers, since read_properties() will
1592 * only ensure opt and value are split at first " \t". */
1593 optlen = strcspn(opt, "#");
1594 if (optlen == 0)
1595 return OK;
1597 if (opt[optlen] == 0) {
1598 /* Look for comment endings in the value. */
1599 size_t len = strcspn(value, "#");
1601 if (len < valuelen) {
1602 valuelen = len;
1603 value[valuelen] = 0;
1606 status = set_option(opt, value);
1609 if (status != OPT_OK) {
1610 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1611 option_errors[status], (int) optlen, opt);
1612 config->errors = TRUE;
1615 /* Always keep going if errors are encountered. */
1616 return OK;
1619 static enum option_code
1620 load_option_file(const char *path)
1622 struct config_state config = { path, 0, FALSE };
1623 struct io io;
1625 /* Do not read configuration from stdin if set to "" */
1626 if (!path || !strlen(path))
1627 return OPT_OK;
1629 /* It's OK that the file doesn't exist. */
1630 if (!io_open(&io, "%s", path))
1631 return OPT_ERR_FILE_DOES_NOT_EXIST;
1633 if (io_load(&io, " \t", read_option, &config) == ERR ||
1634 config.errors == TRUE)
1635 warn("Errors while loading %s.", path);
1636 return OPT_OK;
1639 static int
1640 load_options(void)
1642 const char *home = getenv("HOME");
1643 const char *tigrc_user = getenv("TIGRC_USER");
1644 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1645 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1646 char buf[SIZEOF_STR];
1648 if (!tigrc_system)
1649 tigrc_system = SYSCONFDIR "/tigrc";
1650 load_option_file(tigrc_system);
1652 if (!tigrc_user) {
1653 if (!home || !string_format(buf, "%s/.tigrc", home))
1654 return ERR;
1655 tigrc_user = buf;
1657 load_option_file(tigrc_user);
1659 /* Add _after_ loading config files to avoid adding run requests
1660 * that conflict with keybindings. */
1661 add_builtin_run_requests();
1663 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1664 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1665 int argc = 0;
1667 if (!string_format(buf, "%s", tig_diff_opts) ||
1668 !argv_from_string(diff_opts, &argc, buf))
1669 die("TIG_DIFF_OPTS contains too many arguments");
1670 else if (!argv_copy(&opt_diff_argv, diff_opts))
1671 die("Failed to format TIG_DIFF_OPTS arguments");
1674 return OK;
1679 * The viewer
1682 struct view;
1683 struct view_ops;
1685 /* The display array of active views and the index of the current view. */
1686 static struct view *display[2];
1687 static WINDOW *display_win[2];
1688 static WINDOW *display_title[2];
1689 static unsigned int current_view;
1691 #define foreach_displayed_view(view, i) \
1692 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1694 #define displayed_views() (display[1] != NULL ? 2 : 1)
1696 /* Current head and commit ID */
1697 static char ref_blob[SIZEOF_REF] = "";
1698 static char ref_commit[SIZEOF_REF] = "HEAD";
1699 static char ref_head[SIZEOF_REF] = "HEAD";
1700 static char ref_branch[SIZEOF_REF] = "";
1702 enum view_flag {
1703 VIEW_NO_FLAGS = 0,
1704 VIEW_ALWAYS_LINENO = 1 << 0,
1705 VIEW_CUSTOM_STATUS = 1 << 1,
1706 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1707 VIEW_ADD_PAGER_REFS = 1 << 3,
1708 VIEW_OPEN_DIFF = 1 << 4,
1709 VIEW_NO_REF = 1 << 5,
1710 VIEW_NO_GIT_DIR = 1 << 6,
1711 VIEW_DIFF_LIKE = 1 << 7,
1714 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1716 struct position {
1717 unsigned long offset; /* Offset of the window top */
1718 unsigned long col; /* Offset from the window side. */
1719 unsigned long lineno; /* Current line number */
1722 struct view {
1723 const char *name; /* View name */
1724 const char *id; /* Points to either of ref_{head,commit,blob} */
1726 struct view_ops *ops; /* View operations */
1728 char ref[SIZEOF_REF]; /* Hovered commit reference */
1729 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1731 int height, width; /* The width and height of the main window */
1732 WINDOW *win; /* The main window */
1734 /* Navigation */
1735 struct position pos; /* Current position. */
1736 struct position prev_pos; /* Previous position. */
1738 /* Searching */
1739 char grep[SIZEOF_STR]; /* Search string */
1740 regex_t *regex; /* Pre-compiled regexp */
1742 /* If non-NULL, points to the view that opened this view. If this view
1743 * is closed tig will switch back to the parent view. */
1744 struct view *parent;
1745 struct view *prev;
1747 /* Buffering */
1748 size_t lines; /* Total number of lines */
1749 struct line *line; /* Line index */
1750 unsigned int digits; /* Number of digits in the lines member. */
1751 unsigned int lineoffset;/* Offset from where to count line objects. */
1753 /* Drawing */
1754 struct line *curline; /* Line currently being drawn. */
1755 enum line_type curtype; /* Attribute currently used for drawing. */
1756 unsigned long col; /* Column when drawing. */
1757 bool has_scrolled; /* View was scrolled. */
1759 /* Loading */
1760 const char **argv; /* Shell command arguments. */
1761 const char *dir; /* Directory from which to execute. */
1762 struct io io;
1763 struct io *pipe;
1764 time_t start_time;
1765 time_t update_secs;
1766 struct encoding *encoding;
1768 /* Private data */
1769 void *private;
1772 enum open_flags {
1773 OPEN_DEFAULT = 0, /* Use default view switching. */
1774 OPEN_SPLIT = 1, /* Split current view. */
1775 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1776 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1777 OPEN_PREPARED = 32, /* Open already prepared command. */
1778 OPEN_EXTRA = 64, /* Open extra data from command. */
1781 struct view_ops {
1782 /* What type of content being displayed. Used in the title bar. */
1783 const char *type;
1784 /* What keymap does this view have */
1785 struct keymap keymap;
1786 /* Flags to control the view behavior. */
1787 enum view_flag flags;
1788 /* Size of private data. */
1789 size_t private_size;
1790 /* Open and reads in all view content. */
1791 bool (*open)(struct view *view, enum open_flags flags);
1792 /* Read one line; updates view->line. */
1793 bool (*read)(struct view *view, char *data);
1794 /* Draw one line; @lineno must be < view->height. */
1795 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1796 /* Depending on view handle a special requests. */
1797 enum request (*request)(struct view *view, enum request request, struct line *line);
1798 /* Search for regexp in a line. */
1799 bool (*grep)(struct view *view, struct line *line);
1800 /* Select line */
1801 void (*select)(struct view *view, struct line *line);
1804 #define VIEW_OPS(id, name, ref) name##_ops
1805 static struct view_ops VIEW_INFO(VIEW_OPS);
1807 static struct view views[] = {
1808 #define VIEW_DATA(id, name, ref) \
1809 { #name, ref, &name##_ops }
1810 VIEW_INFO(VIEW_DATA)
1813 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1815 #define foreach_view(view, i) \
1816 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1818 #define view_is_displayed(view) \
1819 (view == display[0] || view == display[1])
1821 #define view_has_line(view, line_) \
1822 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1824 static enum request
1825 view_request(struct view *view, enum request request)
1827 if (!view || !view->lines)
1828 return request;
1829 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1833 * View drawing.
1836 static inline void
1837 set_view_attr(struct view *view, enum line_type type)
1839 if (!view->curline->selected && view->curtype != type) {
1840 (void) wattrset(view->win, get_line_attr(type));
1841 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1842 view->curtype = type;
1846 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1848 static bool
1849 draw_chars(struct view *view, enum line_type type, const char *string,
1850 int max_len, bool use_tilde)
1852 static char out_buffer[BUFSIZ * 2];
1853 int len = 0;
1854 int col = 0;
1855 int trimmed = FALSE;
1856 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1858 if (max_len <= 0)
1859 return VIEW_MAX_LEN(view) <= 0;
1861 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1863 set_view_attr(view, type);
1864 if (len > 0) {
1865 if (opt_iconv_out != ICONV_NONE) {
1866 size_t inlen = len + 1;
1867 char *instr = calloc(1, inlen);
1868 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1869 if (!instr)
1870 return VIEW_MAX_LEN(view) <= 0;
1872 strncpy(instr, string, len);
1874 char *outbuf = out_buffer;
1875 size_t outlen = sizeof(out_buffer);
1877 size_t ret;
1879 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1880 if (ret != (size_t) -1) {
1881 string = out_buffer;
1882 len = sizeof(out_buffer) - outlen;
1884 free(instr);
1887 waddnstr(view->win, string, len);
1889 if (trimmed && use_tilde) {
1890 set_view_attr(view, LINE_DELIMITER);
1891 waddch(view->win, '~');
1892 col++;
1896 view->col += col;
1897 return VIEW_MAX_LEN(view) <= 0;
1900 static bool
1901 draw_space(struct view *view, enum line_type type, int max, int spaces)
1903 static char space[] = " ";
1905 spaces = MIN(max, spaces);
1907 while (spaces > 0) {
1908 int len = MIN(spaces, sizeof(space) - 1);
1910 if (draw_chars(view, type, space, len, FALSE))
1911 return TRUE;
1912 spaces -= len;
1915 return VIEW_MAX_LEN(view) <= 0;
1918 static bool
1919 draw_text(struct view *view, enum line_type type, const char *string)
1921 static char text[SIZEOF_STR];
1923 do {
1924 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1926 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1927 return TRUE;
1928 string += pos;
1929 } while (*string);
1931 return VIEW_MAX_LEN(view) <= 0;
1934 static bool
1935 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1937 char text[SIZEOF_STR];
1938 int retval;
1940 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1941 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1944 static bool
1945 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1947 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1948 int max = VIEW_MAX_LEN(view);
1949 int i;
1951 if (max < size)
1952 size = max;
1954 set_view_attr(view, type);
1955 /* Using waddch() instead of waddnstr() ensures that
1956 * they'll be rendered correctly for the cursor line. */
1957 for (i = skip; i < size; i++)
1958 waddch(view->win, graphic[i]);
1960 view->col += size;
1961 if (separator) {
1962 if (size < max && skip <= size)
1963 waddch(view->win, ' ');
1964 view->col++;
1967 return VIEW_MAX_LEN(view) <= 0;
1970 static bool
1971 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1973 int max = MIN(VIEW_MAX_LEN(view), len);
1974 int col = view->col;
1976 if (!text)
1977 return draw_space(view, type, max, max);
1979 return draw_chars(view, type, text, max - 1, trim)
1980 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1983 static bool
1984 draw_date(struct view *view, struct time *time)
1986 const char *date = mkdate(time, opt_date);
1987 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1989 if (opt_date == DATE_NO)
1990 return FALSE;
1992 return draw_field(view, LINE_DATE, date, cols, FALSE);
1995 static bool
1996 draw_author(struct view *view, const char *author)
1998 bool trim = author_trim(opt_author_cols);
1999 const char *text = mkauthor(author, opt_author_cols, opt_author);
2001 if (opt_author == AUTHOR_NO)
2002 return FALSE;
2004 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2007 static bool
2008 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2010 bool trim = filename && strlen(filename) >= opt_filename_cols;
2012 if (opt_filename == FILENAME_NO)
2013 return FALSE;
2015 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2016 return FALSE;
2018 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2021 static bool
2022 draw_mode(struct view *view, mode_t mode)
2024 const char *str = mkmode(mode);
2026 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2029 static bool
2030 draw_lineno(struct view *view, unsigned int lineno)
2032 char number[10];
2033 int digits3 = view->digits < 3 ? 3 : view->digits;
2034 int max = MIN(VIEW_MAX_LEN(view), digits3);
2035 char *text = NULL;
2036 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2038 if (!opt_line_number)
2039 return FALSE;
2041 lineno += view->pos.offset + 1;
2042 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2043 static char fmt[] = "%1ld";
2045 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2046 if (string_format(number, fmt, lineno))
2047 text = number;
2049 if (text)
2050 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2051 else
2052 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2053 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2056 static bool
2057 draw_refs(struct view *view, struct ref_list *refs)
2059 size_t i;
2061 if (!opt_show_refs || !refs)
2062 return FALSE;
2064 for (i = 0; i < refs->size; i++) {
2065 struct ref *ref = refs->refs[i];
2066 enum line_type type = get_line_type_from_ref(ref);
2068 if (draw_formatted(view, type, "[%s]", ref->name))
2069 return TRUE;
2071 if (draw_text(view, LINE_DEFAULT, " "))
2072 return TRUE;
2075 return FALSE;
2078 static bool
2079 draw_view_line(struct view *view, unsigned int lineno)
2081 struct line *line;
2082 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2084 assert(view_is_displayed(view));
2086 if (view->pos.offset + lineno >= view->lines)
2087 return FALSE;
2089 line = &view->line[view->pos.offset + lineno];
2091 wmove(view->win, lineno, 0);
2092 if (line->cleareol)
2093 wclrtoeol(view->win);
2094 view->col = 0;
2095 view->curline = line;
2096 view->curtype = LINE_NONE;
2097 line->selected = FALSE;
2098 line->dirty = line->cleareol = 0;
2100 if (selected) {
2101 set_view_attr(view, LINE_CURSOR);
2102 line->selected = TRUE;
2103 view->ops->select(view, line);
2106 return view->ops->draw(view, line, lineno);
2109 static void
2110 redraw_view_dirty(struct view *view)
2112 bool dirty = FALSE;
2113 int lineno;
2115 for (lineno = 0; lineno < view->height; lineno++) {
2116 if (view->pos.offset + lineno >= view->lines)
2117 break;
2118 if (!view->line[view->pos.offset + lineno].dirty)
2119 continue;
2120 dirty = TRUE;
2121 if (!draw_view_line(view, lineno))
2122 break;
2125 if (!dirty)
2126 return;
2127 wnoutrefresh(view->win);
2130 static void
2131 redraw_view_from(struct view *view, int lineno)
2133 assert(0 <= lineno && lineno < view->height);
2135 for (; lineno < view->height; lineno++) {
2136 if (!draw_view_line(view, lineno))
2137 break;
2140 wnoutrefresh(view->win);
2143 static void
2144 redraw_view(struct view *view)
2146 werase(view->win);
2147 redraw_view_from(view, 0);
2151 static void
2152 update_view_title(struct view *view)
2154 char buf[SIZEOF_STR];
2155 char state[SIZEOF_STR];
2156 size_t bufpos = 0, statelen = 0;
2157 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2159 assert(view_is_displayed(view));
2161 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines &&
2162 view->pos.lineno >= view->lineoffset) {
2163 unsigned int view_lines = view->pos.offset + view->height;
2164 unsigned int lines = view->lines
2165 ? MIN(view_lines, view->lines) * 100 / view->lines
2166 : 0;
2168 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2169 view->ops->type,
2170 view->pos.lineno + 1 - view->lineoffset,
2171 view->lines - view->lineoffset,
2172 lines);
2176 if (view->pipe) {
2177 time_t secs = time(NULL) - view->start_time;
2179 /* Three git seconds are a long time ... */
2180 if (secs > 2)
2181 string_format_from(state, &statelen, " loading %lds", secs);
2184 string_format_from(buf, &bufpos, "[%s]", view->name);
2185 if (*view->ref && bufpos < view->width) {
2186 size_t refsize = strlen(view->ref);
2187 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2189 if (minsize < view->width)
2190 refsize = view->width - minsize + 7;
2191 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2194 if (statelen && bufpos < view->width) {
2195 string_format_from(buf, &bufpos, "%s", state);
2198 if (view == display[current_view])
2199 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2200 else
2201 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2203 mvwaddnstr(window, 0, 0, buf, bufpos);
2204 wclrtoeol(window);
2205 wnoutrefresh(window);
2208 static int
2209 apply_step(double step, int value)
2211 if (step >= 1)
2212 return (int) step;
2213 value *= step + 0.01;
2214 return value ? value : 1;
2217 static void
2218 resize_display(void)
2220 int offset, i;
2221 struct view *base = display[0];
2222 struct view *view = display[1] ? display[1] : display[0];
2224 /* Setup window dimensions */
2226 getmaxyx(stdscr, base->height, base->width);
2228 /* Make room for the status window. */
2229 base->height -= 1;
2231 if (view != base) {
2232 /* Horizontal split. */
2233 view->width = base->width;
2234 view->height = apply_step(opt_scale_split_view, base->height);
2235 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2236 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2237 base->height -= view->height;
2239 /* Make room for the title bar. */
2240 view->height -= 1;
2243 /* Make room for the title bar. */
2244 base->height -= 1;
2246 offset = 0;
2248 foreach_displayed_view (view, i) {
2249 if (!display_win[i]) {
2250 display_win[i] = newwin(view->height, view->width, offset, 0);
2251 if (!display_win[i])
2252 die("Failed to create %s view", view->name);
2254 scrollok(display_win[i], FALSE);
2256 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2257 if (!display_title[i])
2258 die("Failed to create title window");
2260 } else {
2261 wresize(display_win[i], view->height, view->width);
2262 mvwin(display_win[i], offset, 0);
2263 mvwin(display_title[i], offset + view->height, 0);
2266 view->win = display_win[i];
2268 offset += view->height + 1;
2272 static void
2273 redraw_display(bool clear)
2275 struct view *view;
2276 int i;
2278 foreach_displayed_view (view, i) {
2279 if (clear)
2280 wclear(view->win);
2281 redraw_view(view);
2282 update_view_title(view);
2288 * Option management
2291 #define TOGGLE_MENU \
2292 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2293 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2294 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2295 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2296 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2297 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2298 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2299 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2300 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2301 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2303 static bool
2304 toggle_option(enum request request)
2306 const struct {
2307 enum request request;
2308 const struct enum_map *map;
2309 size_t map_size;
2310 } data[] = {
2311 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2312 TOGGLE_MENU
2313 #undef TOGGLE_
2315 const struct menu_item menu[] = {
2316 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2317 TOGGLE_MENU
2318 #undef TOGGLE_
2319 { 0 }
2321 int i = 0;
2323 if (request == REQ_OPTIONS) {
2324 if (!prompt_menu("Toggle option", menu, &i))
2325 return FALSE;
2326 } else {
2327 while (i < ARRAY_SIZE(data) && data[i].request != request)
2328 i++;
2329 if (i >= ARRAY_SIZE(data))
2330 die("Invalid request (%d)", request);
2333 if (data[i].map != NULL) {
2334 unsigned int *opt = menu[i].data;
2336 *opt = (*opt + 1) % data[i].map_size;
2337 if (data[i].map == ignore_space_map) {
2338 update_ignore_space_arg();
2339 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2340 return TRUE;
2342 } else if (data[i].map == commit_order_map) {
2343 update_commit_order_arg();
2344 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2345 return TRUE;
2348 redraw_display(FALSE);
2349 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2351 } else {
2352 bool *option = menu[i].data;
2354 *option = !*option;
2355 redraw_display(FALSE);
2356 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2359 return FALSE;
2364 * Navigation
2367 static bool
2368 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2370 if (lineno >= view->lines)
2371 lineno = view->lines > 0 ? view->lines - 1 : 0;
2373 if (offset > lineno || offset + view->height <= lineno) {
2374 unsigned long half = view->height / 2;
2376 if (lineno > half)
2377 offset = lineno - half;
2378 else
2379 offset = 0;
2382 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2383 view->pos.offset = offset;
2384 view->pos.lineno = lineno;
2385 return TRUE;
2388 return FALSE;
2391 /* Scrolling backend */
2392 static void
2393 do_scroll_view(struct view *view, int lines)
2395 bool redraw_current_line = FALSE;
2397 /* The rendering expects the new offset. */
2398 view->pos.offset += lines;
2400 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2401 assert(lines);
2403 /* Move current line into the view. */
2404 if (view->pos.lineno < view->pos.offset) {
2405 view->pos.lineno = view->pos.offset;
2406 redraw_current_line = TRUE;
2407 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2408 view->pos.lineno = view->pos.offset + view->height - 1;
2409 redraw_current_line = TRUE;
2412 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2414 /* Redraw the whole screen if scrolling is pointless. */
2415 if (view->height < ABS(lines)) {
2416 redraw_view(view);
2418 } else {
2419 int line = lines > 0 ? view->height - lines : 0;
2420 int end = line + ABS(lines);
2422 scrollok(view->win, TRUE);
2423 wscrl(view->win, lines);
2424 scrollok(view->win, FALSE);
2426 while (line < end && draw_view_line(view, line))
2427 line++;
2429 if (redraw_current_line)
2430 draw_view_line(view, view->pos.lineno - view->pos.offset);
2431 wnoutrefresh(view->win);
2434 view->has_scrolled = TRUE;
2435 report("");
2438 /* Scroll frontend */
2439 static void
2440 scroll_view(struct view *view, enum request request)
2442 int lines = 1;
2444 assert(view_is_displayed(view));
2446 switch (request) {
2447 case REQ_SCROLL_FIRST_COL:
2448 view->pos.col = 0;
2449 redraw_view_from(view, 0);
2450 report("");
2451 return;
2452 case REQ_SCROLL_LEFT:
2453 if (view->pos.col == 0) {
2454 report("Cannot scroll beyond the first column");
2455 return;
2457 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2458 view->pos.col = 0;
2459 else
2460 view->pos.col -= apply_step(opt_hscroll, view->width);
2461 redraw_view_from(view, 0);
2462 report("");
2463 return;
2464 case REQ_SCROLL_RIGHT:
2465 view->pos.col += apply_step(opt_hscroll, view->width);
2466 redraw_view(view);
2467 report("");
2468 return;
2469 case REQ_SCROLL_PAGE_DOWN:
2470 lines = view->height;
2471 case REQ_SCROLL_LINE_DOWN:
2472 if (view->pos.offset + lines > view->lines)
2473 lines = view->lines - view->pos.offset;
2475 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2476 report("Cannot scroll beyond the last line");
2477 return;
2479 break;
2481 case REQ_SCROLL_PAGE_UP:
2482 lines = view->height;
2483 case REQ_SCROLL_LINE_UP:
2484 if (lines > view->pos.offset)
2485 lines = view->pos.offset;
2487 if (lines == 0) {
2488 report("Cannot scroll beyond the first line");
2489 return;
2492 lines = -lines;
2493 break;
2495 default:
2496 die("request %d not handled in switch", request);
2499 do_scroll_view(view, lines);
2502 /* Cursor moving */
2503 static void
2504 move_view(struct view *view, enum request request)
2506 int scroll_steps = 0;
2507 int steps;
2509 switch (request) {
2510 case REQ_MOVE_FIRST_LINE:
2511 steps = -view->pos.lineno;
2512 break;
2514 case REQ_MOVE_LAST_LINE:
2515 steps = view->lines - view->pos.lineno - 1;
2516 break;
2518 case REQ_MOVE_PAGE_UP:
2519 steps = view->height > view->pos.lineno
2520 ? -view->pos.lineno : -view->height;
2521 break;
2523 case REQ_MOVE_PAGE_DOWN:
2524 steps = view->pos.lineno + view->height >= view->lines
2525 ? view->lines - view->pos.lineno - 1 : view->height;
2526 break;
2528 case REQ_MOVE_UP:
2529 case REQ_PREVIOUS:
2530 steps = -1;
2531 break;
2533 case REQ_MOVE_DOWN:
2534 case REQ_NEXT:
2535 steps = 1;
2536 break;
2538 default:
2539 die("request %d not handled in switch", request);
2542 if (steps <= 0 && view->pos.lineno == 0) {
2543 report("Cannot move beyond the first line");
2544 return;
2546 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2547 report("Cannot move beyond the last line");
2548 return;
2551 /* Move the current line */
2552 view->pos.lineno += steps;
2553 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2555 /* Check whether the view needs to be scrolled */
2556 if (view->pos.lineno < view->pos.offset ||
2557 view->pos.lineno >= view->pos.offset + view->height) {
2558 scroll_steps = steps;
2559 if (steps < 0 && -steps > view->pos.offset) {
2560 scroll_steps = -view->pos.offset;
2562 } else if (steps > 0) {
2563 if (view->pos.lineno == view->lines - 1 &&
2564 view->lines > view->height) {
2565 scroll_steps = view->lines - view->pos.offset - 1;
2566 if (scroll_steps >= view->height)
2567 scroll_steps -= view->height - 1;
2572 if (!view_is_displayed(view)) {
2573 view->pos.offset += scroll_steps;
2574 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2575 view->ops->select(view, &view->line[view->pos.lineno]);
2576 return;
2579 /* Repaint the old "current" line if we be scrolling */
2580 if (ABS(steps) < view->height)
2581 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2583 if (scroll_steps) {
2584 do_scroll_view(view, scroll_steps);
2585 return;
2588 /* Draw the current line */
2589 draw_view_line(view, view->pos.lineno - view->pos.offset);
2591 wnoutrefresh(view->win);
2592 report("");
2597 * Searching
2600 static void search_view(struct view *view, enum request request);
2602 static bool
2603 grep_text(struct view *view, const char *text[])
2605 regmatch_t pmatch;
2606 size_t i;
2608 for (i = 0; text[i]; i++)
2609 if (*text[i] &&
2610 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2611 return TRUE;
2612 return FALSE;
2615 static void
2616 select_view_line(struct view *view, unsigned long lineno)
2618 struct position old = view->pos;
2620 if (goto_view_line(view, view->pos.offset, lineno)) {
2621 if (view_is_displayed(view)) {
2622 if (old.offset != view->pos.offset) {
2623 redraw_view(view);
2624 } else {
2625 draw_view_line(view, old.lineno - view->pos.offset);
2626 draw_view_line(view, view->pos.lineno - view->pos.offset);
2627 wnoutrefresh(view->win);
2629 } else {
2630 view->ops->select(view, &view->line[view->pos.lineno]);
2635 static void
2636 find_next(struct view *view, enum request request)
2638 unsigned long lineno = view->pos.lineno;
2639 int direction;
2641 if (!*view->grep) {
2642 if (!*opt_search)
2643 report("No previous search");
2644 else
2645 search_view(view, request);
2646 return;
2649 switch (request) {
2650 case REQ_SEARCH:
2651 case REQ_FIND_NEXT:
2652 direction = 1;
2653 break;
2655 case REQ_SEARCH_BACK:
2656 case REQ_FIND_PREV:
2657 direction = -1;
2658 break;
2660 default:
2661 return;
2664 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2665 lineno += direction;
2667 /* Note, lineno is unsigned long so will wrap around in which case it
2668 * will become bigger than view->lines. */
2669 for (; lineno < view->lines; lineno += direction) {
2670 if (view->ops->grep(view, &view->line[lineno])) {
2671 select_view_line(view, lineno);
2672 report("Line %ld matches '%s'", lineno + 1, view->grep);
2673 return;
2677 report("No match found for '%s'", view->grep);
2680 static void
2681 search_view(struct view *view, enum request request)
2683 int regex_err;
2685 if (view->regex) {
2686 regfree(view->regex);
2687 *view->grep = 0;
2688 } else {
2689 view->regex = calloc(1, sizeof(*view->regex));
2690 if (!view->regex)
2691 return;
2694 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2695 if (regex_err != 0) {
2696 char buf[SIZEOF_STR] = "unknown error";
2698 regerror(regex_err, view->regex, buf, sizeof(buf));
2699 report("Search failed: %s", buf);
2700 return;
2703 string_copy(view->grep, opt_search);
2705 find_next(view, request);
2709 * Incremental updating
2712 static inline bool
2713 check_position(struct position *pos)
2715 return pos->lineno || pos->col || pos->offset;
2718 static inline void
2719 clear_position(struct position *pos)
2721 memset(pos, 0, sizeof(*pos));
2724 static void
2725 reset_view(struct view *view)
2727 int i;
2729 for (i = 0; i < view->lines; i++)
2730 if (!view->line[i].dont_free)
2731 free(view->line[i].data);
2732 free(view->line);
2734 view->prev_pos = view->pos;
2735 clear_position(&view->pos);
2737 view->line = NULL;
2738 view->lines = 0;
2739 view->vid[0] = 0;
2740 view->lineoffset = 0;
2741 view->update_secs = 0;
2744 static const char *
2745 format_arg(const char *name)
2747 static struct {
2748 const char *name;
2749 size_t namelen;
2750 const char *value;
2751 const char *value_if_empty;
2752 } vars[] = {
2753 #define FORMAT_VAR(name, value, value_if_empty) \
2754 { name, STRING_SIZE(name), value, value_if_empty }
2755 FORMAT_VAR("%(directory)", opt_path, "."),
2756 FORMAT_VAR("%(file)", opt_file, ""),
2757 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2758 FORMAT_VAR("%(head)", ref_head, ""),
2759 FORMAT_VAR("%(commit)", ref_commit, ""),
2760 FORMAT_VAR("%(blob)", ref_blob, ""),
2761 FORMAT_VAR("%(branch)", ref_branch, ""),
2763 int i;
2765 if (!prefixcmp(name, "%(prompt"))
2766 return read_prompt("Command argument: ");
2768 for (i = 0; i < ARRAY_SIZE(vars); i++)
2769 if (!strncmp(name, vars[i].name, vars[i].namelen))
2770 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2772 report("Unknown replacement: `%s`", name);
2773 return NULL;
2776 static bool
2777 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2779 char buf[SIZEOF_STR];
2780 int argc;
2782 argv_free(*dst_argv);
2784 for (argc = 0; src_argv[argc]; argc++) {
2785 const char *arg = src_argv[argc];
2786 size_t bufpos = 0;
2788 if (!strcmp(arg, "%(fileargs)")) {
2789 if (!argv_append_array(dst_argv, opt_file_argv))
2790 break;
2791 continue;
2793 } else if (!strcmp(arg, "%(diffargs)")) {
2794 if (!argv_append_array(dst_argv, opt_diff_argv))
2795 break;
2796 continue;
2798 } else if (!strcmp(arg, "%(blameargs)")) {
2799 if (!argv_append_array(dst_argv, opt_blame_argv))
2800 break;
2801 continue;
2803 } else if (!strcmp(arg, "%(revargs)") ||
2804 (first && !strcmp(arg, "%(commit)"))) {
2805 if (!argv_append_array(dst_argv, opt_rev_argv))
2806 break;
2807 continue;
2810 while (arg) {
2811 char *next = strstr(arg, "%(");
2812 int len = next - arg;
2813 const char *value;
2815 if (!next) {
2816 len = strlen(arg);
2817 value = "";
2819 } else {
2820 value = format_arg(next);
2822 if (!value) {
2823 return FALSE;
2827 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2828 return FALSE;
2830 arg = next ? strchr(next, ')') + 1 : NULL;
2833 if (!argv_append(dst_argv, buf))
2834 break;
2837 return src_argv[argc] == NULL;
2840 static bool
2841 restore_view_position(struct view *view)
2843 /* A view without a previous view is the first view */
2844 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2845 select_view_line(view, opt_lineno - 1);
2846 opt_lineno = 0;
2849 /* Ensure that the view position is in a valid state. */
2850 if (!check_position(&view->prev_pos) ||
2851 (view->pipe && view->lines <= view->prev_pos.lineno))
2852 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2854 /* Changing the view position cancels the restoring. */
2855 /* FIXME: Changing back to the first line is not detected. */
2856 if (check_position(&view->pos)) {
2857 clear_position(&view->prev_pos);
2858 return FALSE;
2861 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2862 view_is_displayed(view))
2863 werase(view->win);
2865 view->pos.col = view->prev_pos.col;
2866 clear_position(&view->prev_pos);
2868 return TRUE;
2871 static void
2872 end_update(struct view *view, bool force)
2874 if (!view->pipe)
2875 return;
2876 while (!view->ops->read(view, NULL))
2877 if (!force)
2878 return;
2879 if (force)
2880 io_kill(view->pipe);
2881 io_done(view->pipe);
2882 view->pipe = NULL;
2885 static void
2886 setup_update(struct view *view, const char *vid)
2888 reset_view(view);
2889 string_copy_rev(view->vid, vid);
2890 view->pipe = &view->io;
2891 view->start_time = time(NULL);
2894 static bool
2895 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2897 bool extra = !!(flags & (OPEN_EXTRA));
2898 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2899 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2901 if (!reload && !strcmp(view->vid, view->id))
2902 return TRUE;
2904 if (view->pipe) {
2905 if (extra)
2906 io_done(view->pipe);
2907 else
2908 end_update(view, TRUE);
2911 if (!refresh && argv) {
2912 view->dir = dir;
2913 if (!format_argv(&view->argv, argv, !view->prev)) {
2914 report("Failed to format %s arguments", view->name);
2915 return FALSE;
2918 /* Put the current ref_* value to the view title ref
2919 * member. This is needed by the blob view. Most other
2920 * views sets it automatically after loading because the
2921 * first line is a commit line. */
2922 string_copy_rev(view->ref, view->id);
2925 if (view->argv && view->argv[0] &&
2926 !io_run(&view->io, IO_RD, view->dir, view->argv)) {
2927 report("Failed to open %s view", view->name);
2928 return FALSE;
2931 if (!extra)
2932 setup_update(view, view->id);
2934 return TRUE;
2937 static bool
2938 update_view(struct view *view)
2940 char *line;
2941 /* Clear the view and redraw everything since the tree sorting
2942 * might have rearranged things. */
2943 bool redraw = view->lines == 0;
2944 bool can_read = TRUE;
2946 if (!view->pipe)
2947 return TRUE;
2949 if (!io_can_read(view->pipe, FALSE)) {
2950 if (view->lines == 0 && view_is_displayed(view)) {
2951 time_t secs = time(NULL) - view->start_time;
2953 if (secs > 1 && secs > view->update_secs) {
2954 if (view->update_secs == 0)
2955 redraw_view(view);
2956 update_view_title(view);
2957 view->update_secs = secs;
2960 return TRUE;
2963 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2964 if (view->encoding) {
2965 line = encoding_convert(view->encoding, line);
2968 if (!view->ops->read(view, line)) {
2969 report("Allocation failure");
2970 end_update(view, TRUE);
2971 return FALSE;
2976 unsigned long lines = view->lines;
2977 int digits;
2979 for (digits = 0; lines; digits++)
2980 lines /= 10;
2982 /* Keep the displayed view in sync with line number scaling. */
2983 if (digits != view->digits) {
2984 view->digits = digits;
2985 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2986 redraw = TRUE;
2990 if (io_error(view->pipe)) {
2991 report("Failed to read: %s", io_strerror(view->pipe));
2992 end_update(view, TRUE);
2994 } else if (io_eof(view->pipe)) {
2995 if (view_is_displayed(view))
2996 report("");
2997 end_update(view, FALSE);
3000 if (restore_view_position(view))
3001 redraw = TRUE;
3003 if (!view_is_displayed(view))
3004 return TRUE;
3006 if (redraw)
3007 redraw_view_from(view, 0);
3008 else
3009 redraw_view_dirty(view);
3011 /* Update the title _after_ the redraw so that if the redraw picks up a
3012 * commit reference in view->ref it'll be available here. */
3013 update_view_title(view);
3014 return TRUE;
3017 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3019 static struct line *
3020 add_line_data(struct view *view, void *data, enum line_type type)
3022 struct line *line;
3024 if (!realloc_lines(&view->line, view->lines, 1))
3025 return NULL;
3027 line = &view->line[view->lines++];
3028 memset(line, 0, sizeof(*line));
3029 line->type = type;
3030 line->data = data;
3031 line->dirty = 1;
3033 return line;
3036 static struct line *
3037 add_line_static_data(struct view *view, void *data, enum line_type type)
3039 struct line *line = add_line_data(view, data, type);
3041 if (line)
3042 line->dont_free = TRUE;
3043 return line;
3046 static struct line *
3047 add_line_text(struct view *view, const char *text, enum line_type type)
3049 char *data = text ? strdup(text) : NULL;
3051 return data ? add_line_data(view, data, type) : NULL;
3054 static struct line *
3055 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3057 char buf[SIZEOF_STR];
3058 int retval;
3060 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3061 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3065 * View opening
3068 static void
3069 split_view(struct view *prev, struct view *view)
3071 display[1] = view;
3072 current_view = 1;
3073 view->parent = prev;
3074 resize_display();
3076 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3077 /* Take the title line into account. */
3078 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3080 /* Scroll the view that was split if the current line is
3081 * outside the new limited view. */
3082 do_scroll_view(prev, lines);
3085 if (view != prev && view_is_displayed(prev)) {
3086 /* "Blur" the previous view. */
3087 update_view_title(prev);
3091 static void
3092 maximize_view(struct view *view, bool redraw)
3094 memset(display, 0, sizeof(display));
3095 current_view = 0;
3096 display[current_view] = view;
3097 resize_display();
3098 if (redraw) {
3099 redraw_display(FALSE);
3100 report("");
3104 static void
3105 load_view(struct view *view, struct view *prev, enum open_flags flags)
3107 if (view->pipe)
3108 end_update(view, TRUE);
3109 if (view->ops->private_size) {
3110 if (!view->private)
3111 view->private = calloc(1, view->ops->private_size);
3112 else
3113 memset(view->private, 0, view->ops->private_size);
3116 /* When prev == view it means this is the first loaded view. */
3117 if (prev && view != prev) {
3118 view->prev = prev;
3121 if (!view->ops->open(view, flags))
3122 return;
3124 if (prev) {
3125 bool split = !!(flags & OPEN_SPLIT);
3127 if (split) {
3128 split_view(prev, view);
3129 } else {
3130 maximize_view(view, FALSE);
3134 restore_view_position(view);
3136 if (view->pipe && view->lines == 0) {
3137 /* Clear the old view and let the incremental updating refill
3138 * the screen. */
3139 werase(view->win);
3140 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3141 clear_position(&view->prev_pos);
3142 report("");
3143 } else if (view_is_displayed(view)) {
3144 redraw_view(view);
3145 report("");
3149 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3150 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3152 static void
3153 open_view(struct view *prev, enum request request, enum open_flags flags)
3155 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3156 struct view *view = VIEW(request);
3157 int nviews = displayed_views();
3159 assert(flags ^ OPEN_REFRESH);
3161 if (view == prev && nviews == 1 && !reload) {
3162 report("Already in %s view", view->name);
3163 return;
3166 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3167 report("The %s view is disabled in pager view", view->name);
3168 return;
3171 load_view(view, prev ? prev : view, flags);
3174 static void
3175 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3177 enum request request = view - views + REQ_OFFSET + 1;
3179 if (view->pipe)
3180 end_update(view, TRUE);
3181 view->dir = dir;
3183 if (!argv_copy(&view->argv, argv)) {
3184 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3185 } else {
3186 open_view(prev, request, flags | OPEN_PREPARED);
3190 static void
3191 open_external_viewer(const char *argv[], const char *dir)
3193 def_prog_mode(); /* save current tty modes */
3194 endwin(); /* restore original tty modes */
3195 io_run_fg(argv, dir);
3196 fprintf(stderr, "Press Enter to continue");
3197 getc(opt_tty);
3198 reset_prog_mode();
3199 redraw_display(TRUE);
3202 static void
3203 open_mergetool(const char *file)
3205 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3207 open_external_viewer(mergetool_argv, opt_cdup);
3210 static void
3211 open_editor(const char *file)
3213 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3214 char editor_cmd[SIZEOF_STR];
3215 const char *editor;
3216 int argc = 0;
3218 editor = getenv("GIT_EDITOR");
3219 if (!editor && *opt_editor)
3220 editor = opt_editor;
3221 if (!editor)
3222 editor = getenv("VISUAL");
3223 if (!editor)
3224 editor = getenv("EDITOR");
3225 if (!editor)
3226 editor = "vi";
3228 string_ncopy(editor_cmd, editor, strlen(editor));
3229 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3230 report("Failed to read editor command");
3231 return;
3234 editor_argv[argc] = file;
3235 open_external_viewer(editor_argv, opt_cdup);
3238 static void
3239 open_run_request(enum request request)
3241 struct run_request *req = get_run_request(request);
3242 const char **argv = NULL;
3244 if (!req) {
3245 report("Unknown run request");
3246 return;
3249 if (format_argv(&argv, req->argv, FALSE)) {
3250 if (req->silent)
3251 io_run_bg(argv);
3252 else
3253 open_external_viewer(argv, NULL);
3255 if (argv)
3256 argv_free(argv);
3257 free(argv);
3261 * User request switch noodle
3264 static int
3265 view_driver(struct view *view, enum request request)
3267 int i;
3269 if (request == REQ_NONE)
3270 return TRUE;
3272 if (request > REQ_NONE) {
3273 open_run_request(request);
3274 view_request(view, REQ_REFRESH);
3275 return TRUE;
3278 request = view_request(view, request);
3279 if (request == REQ_NONE)
3280 return TRUE;
3282 switch (request) {
3283 case REQ_MOVE_UP:
3284 case REQ_MOVE_DOWN:
3285 case REQ_MOVE_PAGE_UP:
3286 case REQ_MOVE_PAGE_DOWN:
3287 case REQ_MOVE_FIRST_LINE:
3288 case REQ_MOVE_LAST_LINE:
3289 move_view(view, request);
3290 break;
3292 case REQ_SCROLL_FIRST_COL:
3293 case REQ_SCROLL_LEFT:
3294 case REQ_SCROLL_RIGHT:
3295 case REQ_SCROLL_LINE_DOWN:
3296 case REQ_SCROLL_LINE_UP:
3297 case REQ_SCROLL_PAGE_DOWN:
3298 case REQ_SCROLL_PAGE_UP:
3299 scroll_view(view, request);
3300 break;
3302 case REQ_VIEW_MAIN:
3303 case REQ_VIEW_DIFF:
3304 case REQ_VIEW_LOG:
3305 case REQ_VIEW_TREE:
3306 case REQ_VIEW_HELP:
3307 case REQ_VIEW_BRANCH:
3308 case REQ_VIEW_BLAME:
3309 case REQ_VIEW_BLOB:
3310 case REQ_VIEW_STATUS:
3311 case REQ_VIEW_STAGE:
3312 case REQ_VIEW_PAGER:
3313 open_view(view, request, OPEN_DEFAULT);
3314 break;
3316 case REQ_NEXT:
3317 case REQ_PREVIOUS:
3318 if (view->parent) {
3319 int line;
3321 view = view->parent;
3322 line = view->pos.lineno;
3323 move_view(view, request);
3324 if (view_is_displayed(view))
3325 update_view_title(view);
3326 if (line != view->pos.lineno)
3327 view_request(view, REQ_ENTER);
3328 } else {
3329 move_view(view, request);
3331 break;
3333 case REQ_VIEW_NEXT:
3335 int nviews = displayed_views();
3336 int next_view = (current_view + 1) % nviews;
3338 if (next_view == current_view) {
3339 report("Only one view is displayed");
3340 break;
3343 current_view = next_view;
3344 /* Blur out the title of the previous view. */
3345 update_view_title(view);
3346 report("");
3347 break;
3349 case REQ_REFRESH:
3350 report("Refreshing is not yet supported for the %s view", view->name);
3351 break;
3353 case REQ_MAXIMIZE:
3354 if (displayed_views() == 2)
3355 maximize_view(view, TRUE);
3356 break;
3358 case REQ_OPTIONS:
3359 case REQ_TOGGLE_LINENO:
3360 case REQ_TOGGLE_DATE:
3361 case REQ_TOGGLE_AUTHOR:
3362 case REQ_TOGGLE_FILENAME:
3363 case REQ_TOGGLE_GRAPHIC:
3364 case REQ_TOGGLE_REV_GRAPH:
3365 case REQ_TOGGLE_REFS:
3366 case REQ_TOGGLE_CHANGES:
3367 case REQ_TOGGLE_IGNORE_SPACE:
3368 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3369 reload_view(view);
3370 break;
3372 case REQ_TOGGLE_SORT_FIELD:
3373 case REQ_TOGGLE_SORT_ORDER:
3374 report("Sorting is not yet supported for the %s view", view->name);
3375 break;
3377 case REQ_DIFF_CONTEXT_UP:
3378 case REQ_DIFF_CONTEXT_DOWN:
3379 report("Changing the diff context is not yet supported for the %s view", view->name);
3380 break;
3382 case REQ_SEARCH:
3383 case REQ_SEARCH_BACK:
3384 search_view(view, request);
3385 break;
3387 case REQ_FIND_NEXT:
3388 case REQ_FIND_PREV:
3389 find_next(view, request);
3390 break;
3392 case REQ_STOP_LOADING:
3393 foreach_view(view, i) {
3394 if (view->pipe)
3395 report("Stopped loading the %s view", view->name),
3396 end_update(view, TRUE);
3398 break;
3400 case REQ_SHOW_VERSION:
3401 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3402 return TRUE;
3404 case REQ_SCREEN_REDRAW:
3405 redraw_display(TRUE);
3406 break;
3408 case REQ_EDIT:
3409 report("Nothing to edit");
3410 break;
3412 case REQ_ENTER:
3413 report("Nothing to enter");
3414 break;
3416 case REQ_VIEW_CLOSE:
3417 /* XXX: Mark closed views by letting view->prev point to the
3418 * view itself. Parents to closed view should never be
3419 * followed. */
3420 if (view->prev && view->prev != view) {
3421 maximize_view(view->prev, TRUE);
3422 view->prev = view;
3423 break;
3425 /* Fall-through */
3426 case REQ_QUIT:
3427 return FALSE;
3429 default:
3430 report("Unknown key, press %s for help",
3431 get_view_key(view, REQ_VIEW_HELP));
3432 return TRUE;
3435 return TRUE;
3440 * View backend utilities
3443 enum sort_field {
3444 ORDERBY_NAME,
3445 ORDERBY_DATE,
3446 ORDERBY_AUTHOR,
3449 struct sort_state {
3450 const enum sort_field *fields;
3451 size_t size, current;
3452 bool reverse;
3455 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3456 #define get_sort_field(state) ((state).fields[(state).current])
3457 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3459 static void
3460 sort_view(struct view *view, enum request request, struct sort_state *state,
3461 int (*compare)(const void *, const void *))
3463 switch (request) {
3464 case REQ_TOGGLE_SORT_FIELD:
3465 state->current = (state->current + 1) % state->size;
3466 break;
3468 case REQ_TOGGLE_SORT_ORDER:
3469 state->reverse = !state->reverse;
3470 break;
3471 default:
3472 die("Not a sort request");
3475 qsort(view->line, view->lines, sizeof(*view->line), compare);
3476 redraw_view(view);
3479 static bool
3480 update_diff_context(enum request request)
3482 int diff_context = opt_diff_context;
3484 switch (request) {
3485 case REQ_DIFF_CONTEXT_UP:
3486 opt_diff_context += 1;
3487 update_diff_context_arg(opt_diff_context);
3488 break;
3490 case REQ_DIFF_CONTEXT_DOWN:
3491 if (opt_diff_context == 0) {
3492 report("Diff context cannot be less than zero");
3493 break;
3495 opt_diff_context -= 1;
3496 update_diff_context_arg(opt_diff_context);
3497 break;
3499 default:
3500 die("Not a diff context request");
3503 return diff_context != opt_diff_context;
3506 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3508 /* Small author cache to reduce memory consumption. It uses binary
3509 * search to lookup or find place to position new entries. No entries
3510 * are ever freed. */
3511 static const char *
3512 get_author(const char *name)
3514 static const char **authors;
3515 static size_t authors_size;
3516 int from = 0, to = authors_size - 1;
3518 while (from <= to) {
3519 size_t pos = (to + from) / 2;
3520 int cmp = strcmp(name, authors[pos]);
3522 if (!cmp)
3523 return authors[pos];
3525 if (cmp < 0)
3526 to = pos - 1;
3527 else
3528 from = pos + 1;
3531 if (!realloc_authors(&authors, authors_size, 1))
3532 return NULL;
3533 name = strdup(name);
3534 if (!name)
3535 return NULL;
3537 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3538 authors[from] = name;
3539 authors_size++;
3541 return name;
3544 static void
3545 parse_timesec(struct time *time, const char *sec)
3547 time->sec = (time_t) atol(sec);
3550 static void
3551 parse_timezone(struct time *time, const char *zone)
3553 long tz;
3555 tz = ('0' - zone[1]) * 60 * 60 * 10;
3556 tz += ('0' - zone[2]) * 60 * 60;
3557 tz += ('0' - zone[3]) * 60 * 10;
3558 tz += ('0' - zone[4]) * 60;
3560 if (zone[0] == '-')
3561 tz = -tz;
3563 time->tz = tz;
3564 time->sec -= tz;
3567 /* Parse author lines where the name may be empty:
3568 * author <email@address.tld> 1138474660 +0100
3570 static void
3571 parse_author_line(char *ident, const char **author, struct time *time)
3573 char *nameend = strchr(ident, '<');
3574 char *emailend = strchr(ident, '>');
3576 if (nameend && emailend)
3577 *nameend = *emailend = 0;
3578 ident = chomp_string(ident);
3579 if (!*ident) {
3580 if (nameend)
3581 ident = chomp_string(nameend + 1);
3582 if (!*ident)
3583 ident = "Unknown";
3586 *author = get_author(ident);
3588 /* Parse epoch and timezone */
3589 if (emailend && emailend[1] == ' ') {
3590 char *secs = emailend + 2;
3591 char *zone = strchr(secs, ' ');
3593 parse_timesec(time, secs);
3595 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3596 parse_timezone(time, zone + 1);
3600 static struct line *
3601 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3603 for (; view_has_line(view, line); line += direction)
3604 if (line->type == type)
3605 return line;
3607 return NULL;
3610 #define find_prev_line_by_type(view, line, type) \
3611 find_line_by_type(view, line, type, -1)
3613 #define find_next_line_by_type(view, line, type) \
3614 find_line_by_type(view, line, type, 1)
3617 * Blame
3620 struct blame_commit {
3621 char id[SIZEOF_REV]; /* SHA1 ID. */
3622 char title[128]; /* First line of the commit message. */
3623 const char *author; /* Author of the commit. */
3624 struct time time; /* Date from the author ident. */
3625 char filename[128]; /* Name of file. */
3626 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3627 char parent_filename[128]; /* Parent/previous name of file. */
3630 struct blame_header {
3631 char id[SIZEOF_REV]; /* SHA1 ID. */
3632 size_t orig_lineno;
3633 size_t lineno;
3634 size_t group;
3637 static bool
3638 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3640 const char *pos = *posref;
3642 *posref = NULL;
3643 pos = strchr(pos + 1, ' ');
3644 if (!pos || !isdigit(pos[1]))
3645 return FALSE;
3646 *number = atoi(pos + 1);
3647 if (*number < min || *number > max)
3648 return FALSE;
3650 *posref = pos;
3651 return TRUE;
3654 static bool
3655 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3657 const char *pos = text + SIZEOF_REV - 2;
3659 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3660 return FALSE;
3662 string_ncopy(header->id, text, SIZEOF_REV);
3664 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3665 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3666 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3667 return FALSE;
3669 return TRUE;
3672 static bool
3673 match_blame_header(const char *name, char **line)
3675 size_t namelen = strlen(name);
3676 bool matched = !strncmp(name, *line, namelen);
3678 if (matched)
3679 *line += namelen;
3681 return matched;
3684 static bool
3685 parse_blame_info(struct blame_commit *commit, char *line)
3687 if (match_blame_header("author ", &line)) {
3688 commit->author = get_author(line);
3690 } else if (match_blame_header("author-time ", &line)) {
3691 parse_timesec(&commit->time, line);
3693 } else if (match_blame_header("author-tz ", &line)) {
3694 parse_timezone(&commit->time, line);
3696 } else if (match_blame_header("summary ", &line)) {
3697 string_ncopy(commit->title, line, strlen(line));
3699 } else if (match_blame_header("previous ", &line)) {
3700 if (strlen(line) <= SIZEOF_REV)
3701 return FALSE;
3702 string_copy_rev(commit->parent_id, line);
3703 line += SIZEOF_REV;
3704 string_ncopy(commit->parent_filename, line, strlen(line));
3706 } else if (match_blame_header("filename ", &line)) {
3707 string_ncopy(commit->filename, line, strlen(line));
3708 return TRUE;
3711 return FALSE;
3715 * Pager backend
3718 static bool
3719 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3721 if (draw_lineno(view, lineno))
3722 return TRUE;
3724 draw_text(view, line->type, line->data);
3725 return TRUE;
3728 static bool
3729 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3731 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3732 char ref[SIZEOF_STR];
3734 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3735 return TRUE;
3737 /* This is the only fatal call, since it can "corrupt" the buffer. */
3738 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3739 return FALSE;
3741 return TRUE;
3744 static void
3745 add_pager_refs(struct view *view, struct line *line)
3747 char buf[SIZEOF_STR];
3748 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3749 struct ref_list *list;
3750 size_t bufpos = 0, i;
3751 const char *sep = "Refs: ";
3752 bool is_tag = FALSE;
3754 assert(line->type == LINE_COMMIT);
3756 list = get_ref_list(commit_id);
3757 if (!list) {
3758 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3759 goto try_add_describe_ref;
3760 return;
3763 for (i = 0; i < list->size; i++) {
3764 struct ref *ref = list->refs[i];
3765 const char *fmt = ref->tag ? "%s[%s]" :
3766 ref->remote ? "%s<%s>" : "%s%s";
3768 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3769 return;
3770 sep = ", ";
3771 if (ref->tag)
3772 is_tag = TRUE;
3775 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3776 try_add_describe_ref:
3777 /* Add <tag>-g<commit_id> "fake" reference. */
3778 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3779 return;
3782 if (bufpos == 0)
3783 return;
3785 add_line_text(view, buf, LINE_PP_REFS);
3788 static bool
3789 pager_common_read(struct view *view, char *data, enum line_type type)
3791 struct line *line;
3793 if (!data)
3794 return TRUE;
3796 line = add_line_text(view, data, type);
3797 if (!line)
3798 return FALSE;
3800 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3801 add_pager_refs(view, line);
3803 return TRUE;
3806 static bool
3807 pager_read(struct view *view, char *data)
3809 if (!data)
3810 return TRUE;
3812 return pager_common_read(view, data, get_line_type(data));
3815 static enum request
3816 pager_request(struct view *view, enum request request, struct line *line)
3818 int split = 0;
3820 if (request != REQ_ENTER)
3821 return request;
3823 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3824 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3825 split = 1;
3828 /* Always scroll the view even if it was split. That way
3829 * you can use Enter to scroll through the log view and
3830 * split open each commit diff. */
3831 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3833 /* FIXME: A minor workaround. Scrolling the view will call report("")
3834 * but if we are scrolling a non-current view this won't properly
3835 * update the view title. */
3836 if (split)
3837 update_view_title(view);
3839 return REQ_NONE;
3842 static bool
3843 pager_grep(struct view *view, struct line *line)
3845 const char *text[] = { line->data, NULL };
3847 return grep_text(view, text);
3850 static void
3851 pager_select(struct view *view, struct line *line)
3853 if (line->type == LINE_COMMIT) {
3854 char *text = (char *)line->data + STRING_SIZE("commit ");
3856 if (!view_has_flags(view, VIEW_NO_REF))
3857 string_copy_rev(view->ref, text);
3858 string_copy_rev(ref_commit, text);
3862 static bool
3863 pager_open(struct view *view, enum open_flags flags)
3865 if (display[0] == NULL) {
3866 if (!io_open(&view->io, ""))
3867 die("Failed to open stdin");
3868 flags = OPEN_PREPARED;
3870 } else if (!view->pipe && !view->lines) {
3871 report("No pager content, press %s to run command from prompt",
3872 get_view_key(view, REQ_PROMPT));
3873 return FALSE;
3876 return begin_update(view, NULL, NULL, flags);
3879 static struct view_ops pager_ops = {
3880 "line",
3881 { "pager" },
3882 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3884 pager_open,
3885 pager_read,
3886 pager_draw,
3887 pager_request,
3888 pager_grep,
3889 pager_select,
3892 static bool
3893 log_open(struct view *view, enum open_flags flags)
3895 static const char *log_argv[] = {
3896 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3899 return begin_update(view, NULL, log_argv, flags);
3902 static enum request
3903 log_request(struct view *view, enum request request, struct line *line)
3905 switch (request) {
3906 case REQ_REFRESH:
3907 load_refs();
3908 refresh_view(view);
3909 return REQ_NONE;
3910 default:
3911 return pager_request(view, request, line);
3915 static struct view_ops log_ops = {
3916 "line",
3917 { "log" },
3918 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3920 log_open,
3921 pager_read,
3922 pager_draw,
3923 log_request,
3924 pager_grep,
3925 pager_select,
3928 struct diff_state {
3929 bool reading_diff_stat;
3930 bool combined_diff;
3933 static bool
3934 diff_open(struct view *view, enum open_flags flags)
3936 static const char *diff_argv[] = {
3937 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3938 "--patch-with-stat", "--find-copies-harder", "-C",
3939 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3940 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3943 return begin_update(view, NULL, diff_argv, flags);
3946 static bool
3947 diff_common_read(struct view *view, char *data, struct diff_state *state)
3949 enum line_type type = get_line_type(data);
3951 if (!view->lines && type != LINE_COMMIT)
3952 state->reading_diff_stat = TRUE;
3954 if (state->reading_diff_stat) {
3955 size_t len = strlen(data);
3956 char *pipe = strchr(data, '|');
3957 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3958 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3959 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
3961 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
3962 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3963 } else {
3964 state->reading_diff_stat = FALSE;
3967 } else if (!strcmp(data, "---")) {
3968 state->reading_diff_stat = TRUE;
3971 if (type == LINE_DIFF_HEADER) {
3972 const int len = line_info[LINE_DIFF_HEADER].linelen;
3974 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3975 !strncmp(data + len, "cc ", strlen("cc ")))
3976 state->combined_diff = TRUE;
3979 /* ADD2 and DEL2 are only valid in combined diff hunks */
3980 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3981 type = LINE_DEFAULT;
3983 return pager_common_read(view, data, type);
3986 static bool
3987 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
3989 struct line *marker = find_next_line_by_type(view, line, type);
3991 return marker &&
3992 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
3995 static enum request
3996 diff_common_enter(struct view *view, enum request request, struct line *line)
3998 if (line->type == LINE_DIFF_STAT) {
3999 int file_number = 0;
4001 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4002 file_number++;
4003 line--;
4006 for (line = view->line; view_has_line(view, line); line++) {
4007 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4008 if (!line)
4009 break;
4011 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4012 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4013 if (file_number == 1) {
4014 break;
4016 file_number--;
4020 if (!line) {
4021 report("Failed to find file diff");
4022 return REQ_NONE;
4025 select_view_line(view, line - view->line);
4026 report("");
4027 return REQ_NONE;
4029 } else {
4030 return pager_request(view, request, line);
4034 static bool
4035 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4037 char *sep = strchr(*text, c);
4039 if (sep != NULL) {
4040 *sep = 0;
4041 draw_text(view, *type, *text);
4042 *sep = c;
4043 *text = sep;
4044 *type = next_type;
4047 return sep != NULL;
4050 static bool
4051 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4053 char *text = line->data;
4054 enum line_type type = line->type;
4056 if (draw_lineno(view, lineno))
4057 return TRUE;
4059 if (type == LINE_DIFF_STAT) {
4060 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4061 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4062 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4063 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4064 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4065 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4066 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4068 } else {
4069 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4070 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4074 draw_text(view, type, text);
4075 return TRUE;
4078 static bool
4079 diff_read(struct view *view, char *data)
4081 struct diff_state *state = view->private;
4083 if (!data) {
4084 /* Fall back to retry if no diff will be shown. */
4085 if (view->lines == 0 && opt_file_argv) {
4086 int pos = argv_size(view->argv)
4087 - argv_size(opt_file_argv) - 1;
4089 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4090 for (; view->argv[pos]; pos++) {
4091 free((void *) view->argv[pos]);
4092 view->argv[pos] = NULL;
4095 if (view->pipe)
4096 io_done(view->pipe);
4097 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4098 return FALSE;
4101 return TRUE;
4104 return diff_common_read(view, data, state);
4107 static bool
4108 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4109 struct blame_header *header, struct blame_commit *commit)
4111 char line_arg[SIZEOF_STR];
4112 const char *blame_argv[] = {
4113 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4115 struct io io;
4116 bool ok = FALSE;
4117 char *buf;
4119 if (!string_format(line_arg, "-L%d,+1", lineno))
4120 return FALSE;
4122 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4123 return FALSE;
4125 while ((buf = io_get(&io, '\n', TRUE))) {
4126 if (header) {
4127 if (!parse_blame_header(header, buf, 9999999))
4128 break;
4129 header = NULL;
4131 } else if (parse_blame_info(commit, buf)) {
4132 ok = TRUE;
4133 break;
4137 if (io_error(&io))
4138 ok = FALSE;
4140 io_done(&io);
4141 return ok;
4144 static bool
4145 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4147 return prefixcmp(chunk, "@@ -") ||
4148 !(chunk = strchr(chunk, marker)) ||
4149 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4152 static enum request
4153 diff_trace_origin(struct view *view, struct line *line)
4155 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4156 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4157 const char *chunk_data;
4158 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4159 int lineno = 0;
4160 const char *file = NULL;
4161 char ref[SIZEOF_REF];
4162 struct blame_header header;
4163 struct blame_commit commit;
4165 if (!diff || !chunk || chunk == line) {
4166 report("The line to trace must be inside a diff chunk");
4167 return REQ_NONE;
4170 for (; diff < line && !file; diff++) {
4171 const char *data = diff->data;
4173 if (!prefixcmp(data, "--- a/")) {
4174 file = data + STRING_SIZE("--- a/");
4175 break;
4179 if (diff == line || !file) {
4180 report("Failed to read the file name");
4181 return REQ_NONE;
4184 chunk_data = chunk->data;
4186 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4187 report("Failed to read the line number");
4188 return REQ_NONE;
4191 if (lineno == 0) {
4192 report("This is the origin of the line");
4193 return REQ_NONE;
4196 for (chunk += 1; chunk < line; chunk++) {
4197 if (chunk->type == LINE_DIFF_ADD) {
4198 lineno += chunk_marker == '+';
4199 } else if (chunk->type == LINE_DIFF_DEL) {
4200 lineno += chunk_marker == '-';
4201 } else {
4202 lineno++;
4206 if (chunk_marker == '+')
4207 string_copy(ref, view->vid);
4208 else
4209 string_format(ref, "%s^", view->vid);
4211 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4212 report("Failed to read blame data");
4213 return REQ_NONE;
4216 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4217 string_copy(opt_ref, header.id);
4218 opt_goto_line = header.orig_lineno - 1;
4220 return REQ_VIEW_BLAME;
4223 static enum request
4224 diff_request(struct view *view, enum request request, struct line *line)
4226 switch (request) {
4227 case REQ_VIEW_BLAME:
4228 return diff_trace_origin(view, line);
4230 case REQ_DIFF_CONTEXT_UP:
4231 case REQ_DIFF_CONTEXT_DOWN:
4232 if (!update_diff_context(request))
4233 return REQ_NONE;
4234 reload_view(view);
4235 return REQ_NONE;
4238 case REQ_ENTER:
4239 return diff_common_enter(view, request, line);
4241 default:
4242 return pager_request(view, request, line);
4246 static void
4247 diff_select(struct view *view, struct line *line)
4249 if (line->type == LINE_DIFF_STAT) {
4250 const char *key = get_view_key(view, REQ_ENTER);
4252 string_format(view->ref, "Press '%s' to jump to file diff", key);
4253 } else {
4254 struct line *header = line->type == LINE_DIFF_HEADER ? line :
4255 find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4257 if (header != NULL) {
4258 const char *file_name = NULL;
4260 for (header += 1; view_has_line(view, header); header++) {
4261 if (header->type == LINE_DIFF_RENAME_TO)
4262 file_name = header->data + STRING_SIZE("rename to ");
4263 if (header->type == LINE_DIFF_ADD && !strncmp(header->data, "+++ b/", 6))
4264 file_name = header->data + STRING_SIZE("+++ b/");
4266 /* The diff chunk marks the end of the diff header. */
4267 if (file_name || header->type == LINE_DIFF_CHUNK)
4268 break;
4271 string_format(view->ref, "Diff of '%s'", file_name);
4272 return;
4275 string_ncopy(view->ref, view->id, strlen(view->id));
4276 return pager_select(view, line);
4280 static struct view_ops diff_ops = {
4281 "line",
4282 { "diff" },
4283 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4284 sizeof(struct diff_state),
4285 diff_open,
4286 diff_read,
4287 diff_common_draw,
4288 diff_request,
4289 pager_grep,
4290 diff_select,
4294 * Help backend
4297 static bool
4298 help_draw(struct view *view, struct line *line, unsigned int lineno)
4300 if (line->type == LINE_HELP_KEYMAP) {
4301 struct keymap *keymap = line->data;
4303 draw_formatted(view, line->type, "[%c] %s bindings",
4304 keymap->hidden ? '+' : '-', keymap->name);
4305 return TRUE;
4306 } else {
4307 return pager_draw(view, line, lineno);
4311 static bool
4312 help_open_keymap_title(struct view *view, struct keymap *keymap)
4314 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4315 return keymap->hidden;
4318 static void
4319 help_open_keymap(struct view *view, struct keymap *keymap)
4321 const char *group = NULL;
4322 char buf[SIZEOF_STR];
4323 size_t bufpos;
4324 bool add_title = TRUE;
4325 int i;
4327 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4328 const char *key = NULL;
4330 if (req_info[i].request == REQ_NONE)
4331 continue;
4333 if (!req_info[i].request) {
4334 group = req_info[i].help;
4335 continue;
4338 key = get_keys(keymap, req_info[i].request, TRUE);
4339 if (!key || !*key)
4340 continue;
4342 if (add_title && help_open_keymap_title(view, keymap))
4343 return;
4344 add_title = FALSE;
4346 if (group) {
4347 add_line_text(view, group, LINE_HELP_GROUP);
4348 group = NULL;
4351 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4352 enum_name(req_info[i]), req_info[i].help);
4355 group = "External commands:";
4357 for (i = 0; i < run_requests; i++) {
4358 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4359 const char *key;
4360 int argc;
4362 if (!req || req->keymap != keymap)
4363 continue;
4365 key = get_key_name(req->key);
4366 if (!*key)
4367 key = "(no key defined)";
4369 if (add_title && help_open_keymap_title(view, keymap))
4370 return;
4371 add_title = FALSE;
4373 if (group) {
4374 add_line_text(view, group, LINE_HELP_GROUP);
4375 group = NULL;
4378 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4379 if (!string_format_from(buf, &bufpos, "%s%s",
4380 argc ? " " : "", req->argv[argc]))
4381 return;
4383 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4387 static bool
4388 help_open(struct view *view, enum open_flags flags)
4390 struct keymap *keymap;
4392 reset_view(view);
4393 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4394 add_line_text(view, "", LINE_DEFAULT);
4396 for (keymap = keymaps; keymap; keymap = keymap->next)
4397 help_open_keymap(view, keymap);
4399 return TRUE;
4402 static enum request
4403 help_request(struct view *view, enum request request, struct line *line)
4405 switch (request) {
4406 case REQ_ENTER:
4407 if (line->type == LINE_HELP_KEYMAP) {
4408 struct keymap *keymap = line->data;
4410 keymap->hidden = !keymap->hidden;
4411 refresh_view(view);
4414 return REQ_NONE;
4415 default:
4416 return pager_request(view, request, line);
4420 static struct view_ops help_ops = {
4421 "line",
4422 { "help" },
4423 VIEW_NO_GIT_DIR,
4425 help_open,
4426 NULL,
4427 help_draw,
4428 help_request,
4429 pager_grep,
4430 pager_select,
4435 * Tree backend
4438 struct tree_stack_entry {
4439 struct tree_stack_entry *prev; /* Entry below this in the stack */
4440 unsigned long lineno; /* Line number to restore */
4441 char *name; /* Position of name in opt_path */
4444 /* The top of the path stack. */
4445 static struct tree_stack_entry *tree_stack = NULL;
4446 unsigned long tree_lineno = 0;
4448 static void
4449 pop_tree_stack_entry(void)
4451 struct tree_stack_entry *entry = tree_stack;
4453 tree_lineno = entry->lineno;
4454 entry->name[0] = 0;
4455 tree_stack = entry->prev;
4456 free(entry);
4459 static void
4460 push_tree_stack_entry(const char *name, unsigned long lineno)
4462 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4463 size_t pathlen = strlen(opt_path);
4465 if (!entry)
4466 return;
4468 entry->prev = tree_stack;
4469 entry->name = opt_path + pathlen;
4470 tree_stack = entry;
4472 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4473 pop_tree_stack_entry();
4474 return;
4477 /* Move the current line to the first tree entry. */
4478 tree_lineno = 1;
4479 entry->lineno = lineno;
4482 /* Parse output from git-ls-tree(1):
4484 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4487 #define SIZEOF_TREE_ATTR \
4488 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4490 #define SIZEOF_TREE_MODE \
4491 STRING_SIZE("100644 ")
4493 #define TREE_ID_OFFSET \
4494 STRING_SIZE("100644 blob ")
4496 #define tree_entry_is_parent(entry) (!strcmp("..", (entry)->name))
4498 struct tree_entry {
4499 char id[SIZEOF_REV];
4500 mode_t mode;
4501 struct time time; /* Date from the author ident. */
4502 const char *author; /* Author of the commit. */
4503 char name[1];
4506 struct tree_state {
4507 const char *author_name;
4508 struct time author_time;
4509 bool read_date;
4512 static const char *
4513 tree_path(const struct line *line)
4515 return ((struct tree_entry *) line->data)->name;
4518 static int
4519 tree_compare_entry(const struct line *line1, const struct line *line2)
4521 if (line1->type != line2->type)
4522 return line1->type == LINE_TREE_DIR ? -1 : 1;
4523 return strcmp(tree_path(line1), tree_path(line2));
4526 static const enum sort_field tree_sort_fields[] = {
4527 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4529 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4531 static int
4532 tree_compare(const void *l1, const void *l2)
4534 const struct line *line1 = (const struct line *) l1;
4535 const struct line *line2 = (const struct line *) l2;
4536 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4537 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4539 if (line1->type == LINE_TREE_HEAD)
4540 return -1;
4541 if (line2->type == LINE_TREE_HEAD)
4542 return 1;
4544 switch (get_sort_field(tree_sort_state)) {
4545 case ORDERBY_DATE:
4546 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4548 case ORDERBY_AUTHOR:
4549 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4551 case ORDERBY_NAME:
4552 default:
4553 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4558 static struct line *
4559 tree_entry(struct view *view, enum line_type type, const char *path,
4560 const char *mode, const char *id)
4562 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4563 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4565 if (!entry || !line) {
4566 free(entry);
4567 return NULL;
4570 strncpy(entry->name, path, strlen(path));
4571 if (mode)
4572 entry->mode = strtoul(mode, NULL, 8);
4573 if (id)
4574 string_copy_rev(entry->id, id);
4575 if (type == LINE_TREE_HEAD || tree_entry_is_parent(entry))
4576 view->lineoffset++;
4578 return line;
4581 static bool
4582 tree_read_date(struct view *view, char *text, struct tree_state *state)
4584 if (!text && state->read_date) {
4585 state->read_date = FALSE;
4586 return TRUE;
4588 } else if (!text) {
4589 /* Find next entry to process */
4590 const char *log_file[] = {
4591 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4592 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4595 if (!view->lines) {
4596 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4597 report("Tree is empty");
4598 return TRUE;
4601 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4602 report("Failed to load tree data");
4603 return TRUE;
4606 state->read_date = TRUE;
4607 return FALSE;
4609 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4610 parse_author_line(text + STRING_SIZE("author "),
4611 &state->author_name, &state->author_time);
4613 } else if (*text == ':') {
4614 char *pos;
4615 size_t annotated = 1;
4616 size_t i;
4618 pos = strchr(text, '\t');
4619 if (!pos)
4620 return TRUE;
4621 text = pos + 1;
4622 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4623 text += strlen(opt_path);
4624 pos = strchr(text, '/');
4625 if (pos)
4626 *pos = 0;
4628 for (i = 1; i < view->lines; i++) {
4629 struct line *line = &view->line[i];
4630 struct tree_entry *entry = line->data;
4632 annotated += !!entry->author;
4633 if (entry->author || strcmp(entry->name, text))
4634 continue;
4636 entry->author = state->author_name;
4637 entry->time = state->author_time;
4638 line->dirty = 1;
4639 break;
4642 if (annotated == view->lines)
4643 io_kill(view->pipe);
4645 return TRUE;
4648 static bool
4649 tree_read(struct view *view, char *text)
4651 struct tree_state *state = view->private;
4652 struct tree_entry *data;
4653 struct line *entry, *line;
4654 enum line_type type;
4655 size_t textlen = text ? strlen(text) : 0;
4656 char *path = text + SIZEOF_TREE_ATTR;
4658 if (state->read_date || !text)
4659 return tree_read_date(view, text, state);
4661 if (textlen <= SIZEOF_TREE_ATTR)
4662 return FALSE;
4663 if (view->lines == 0 &&
4664 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4665 return FALSE;
4667 /* Strip the path part ... */
4668 if (*opt_path) {
4669 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4670 size_t striplen = strlen(opt_path);
4672 if (pathlen > striplen)
4673 memmove(path, path + striplen,
4674 pathlen - striplen + 1);
4676 /* Insert "link" to parent directory. */
4677 if (view->lines == 1 &&
4678 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4679 return FALSE;
4682 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4683 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4684 if (!entry)
4685 return FALSE;
4686 data = entry->data;
4688 /* Skip "Directory ..." and ".." line. */
4689 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4690 if (tree_compare_entry(line, entry) <= 0)
4691 continue;
4693 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4695 line->data = data;
4696 line->type = type;
4697 for (; line <= entry; line++)
4698 line->dirty = line->cleareol = 1;
4699 return TRUE;
4702 if (tree_lineno <= view->pos.lineno)
4703 tree_lineno = view->lineoffset;
4705 if (tree_lineno > view->pos.lineno) {
4706 view->pos.lineno = tree_lineno;
4707 tree_lineno = 0;
4710 return TRUE;
4713 static bool
4714 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4716 struct tree_entry *entry = line->data;
4718 if (line->type == LINE_TREE_HEAD) {
4719 if (draw_text(view, line->type, "Directory path /"))
4720 return TRUE;
4721 } else {
4722 if (draw_mode(view, entry->mode))
4723 return TRUE;
4725 if (draw_author(view, entry->author))
4726 return TRUE;
4728 if (draw_date(view, &entry->time))
4729 return TRUE;
4732 draw_text(view, line->type, entry->name);
4733 return TRUE;
4736 static void
4737 open_blob_editor(const char *id)
4739 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4740 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4741 int fd = mkstemp(file);
4743 if (fd == -1)
4744 report("Failed to create temporary file");
4745 else if (!io_run_append(blob_argv, fd))
4746 report("Failed to save blob data to file");
4747 else
4748 open_editor(file);
4749 if (fd != -1)
4750 unlink(file);
4753 static enum request
4754 tree_request(struct view *view, enum request request, struct line *line)
4756 enum open_flags flags;
4757 struct tree_entry *entry = line->data;
4759 switch (request) {
4760 case REQ_VIEW_BLAME:
4761 if (line->type != LINE_TREE_FILE) {
4762 report("Blame only supported for files");
4763 return REQ_NONE;
4766 string_copy(opt_ref, view->vid);
4767 return request;
4769 case REQ_EDIT:
4770 if (line->type != LINE_TREE_FILE) {
4771 report("Edit only supported for files");
4772 } else if (!is_head_commit(view->vid)) {
4773 open_blob_editor(entry->id);
4774 } else {
4775 open_editor(opt_file);
4777 return REQ_NONE;
4779 case REQ_TOGGLE_SORT_FIELD:
4780 case REQ_TOGGLE_SORT_ORDER:
4781 sort_view(view, request, &tree_sort_state, tree_compare);
4782 return REQ_NONE;
4784 case REQ_PARENT:
4785 if (!*opt_path) {
4786 /* quit view if at top of tree */
4787 return REQ_VIEW_CLOSE;
4789 /* fake 'cd ..' */
4790 line = &view->line[1];
4791 break;
4793 case REQ_ENTER:
4794 break;
4796 default:
4797 return request;
4800 /* Cleanup the stack if the tree view is at a different tree. */
4801 while (!*opt_path && tree_stack)
4802 pop_tree_stack_entry();
4804 switch (line->type) {
4805 case LINE_TREE_DIR:
4806 /* Depending on whether it is a subdirectory or parent link
4807 * mangle the path buffer. */
4808 if (line == &view->line[1] && *opt_path) {
4809 pop_tree_stack_entry();
4811 } else {
4812 const char *basename = tree_path(line);
4814 push_tree_stack_entry(basename, view->pos.lineno);
4817 /* Trees and subtrees share the same ID, so they are not not
4818 * unique like blobs. */
4819 flags = OPEN_RELOAD;
4820 request = REQ_VIEW_TREE;
4821 break;
4823 case LINE_TREE_FILE:
4824 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4825 request = REQ_VIEW_BLOB;
4826 break;
4828 default:
4829 return REQ_NONE;
4832 open_view(view, request, flags);
4833 if (request == REQ_VIEW_TREE)
4834 view->pos.lineno = tree_lineno;
4836 return REQ_NONE;
4839 static bool
4840 tree_grep(struct view *view, struct line *line)
4842 struct tree_entry *entry = line->data;
4843 const char *text[] = {
4844 entry->name,
4845 mkauthor(entry->author, opt_author_cols, opt_author),
4846 mkdate(&entry->time, opt_date),
4847 NULL
4850 return grep_text(view, text);
4853 static void
4854 tree_select(struct view *view, struct line *line)
4856 struct tree_entry *entry = line->data;
4858 if (line->type == LINE_TREE_HEAD) {
4859 string_format(view->ref, "Files in /%s", opt_path);
4860 return;
4863 if (line->type == LINE_TREE_DIR && tree_entry_is_parent(entry)) {
4864 string_copy(view->ref, "Open parent directory");
4865 return;
4868 if (line->type == LINE_TREE_FILE) {
4869 string_copy_rev(ref_blob, entry->id);
4870 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4873 string_copy_rev(view->ref, entry->id);
4876 static bool
4877 tree_open(struct view *view, enum open_flags flags)
4879 static const char *tree_argv[] = {
4880 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4883 if (string_rev_is_null(ref_commit)) {
4884 report("No tree exists for this commit");
4885 return FALSE;
4888 if (view->lines == 0 && opt_prefix[0]) {
4889 char *pos = opt_prefix;
4891 while (pos && *pos) {
4892 char *end = strchr(pos, '/');
4894 if (end)
4895 *end = 0;
4896 push_tree_stack_entry(pos, 0);
4897 pos = end;
4898 if (end) {
4899 *end = '/';
4900 pos++;
4904 } else if (strcmp(view->vid, view->id)) {
4905 opt_path[0] = 0;
4908 return begin_update(view, opt_cdup, tree_argv, flags);
4911 static struct view_ops tree_ops = {
4912 "file",
4913 { "tree" },
4914 VIEW_NO_FLAGS,
4915 sizeof(struct tree_state),
4916 tree_open,
4917 tree_read,
4918 tree_draw,
4919 tree_request,
4920 tree_grep,
4921 tree_select,
4924 static bool
4925 blob_open(struct view *view, enum open_flags flags)
4927 static const char *blob_argv[] = {
4928 "git", "cat-file", "blob", "%(blob)", NULL
4931 if (!ref_blob[0]) {
4932 report("No file chosen, press %s to open tree view",
4933 get_view_key(view, REQ_VIEW_TREE));
4934 return FALSE;
4937 view->encoding = get_path_encoding(opt_file, opt_encoding);
4939 return begin_update(view, NULL, blob_argv, flags);
4942 static bool
4943 blob_read(struct view *view, char *line)
4945 if (!line)
4946 return TRUE;
4947 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4950 static enum request
4951 blob_request(struct view *view, enum request request, struct line *line)
4953 switch (request) {
4954 case REQ_EDIT:
4955 open_blob_editor(view->vid);
4956 return REQ_NONE;
4957 default:
4958 return pager_request(view, request, line);
4962 static struct view_ops blob_ops = {
4963 "line",
4964 { "blob" },
4965 VIEW_NO_FLAGS,
4967 blob_open,
4968 blob_read,
4969 pager_draw,
4970 blob_request,
4971 pager_grep,
4972 pager_select,
4976 * Blame backend
4978 * Loading the blame view is a two phase job:
4980 * 1. File content is read either using opt_file from the
4981 * filesystem or using git-cat-file.
4982 * 2. Then blame information is incrementally added by
4983 * reading output from git-blame.
4986 struct blame {
4987 struct blame_commit *commit;
4988 unsigned long lineno;
4989 char text[1];
4992 struct blame_state {
4993 struct blame_commit *commit;
4994 int blamed;
4995 bool done_reading;
4996 bool auto_filename_display;
4999 static bool
5000 blame_detect_filename_display(struct view *view)
5002 bool show_filenames = FALSE;
5003 const char *filename = NULL;
5004 int i;
5006 if (opt_blame_argv) {
5007 for (i = 0; opt_blame_argv[i]; i++) {
5008 if (prefixcmp(opt_blame_argv[i], "-C"))
5009 continue;
5011 show_filenames = TRUE;
5015 for (i = 0; i < view->lines; i++) {
5016 struct blame *blame = view->line[i].data;
5018 if (blame->commit && blame->commit->id[0]) {
5019 if (!filename)
5020 filename = blame->commit->filename;
5021 else if (strcmp(filename, blame->commit->filename))
5022 show_filenames = TRUE;
5026 return show_filenames;
5029 static bool
5030 blame_open(struct view *view, enum open_flags flags)
5032 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5033 char path[SIZEOF_STR];
5034 size_t i;
5036 if (!opt_file[0]) {
5037 report("No file chosen, press %s to open tree view",
5038 get_view_key(view, REQ_VIEW_TREE));
5039 return FALSE;
5042 if (!view->prev && *opt_prefix) {
5043 string_copy(path, opt_file);
5044 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5045 report("Failed to setup the blame view");
5046 return FALSE;
5050 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5051 const char *blame_cat_file_argv[] = {
5052 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5055 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5056 return FALSE;
5059 /* First pass: remove multiple references to the same commit. */
5060 for (i = 0; i < view->lines; i++) {
5061 struct blame *blame = view->line[i].data;
5063 if (blame->commit && blame->commit->id[0])
5064 blame->commit->id[0] = 0;
5065 else
5066 blame->commit = NULL;
5069 /* Second pass: free existing references. */
5070 for (i = 0; i < view->lines; i++) {
5071 struct blame *blame = view->line[i].data;
5073 if (blame->commit)
5074 free(blame->commit);
5077 string_format(view->vid, "%s", opt_file);
5078 string_format(view->ref, "%s ...", opt_file);
5080 return TRUE;
5083 static struct blame_commit *
5084 get_blame_commit(struct view *view, const char *id)
5086 size_t i;
5088 for (i = 0; i < view->lines; i++) {
5089 struct blame *blame = view->line[i].data;
5091 if (!blame->commit)
5092 continue;
5094 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5095 return blame->commit;
5099 struct blame_commit *commit = calloc(1, sizeof(*commit));
5101 if (commit)
5102 string_ncopy(commit->id, id, SIZEOF_REV);
5103 return commit;
5107 static struct blame_commit *
5108 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5110 struct blame_header header;
5111 struct blame_commit *commit;
5112 struct blame *blame;
5114 if (!parse_blame_header(&header, text, view->lines))
5115 return NULL;
5117 commit = get_blame_commit(view, text);
5118 if (!commit)
5119 return NULL;
5121 state->blamed += header.group;
5122 while (header.group--) {
5123 struct line *line = &view->line[header.lineno + header.group - 1];
5125 blame = line->data;
5126 blame->commit = commit;
5127 blame->lineno = header.orig_lineno + header.group - 1;
5128 line->dirty = 1;
5131 return commit;
5134 static bool
5135 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5137 if (!line) {
5138 const char *blame_argv[] = {
5139 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5140 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5143 if (view->lines == 0 && !view->prev)
5144 die("No blame exist for %s", view->vid);
5146 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5147 report("Failed to load blame data");
5148 return TRUE;
5151 if (opt_goto_line > 0) {
5152 select_view_line(view, opt_goto_line);
5153 opt_goto_line = 0;
5156 state->done_reading = TRUE;
5157 return FALSE;
5159 } else {
5160 size_t linelen = strlen(line);
5161 struct blame *blame = malloc(sizeof(*blame) + linelen);
5163 if (!blame)
5164 return FALSE;
5166 blame->commit = NULL;
5167 strncpy(blame->text, line, linelen);
5168 blame->text[linelen] = 0;
5169 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5173 static bool
5174 blame_read(struct view *view, char *line)
5176 struct blame_state *state = view->private;
5178 if (!state->done_reading)
5179 return blame_read_file(view, line, state);
5181 if (!line) {
5182 state->auto_filename_display = blame_detect_filename_display(view);
5183 string_format(view->ref, "%s", view->vid);
5184 if (view_is_displayed(view)) {
5185 update_view_title(view);
5186 redraw_view_from(view, 0);
5188 return TRUE;
5191 if (!state->commit) {
5192 state->commit = read_blame_commit(view, line, state);
5193 string_format(view->ref, "%s %2d%%", view->vid,
5194 view->lines ? state->blamed * 100 / view->lines : 0);
5196 } else if (parse_blame_info(state->commit, line)) {
5197 state->commit = NULL;
5200 return TRUE;
5203 static bool
5204 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5206 struct blame_state *state = view->private;
5207 struct blame *blame = line->data;
5208 struct time *time = NULL;
5209 const char *id = NULL, *author = NULL, *filename = NULL;
5210 enum line_type id_type = LINE_BLAME_ID;
5211 static const enum line_type blame_colors[] = {
5212 LINE_PALETTE_0,
5213 LINE_PALETTE_1,
5214 LINE_PALETTE_2,
5215 LINE_PALETTE_3,
5216 LINE_PALETTE_4,
5217 LINE_PALETTE_5,
5218 LINE_PALETTE_6,
5221 #define BLAME_COLOR(i) \
5222 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5224 if (blame->commit && *blame->commit->filename) {
5225 id = blame->commit->id;
5226 author = blame->commit->author;
5227 filename = blame->commit->filename;
5228 time = &blame->commit->time;
5229 id_type = BLAME_COLOR((long) blame->commit);
5232 if (draw_date(view, time))
5233 return TRUE;
5235 if (draw_author(view, author))
5236 return TRUE;
5238 if (draw_filename(view, filename, state->auto_filename_display))
5239 return TRUE;
5241 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5242 return TRUE;
5244 if (draw_lineno(view, lineno))
5245 return TRUE;
5247 draw_text(view, LINE_DEFAULT, blame->text);
5248 return TRUE;
5251 static bool
5252 check_blame_commit(struct blame *blame, bool check_null_id)
5254 if (!blame->commit)
5255 report("Commit data not loaded yet");
5256 else if (check_null_id && string_rev_is_null(blame->commit->id))
5257 report("No commit exist for the selected line");
5258 else
5259 return TRUE;
5260 return FALSE;
5263 static void
5264 setup_blame_parent_line(struct view *view, struct blame *blame)
5266 char from[SIZEOF_REF + SIZEOF_STR];
5267 char to[SIZEOF_REF + SIZEOF_STR];
5268 const char *diff_tree_argv[] = {
5269 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5270 "--no-color", "-U0", from, to, "--", NULL
5272 struct io io;
5273 int parent_lineno = -1;
5274 int blamed_lineno = -1;
5275 char *line;
5277 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5278 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5279 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5280 return;
5282 while ((line = io_get(&io, '\n', TRUE))) {
5283 if (*line == '@') {
5284 char *pos = strchr(line, '+');
5286 parent_lineno = atoi(line + 4);
5287 if (pos)
5288 blamed_lineno = atoi(pos + 1);
5290 } else if (*line == '+' && parent_lineno != -1) {
5291 if (blame->lineno == blamed_lineno - 1 &&
5292 !strcmp(blame->text, line + 1)) {
5293 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5294 break;
5296 blamed_lineno++;
5300 io_done(&io);
5303 static enum request
5304 blame_request(struct view *view, enum request request, struct line *line)
5306 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5307 struct blame *blame = line->data;
5309 switch (request) {
5310 case REQ_VIEW_BLAME:
5311 if (check_blame_commit(blame, TRUE)) {
5312 string_copy(opt_ref, blame->commit->id);
5313 string_copy(opt_file, blame->commit->filename);
5314 if (blame->lineno)
5315 view->pos.lineno = blame->lineno;
5316 reload_view(view);
5318 break;
5320 case REQ_PARENT:
5321 if (!check_blame_commit(blame, TRUE))
5322 break;
5323 if (!*blame->commit->parent_id) {
5324 report("The selected commit has no parents");
5325 } else {
5326 string_copy_rev(opt_ref, blame->commit->parent_id);
5327 string_copy(opt_file, blame->commit->parent_filename);
5328 setup_blame_parent_line(view, blame);
5329 opt_goto_line = blame->lineno;
5330 reload_view(view);
5332 break;
5334 case REQ_ENTER:
5335 if (!check_blame_commit(blame, FALSE))
5336 break;
5338 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5339 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5340 break;
5342 if (string_rev_is_null(blame->commit->id)) {
5343 struct view *diff = VIEW(REQ_VIEW_DIFF);
5344 const char *diff_parent_argv[] = {
5345 GIT_DIFF_BLAME(opt_diff_context_arg,
5346 opt_ignore_space_arg, view->vid)
5348 const char *diff_no_parent_argv[] = {
5349 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5350 opt_ignore_space_arg, view->vid)
5352 const char **diff_index_argv = *blame->commit->parent_id
5353 ? diff_parent_argv : diff_no_parent_argv;
5355 open_argv(view, diff, diff_index_argv, NULL, flags);
5356 if (diff->pipe)
5357 string_copy_rev(diff->ref, NULL_ID);
5358 } else {
5359 open_view(view, REQ_VIEW_DIFF, flags);
5361 break;
5363 default:
5364 return request;
5367 return REQ_NONE;
5370 static bool
5371 blame_grep(struct view *view, struct line *line)
5373 struct blame *blame = line->data;
5374 struct blame_commit *commit = blame->commit;
5375 const char *text[] = {
5376 blame->text,
5377 commit ? commit->title : "",
5378 commit ? commit->id : "",
5379 commit && opt_author ? commit->author : "",
5380 commit ? mkdate(&commit->time, opt_date) : "",
5381 NULL
5384 return grep_text(view, text);
5387 static void
5388 blame_select(struct view *view, struct line *line)
5390 struct blame *blame = line->data;
5391 struct blame_commit *commit = blame->commit;
5393 if (!commit)
5394 return;
5396 if (string_rev_is_null(commit->id))
5397 string_ncopy(ref_commit, "HEAD", 4);
5398 else
5399 string_copy_rev(ref_commit, commit->id);
5402 static struct view_ops blame_ops = {
5403 "line",
5404 { "blame" },
5405 VIEW_ALWAYS_LINENO,
5406 sizeof(struct blame_state),
5407 blame_open,
5408 blame_read,
5409 blame_draw,
5410 blame_request,
5411 blame_grep,
5412 blame_select,
5416 * Branch backend
5419 struct branch {
5420 const char *author; /* Author of the last commit. */
5421 struct time time; /* Date of the last activity. */
5422 char title[128]; /* First line of the commit message. */
5423 const struct ref *ref; /* Name and commit ID information. */
5426 static const struct ref branch_all;
5427 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5429 static const enum sort_field branch_sort_fields[] = {
5430 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5432 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5434 struct branch_state {
5435 char id[SIZEOF_REV];
5436 size_t max_ref_length;
5439 static int
5440 branch_compare(const void *l1, const void *l2)
5442 const struct branch *branch1 = ((const struct line *) l1)->data;
5443 const struct branch *branch2 = ((const struct line *) l2)->data;
5445 if (branch_is_all(branch1))
5446 return -1;
5447 else if (branch_is_all(branch2))
5448 return 1;
5450 switch (get_sort_field(branch_sort_state)) {
5451 case ORDERBY_DATE:
5452 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5454 case ORDERBY_AUTHOR:
5455 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5457 case ORDERBY_NAME:
5458 default:
5459 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5463 static bool
5464 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5466 struct branch_state *state = view->private;
5467 struct branch *branch = line->data;
5468 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5469 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5471 if (draw_date(view, &branch->time))
5472 return TRUE;
5474 if (draw_author(view, branch->author))
5475 return TRUE;
5477 if (draw_field(view, type, branch_name, state->max_ref_length + 1, FALSE))
5478 return TRUE;
5480 draw_text(view, LINE_DEFAULT, branch->title);
5481 return TRUE;
5484 static enum request
5485 branch_request(struct view *view, enum request request, struct line *line)
5487 struct branch *branch = line->data;
5489 switch (request) {
5490 case REQ_REFRESH:
5491 load_refs();
5492 refresh_view(view);
5493 return REQ_NONE;
5495 case REQ_TOGGLE_SORT_FIELD:
5496 case REQ_TOGGLE_SORT_ORDER:
5497 sort_view(view, request, &branch_sort_state, branch_compare);
5498 return REQ_NONE;
5500 case REQ_ENTER:
5502 const struct ref *ref = branch->ref;
5503 const char *all_branches_argv[] = {
5504 GIT_MAIN_LOG("", branch_is_all(branch) ? "--all" : ref->name, "")
5506 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5508 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5509 return REQ_NONE;
5511 case REQ_JUMP_COMMIT:
5513 int lineno;
5515 for (lineno = 0; lineno < view->lines; lineno++) {
5516 struct branch *branch = view->line[lineno].data;
5518 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5519 select_view_line(view, lineno);
5520 report("");
5521 return REQ_NONE;
5525 default:
5526 return request;
5530 static bool
5531 branch_read(struct view *view, char *line)
5533 struct branch_state *state = view->private;
5534 const char *title = NULL;
5535 const char *author = NULL;
5536 struct time time = {};
5537 size_t i;
5539 if (!line)
5540 return TRUE;
5542 switch (get_line_type(line)) {
5543 case LINE_COMMIT:
5544 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5545 return TRUE;
5547 case LINE_AUTHOR:
5548 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5550 default:
5551 title = line + STRING_SIZE("title ");
5554 for (i = 0; i < view->lines; i++) {
5555 struct branch *branch = view->line[i].data;
5557 if (strcmp(branch->ref->id, state->id))
5558 continue;
5560 if (author) {
5561 branch->author = author;
5562 branch->time = time;
5565 if (title)
5566 string_expand(branch->title, sizeof(branch->title), title, 1);
5568 view->line[i].dirty = TRUE;
5571 return TRUE;
5574 static bool
5575 branch_open_visitor(void *data, const struct ref *ref)
5577 struct view *view = data;
5578 struct branch_state *state = view->private;
5579 struct branch *branch;
5580 size_t ref_length;
5582 if (ref->tag || ref->ltag)
5583 return TRUE;
5585 branch = calloc(1, sizeof(*branch));
5586 if (!branch)
5587 return FALSE;
5589 ref_length = strlen(ref->name);
5590 if (ref_length > state->max_ref_length)
5591 state->max_ref_length = ref_length;
5593 branch->ref = ref;
5594 return !!add_line_data(view, branch, LINE_DEFAULT);
5597 static bool
5598 branch_open(struct view *view, enum open_flags flags)
5600 const char *branch_log[] = {
5601 "git", "log", ENCODING_ARG, "--no-color", "--date=raw",
5602 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5603 "--all", "--simplify-by-decoration", NULL
5606 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5607 report("Failed to load branch data");
5608 return FALSE;
5611 if (branch_open_visitor(view, &branch_all))
5612 view->lineoffset++;
5613 foreach_ref(branch_open_visitor, view);
5615 return TRUE;
5618 static bool
5619 branch_grep(struct view *view, struct line *line)
5621 struct branch *branch = line->data;
5622 const char *text[] = {
5623 branch->ref->name,
5624 mkauthor(branch->author, opt_author_cols, opt_author),
5625 NULL
5628 return grep_text(view, text);
5631 static void
5632 branch_select(struct view *view, struct line *line)
5634 struct branch *branch = line->data;
5636 if (branch_is_all(branch)) {
5637 string_copy(view->ref, "All branches");
5638 return;
5640 string_copy_rev(view->ref, branch->ref->id);
5641 string_copy_rev(ref_commit, branch->ref->id);
5642 string_copy_rev(ref_head, branch->ref->id);
5643 string_copy_rev(ref_branch, branch->ref->name);
5646 static struct view_ops branch_ops = {
5647 "branch",
5648 { "branch" },
5649 VIEW_NO_FLAGS,
5650 sizeof(struct branch_state),
5651 branch_open,
5652 branch_read,
5653 branch_draw,
5654 branch_request,
5655 branch_grep,
5656 branch_select,
5660 * Status backend
5663 struct status {
5664 char status;
5665 struct {
5666 mode_t mode;
5667 char rev[SIZEOF_REV];
5668 char name[SIZEOF_STR];
5669 } old;
5670 struct {
5671 mode_t mode;
5672 char rev[SIZEOF_REV];
5673 char name[SIZEOF_STR];
5674 } new;
5677 static char status_onbranch[SIZEOF_STR];
5678 static struct status stage_status;
5679 static enum line_type stage_line_type;
5681 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5683 /* This should work even for the "On branch" line. */
5684 static inline bool
5685 status_has_none(struct view *view, struct line *line)
5687 return view_has_line(view, line) && !line[1].data;
5690 /* Get fields from the diff line:
5691 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5693 static inline bool
5694 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5696 const char *old_mode = buf + 1;
5697 const char *new_mode = buf + 8;
5698 const char *old_rev = buf + 15;
5699 const char *new_rev = buf + 56;
5700 const char *status = buf + 97;
5702 if (bufsize < 98 ||
5703 old_mode[-1] != ':' ||
5704 new_mode[-1] != ' ' ||
5705 old_rev[-1] != ' ' ||
5706 new_rev[-1] != ' ' ||
5707 status[-1] != ' ')
5708 return FALSE;
5710 file->status = *status;
5712 string_copy_rev(file->old.rev, old_rev);
5713 string_copy_rev(file->new.rev, new_rev);
5715 file->old.mode = strtoul(old_mode, NULL, 8);
5716 file->new.mode = strtoul(new_mode, NULL, 8);
5718 file->old.name[0] = file->new.name[0] = 0;
5720 return TRUE;
5723 static bool
5724 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5726 struct status *unmerged = NULL;
5727 char *buf;
5728 struct io io;
5730 if (!io_run(&io, IO_RD, opt_cdup, argv))
5731 return FALSE;
5733 add_line_data(view, NULL, type);
5735 while ((buf = io_get(&io, 0, TRUE))) {
5736 struct status *file = unmerged;
5738 if (!file) {
5739 file = calloc(1, sizeof(*file));
5740 if (!file || !add_line_data(view, file, type))
5741 goto error_out;
5744 /* Parse diff info part. */
5745 if (status) {
5746 file->status = status;
5747 if (status == 'A')
5748 string_copy(file->old.rev, NULL_ID);
5750 } else if (!file->status || file == unmerged) {
5751 if (!status_get_diff(file, buf, strlen(buf)))
5752 goto error_out;
5754 buf = io_get(&io, 0, TRUE);
5755 if (!buf)
5756 break;
5758 /* Collapse all modified entries that follow an
5759 * associated unmerged entry. */
5760 if (unmerged == file) {
5761 unmerged->status = 'U';
5762 unmerged = NULL;
5763 } else if (file->status == 'U') {
5764 unmerged = file;
5768 /* Grab the old name for rename/copy. */
5769 if (!*file->old.name &&
5770 (file->status == 'R' || file->status == 'C')) {
5771 string_ncopy(file->old.name, buf, strlen(buf));
5773 buf = io_get(&io, 0, TRUE);
5774 if (!buf)
5775 break;
5778 /* git-ls-files just delivers a NUL separated list of
5779 * file names similar to the second half of the
5780 * git-diff-* output. */
5781 string_ncopy(file->new.name, buf, strlen(buf));
5782 if (!*file->old.name)
5783 string_copy(file->old.name, file->new.name);
5784 file = NULL;
5787 if (io_error(&io)) {
5788 error_out:
5789 io_done(&io);
5790 return FALSE;
5793 if (!view->line[view->lines - 1].data)
5794 add_line_data(view, NULL, LINE_STAT_NONE);
5796 io_done(&io);
5797 return TRUE;
5800 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5801 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5803 static const char *status_list_other_argv[] = {
5804 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5807 static const char *status_list_no_head_argv[] = {
5808 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5811 static const char *update_index_argv[] = {
5812 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5815 /* Restore the previous line number to stay in the context or select a
5816 * line with something that can be updated. */
5817 static void
5818 status_restore(struct view *view)
5820 if (!check_position(&view->prev_pos))
5821 return;
5823 if (view->prev_pos.lineno >= view->lines)
5824 view->prev_pos.lineno = view->lines - 1;
5825 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5826 view->prev_pos.lineno++;
5827 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5828 view->prev_pos.lineno--;
5830 /* If the above fails, always skip the "On branch" line. */
5831 if (view->prev_pos.lineno < view->lines)
5832 view->pos.lineno = view->prev_pos.lineno;
5833 else
5834 view->pos.lineno = 1;
5836 if (view->prev_pos.offset > view->pos.lineno)
5837 view->pos.offset = view->pos.lineno;
5838 else if (view->prev_pos.offset < view->lines)
5839 view->pos.offset = view->prev_pos.offset;
5841 clear_position(&view->prev_pos);
5844 static void
5845 status_update_onbranch(void)
5847 static const char *paths[][2] = {
5848 { "rebase-apply/rebasing", "Rebasing" },
5849 { "rebase-apply/applying", "Applying mailbox" },
5850 { "rebase-apply/", "Rebasing mailbox" },
5851 { "rebase-merge/interactive", "Interactive rebase" },
5852 { "rebase-merge/", "Rebase merge" },
5853 { "MERGE_HEAD", "Merging" },
5854 { "BISECT_LOG", "Bisecting" },
5855 { "HEAD", "On branch" },
5857 char buf[SIZEOF_STR];
5858 struct stat stat;
5859 int i;
5861 if (is_initial_commit()) {
5862 string_copy(status_onbranch, "Initial commit");
5863 return;
5866 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5867 char *head = opt_head;
5869 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5870 lstat(buf, &stat) < 0)
5871 continue;
5873 if (!*opt_head) {
5874 struct io io;
5876 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5877 io_read_buf(&io, buf, sizeof(buf))) {
5878 head = buf;
5879 if (!prefixcmp(head, "refs/heads/"))
5880 head += STRING_SIZE("refs/heads/");
5884 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5885 string_copy(status_onbranch, opt_head);
5886 return;
5889 string_copy(status_onbranch, "Not currently on any branch");
5892 /* First parse staged info using git-diff-index(1), then parse unstaged
5893 * info using git-diff-files(1), and finally untracked files using
5894 * git-ls-files(1). */
5895 static bool
5896 status_open(struct view *view, enum open_flags flags)
5898 const char **staged_argv = is_initial_commit() ?
5899 status_list_no_head_argv : status_diff_index_argv;
5900 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
5902 if (opt_is_inside_work_tree == FALSE) {
5903 report("The status view requires a working tree");
5904 return FALSE;
5907 reset_view(view);
5909 add_line_data(view, NULL, LINE_STAT_HEAD);
5910 status_update_onbranch();
5912 io_run_bg(update_index_argv);
5914 if (!opt_untracked_dirs_content)
5915 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5917 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
5918 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5919 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
5920 report("Failed to load status data");
5921 return FALSE;
5924 /* Restore the exact position or use the specialized restore
5925 * mode? */
5926 status_restore(view);
5927 return TRUE;
5930 static bool
5931 status_draw(struct view *view, struct line *line, unsigned int lineno)
5933 struct status *status = line->data;
5934 enum line_type type;
5935 const char *text;
5937 if (!status) {
5938 switch (line->type) {
5939 case LINE_STAT_STAGED:
5940 type = LINE_STAT_SECTION;
5941 text = "Changes to be committed:";
5942 break;
5944 case LINE_STAT_UNSTAGED:
5945 type = LINE_STAT_SECTION;
5946 text = "Changed but not updated:";
5947 break;
5949 case LINE_STAT_UNTRACKED:
5950 type = LINE_STAT_SECTION;
5951 text = "Untracked files:";
5952 break;
5954 case LINE_STAT_NONE:
5955 type = LINE_DEFAULT;
5956 text = " (no files)";
5957 break;
5959 case LINE_STAT_HEAD:
5960 type = LINE_STAT_HEAD;
5961 text = status_onbranch;
5962 break;
5964 default:
5965 return FALSE;
5967 } else {
5968 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5970 buf[0] = status->status;
5971 if (draw_text(view, line->type, buf))
5972 return TRUE;
5973 type = LINE_DEFAULT;
5974 text = status->new.name;
5977 draw_text(view, type, text);
5978 return TRUE;
5981 static enum request
5982 status_enter(struct view *view, struct line *line)
5984 struct status *status = line->data;
5985 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5987 if (line->type == LINE_STAT_NONE ||
5988 (!status && line[1].type == LINE_STAT_NONE)) {
5989 report("No file to diff");
5990 return REQ_NONE;
5993 switch (line->type) {
5994 case LINE_STAT_STAGED:
5995 case LINE_STAT_UNSTAGED:
5996 break;
5998 case LINE_STAT_UNTRACKED:
5999 if (!status) {
6000 report("No file to show");
6001 return REQ_NONE;
6004 if (!suffixcmp(status->new.name, -1, "/")) {
6005 report("Cannot display a directory");
6006 return REQ_NONE;
6008 break;
6010 case LINE_STAT_HEAD:
6011 return REQ_NONE;
6013 default:
6014 die("line type %d not handled in switch", line->type);
6017 if (status) {
6018 stage_status = *status;
6019 } else {
6020 memset(&stage_status, 0, sizeof(stage_status));
6023 stage_line_type = line->type;
6025 open_view(view, REQ_VIEW_STAGE, flags);
6026 return REQ_NONE;
6029 static bool
6030 status_exists(struct view *view, struct status *status, enum line_type type)
6032 unsigned long lineno;
6034 for (lineno = 0; lineno < view->lines; lineno++) {
6035 struct line *line = &view->line[lineno];
6036 struct status *pos = line->data;
6038 if (line->type != type)
6039 continue;
6040 if (!pos && (!status || !status->status) && line[1].data) {
6041 select_view_line(view, lineno);
6042 return TRUE;
6044 if (pos && !strcmp(status->new.name, pos->new.name)) {
6045 select_view_line(view, lineno);
6046 return TRUE;
6050 return FALSE;
6054 static bool
6055 status_update_prepare(struct io *io, enum line_type type)
6057 const char *staged_argv[] = {
6058 "git", "update-index", "-z", "--index-info", NULL
6060 const char *others_argv[] = {
6061 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6064 switch (type) {
6065 case LINE_STAT_STAGED:
6066 return io_run(io, IO_WR, opt_cdup, staged_argv);
6068 case LINE_STAT_UNSTAGED:
6069 case LINE_STAT_UNTRACKED:
6070 return io_run(io, IO_WR, opt_cdup, others_argv);
6072 default:
6073 die("line type %d not handled in switch", type);
6074 return FALSE;
6078 static bool
6079 status_update_write(struct io *io, struct status *status, enum line_type type)
6081 switch (type) {
6082 case LINE_STAT_STAGED:
6083 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6084 status->old.rev, status->old.name, 0);
6086 case LINE_STAT_UNSTAGED:
6087 case LINE_STAT_UNTRACKED:
6088 return io_printf(io, "%s%c", status->new.name, 0);
6090 default:
6091 die("line type %d not handled in switch", type);
6092 return FALSE;
6096 static bool
6097 status_update_file(struct status *status, enum line_type type)
6099 struct io io;
6100 bool result;
6102 if (!status_update_prepare(&io, type))
6103 return FALSE;
6105 result = status_update_write(&io, status, type);
6106 return io_done(&io) && result;
6109 static bool
6110 status_update_files(struct view *view, struct line *line)
6112 char buf[sizeof(view->ref)];
6113 struct io io;
6114 bool result = TRUE;
6115 struct line *pos;
6116 int files = 0;
6117 int file, done;
6118 int cursor_y = -1, cursor_x = -1;
6120 if (!status_update_prepare(&io, line->type))
6121 return FALSE;
6123 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6124 files++;
6126 string_copy(buf, view->ref);
6127 getsyx(cursor_y, cursor_x);
6128 for (file = 0, done = 5; result && file < files; line++, file++) {
6129 int almost_done = file * 100 / files;
6131 if (almost_done > done) {
6132 done = almost_done;
6133 string_format(view->ref, "updating file %u of %u (%d%% done)",
6134 file, files, done);
6135 update_view_title(view);
6136 setsyx(cursor_y, cursor_x);
6137 doupdate();
6139 result = status_update_write(&io, line->data, line->type);
6141 string_copy(view->ref, buf);
6143 return io_done(&io) && result;
6146 static bool
6147 status_update(struct view *view)
6149 struct line *line = &view->line[view->pos.lineno];
6151 assert(view->lines);
6153 if (!line->data) {
6154 if (status_has_none(view, line)) {
6155 report("Nothing to update");
6156 return FALSE;
6159 if (!status_update_files(view, line + 1)) {
6160 report("Failed to update file status");
6161 return FALSE;
6164 } else if (!status_update_file(line->data, line->type)) {
6165 report("Failed to update file status");
6166 return FALSE;
6169 return TRUE;
6172 static bool
6173 status_revert(struct status *status, enum line_type type, bool has_none)
6175 if (!status || type != LINE_STAT_UNSTAGED) {
6176 if (type == LINE_STAT_STAGED) {
6177 report("Cannot revert changes to staged files");
6178 } else if (type == LINE_STAT_UNTRACKED) {
6179 report("Cannot revert changes to untracked files");
6180 } else if (has_none) {
6181 report("Nothing to revert");
6182 } else {
6183 report("Cannot revert changes to multiple files");
6186 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6187 char mode[10] = "100644";
6188 const char *reset_argv[] = {
6189 "git", "update-index", "--cacheinfo", mode,
6190 status->old.rev, status->old.name, NULL
6192 const char *checkout_argv[] = {
6193 "git", "checkout", "--", status->old.name, NULL
6196 if (status->status == 'U') {
6197 string_format(mode, "%5o", status->old.mode);
6199 if (status->old.mode == 0 && status->new.mode == 0) {
6200 reset_argv[2] = "--force-remove";
6201 reset_argv[3] = status->old.name;
6202 reset_argv[4] = NULL;
6205 if (!io_run_fg(reset_argv, opt_cdup))
6206 return FALSE;
6207 if (status->old.mode == 0 && status->new.mode == 0)
6208 return TRUE;
6211 return io_run_fg(checkout_argv, opt_cdup);
6214 return FALSE;
6217 static enum request
6218 status_request(struct view *view, enum request request, struct line *line)
6220 struct status *status = line->data;
6222 switch (request) {
6223 case REQ_STATUS_UPDATE:
6224 if (!status_update(view))
6225 return REQ_NONE;
6226 break;
6228 case REQ_STATUS_REVERT:
6229 if (!status_revert(status, line->type, status_has_none(view, line)))
6230 return REQ_NONE;
6231 break;
6233 case REQ_STATUS_MERGE:
6234 if (!status || status->status != 'U') {
6235 report("Merging only possible for files with unmerged status ('U').");
6236 return REQ_NONE;
6238 open_mergetool(status->new.name);
6239 break;
6241 case REQ_EDIT:
6242 if (!status)
6243 return request;
6244 if (status->status == 'D') {
6245 report("File has been deleted.");
6246 return REQ_NONE;
6249 open_editor(status->new.name);
6250 break;
6252 case REQ_VIEW_BLAME:
6253 if (status)
6254 opt_ref[0] = 0;
6255 return request;
6257 case REQ_ENTER:
6258 /* After returning the status view has been split to
6259 * show the stage view. No further reloading is
6260 * necessary. */
6261 return status_enter(view, line);
6263 case REQ_REFRESH:
6264 /* Simply reload the view. */
6265 break;
6267 default:
6268 return request;
6271 refresh_view(view);
6273 return REQ_NONE;
6276 static void
6277 status_select(struct view *view, struct line *line)
6279 struct status *status = line->data;
6280 char file[SIZEOF_STR] = "all files";
6281 const char *text;
6282 const char *key;
6284 if (status && !string_format(file, "'%s'", status->new.name))
6285 return;
6287 if (!status && line[1].type == LINE_STAT_NONE)
6288 line++;
6290 switch (line->type) {
6291 case LINE_STAT_STAGED:
6292 text = "Press %s to unstage %s for commit";
6293 break;
6295 case LINE_STAT_UNSTAGED:
6296 text = "Press %s to stage %s for commit";
6297 break;
6299 case LINE_STAT_UNTRACKED:
6300 text = "Press %s to stage %s for addition";
6301 break;
6303 case LINE_STAT_HEAD:
6304 case LINE_STAT_NONE:
6305 text = "Nothing to update";
6306 break;
6308 default:
6309 die("line type %d not handled in switch", line->type);
6312 if (status && status->status == 'U') {
6313 text = "Press %s to resolve conflict in %s";
6314 key = get_view_key(view, REQ_STATUS_MERGE);
6316 } else {
6317 key = get_view_key(view, REQ_STATUS_UPDATE);
6320 string_format(view->ref, text, key, file);
6321 if (status)
6322 string_copy(opt_file, status->new.name);
6325 static bool
6326 status_grep(struct view *view, struct line *line)
6328 struct status *status = line->data;
6330 if (status) {
6331 const char buf[2] = { status->status, 0 };
6332 const char *text[] = { status->new.name, buf, NULL };
6334 return grep_text(view, text);
6337 return FALSE;
6340 static struct view_ops status_ops = {
6341 "file",
6342 { "status" },
6343 VIEW_CUSTOM_STATUS,
6345 status_open,
6346 NULL,
6347 status_draw,
6348 status_request,
6349 status_grep,
6350 status_select,
6354 struct stage_state {
6355 struct diff_state diff;
6356 size_t chunks;
6357 int *chunk;
6360 static bool
6361 stage_diff_write(struct io *io, struct line *line, struct line *end)
6363 while (line < end) {
6364 if (!io_write(io, line->data, strlen(line->data)) ||
6365 !io_write(io, "\n", 1))
6366 return FALSE;
6367 line++;
6368 if (line->type == LINE_DIFF_CHUNK ||
6369 line->type == LINE_DIFF_HEADER)
6370 break;
6373 return TRUE;
6376 static bool
6377 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6379 const char *apply_argv[SIZEOF_ARG] = {
6380 "git", "apply", "--whitespace=nowarn", NULL
6382 struct line *diff_hdr;
6383 struct io io;
6384 int argc = 3;
6386 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6387 if (!diff_hdr)
6388 return FALSE;
6390 if (!revert)
6391 apply_argv[argc++] = "--cached";
6392 if (line != NULL)
6393 apply_argv[argc++] = "--unidiff-zero";
6394 if (revert || stage_line_type == LINE_STAT_STAGED)
6395 apply_argv[argc++] = "-R";
6396 apply_argv[argc++] = "-";
6397 apply_argv[argc++] = NULL;
6398 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6399 return FALSE;
6401 if (line != NULL) {
6402 int lineno = 0;
6403 struct line *context = chunk + 1;
6404 const char *markers[] = {
6405 line->type == LINE_DIFF_DEL ? "" : ",0",
6406 line->type == LINE_DIFF_DEL ? ",0" : "",
6409 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6411 while (context < line) {
6412 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6413 break;
6414 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6415 lineno++;
6417 context++;
6420 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6421 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6422 lineno, markers[0], lineno, markers[1]) ||
6423 !stage_diff_write(&io, line, line + 1)) {
6424 chunk = NULL;
6426 } else {
6427 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6428 !stage_diff_write(&io, chunk, view->line + view->lines))
6429 chunk = NULL;
6432 io_done(&io);
6433 io_run_bg(update_index_argv);
6435 return chunk ? TRUE : FALSE;
6438 static bool
6439 stage_update(struct view *view, struct line *line, bool single)
6441 struct line *chunk = NULL;
6443 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6444 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6446 if (chunk) {
6447 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6448 report("Failed to apply chunk");
6449 return FALSE;
6452 } else if (!stage_status.status) {
6453 view = view->parent;
6455 for (line = view->line; view_has_line(view, line); line++)
6456 if (line->type == stage_line_type)
6457 break;
6459 if (!status_update_files(view, line + 1)) {
6460 report("Failed to update files");
6461 return FALSE;
6464 } else if (!status_update_file(&stage_status, stage_line_type)) {
6465 report("Failed to update file");
6466 return FALSE;
6469 return TRUE;
6472 static bool
6473 stage_revert(struct view *view, struct line *line)
6475 struct line *chunk = NULL;
6477 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6478 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6480 if (chunk) {
6481 if (!prompt_yesno("Are you sure you want to revert changes?"))
6482 return FALSE;
6484 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6485 report("Failed to revert chunk");
6486 return FALSE;
6488 return TRUE;
6490 } else {
6491 return status_revert(stage_status.status ? &stage_status : NULL,
6492 stage_line_type, FALSE);
6497 static void
6498 stage_next(struct view *view, struct line *line)
6500 struct stage_state *state = view->private;
6501 int i;
6503 if (!state->chunks) {
6504 for (line = view->line; view_has_line(view, line); line++) {
6505 if (line->type != LINE_DIFF_CHUNK)
6506 continue;
6508 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6509 report("Allocation failure");
6510 return;
6513 state->chunk[state->chunks++] = line - view->line;
6517 for (i = 0; i < state->chunks; i++) {
6518 if (state->chunk[i] > view->pos.lineno) {
6519 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6520 report("Chunk %d of %d", i + 1, state->chunks);
6521 return;
6525 report("No next chunk found");
6528 static enum request
6529 stage_request(struct view *view, enum request request, struct line *line)
6531 switch (request) {
6532 case REQ_STATUS_UPDATE:
6533 if (!stage_update(view, line, FALSE))
6534 return REQ_NONE;
6535 break;
6537 case REQ_STATUS_REVERT:
6538 if (!stage_revert(view, line))
6539 return REQ_NONE;
6540 break;
6542 case REQ_STAGE_UPDATE_LINE:
6543 if (stage_line_type == LINE_STAT_UNTRACKED ||
6544 stage_status.status == 'A') {
6545 report("Staging single lines is not supported for new files");
6546 return REQ_NONE;
6548 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6549 report("Please select a change to stage");
6550 return REQ_NONE;
6552 if (!stage_update(view, line, TRUE))
6553 return REQ_NONE;
6554 break;
6556 case REQ_STAGE_NEXT:
6557 if (stage_line_type == LINE_STAT_UNTRACKED) {
6558 report("File is untracked; press %s to add",
6559 get_view_key(view, REQ_STATUS_UPDATE));
6560 return REQ_NONE;
6562 stage_next(view, line);
6563 return REQ_NONE;
6565 case REQ_EDIT:
6566 if (!stage_status.new.name[0])
6567 return request;
6568 if (stage_status.status == 'D') {
6569 report("File has been deleted.");
6570 return REQ_NONE;
6573 open_editor(stage_status.new.name);
6574 break;
6576 case REQ_REFRESH:
6577 /* Reload everything ... */
6578 break;
6580 case REQ_VIEW_BLAME:
6581 if (stage_status.new.name[0]) {
6582 string_copy(opt_file, stage_status.new.name);
6583 opt_ref[0] = 0;
6585 return request;
6587 case REQ_ENTER:
6588 return diff_common_enter(view, request, line);
6590 case REQ_DIFF_CONTEXT_UP:
6591 case REQ_DIFF_CONTEXT_DOWN:
6592 if (!update_diff_context(request))
6593 return REQ_NONE;
6594 break;
6596 default:
6597 return request;
6600 refresh_view(view->parent);
6602 /* Check whether the staged entry still exists, and close the
6603 * stage view if it doesn't. */
6604 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6605 status_restore(view->parent);
6606 return REQ_VIEW_CLOSE;
6609 refresh_view(view);
6611 return REQ_NONE;
6614 static bool
6615 stage_open(struct view *view, enum open_flags flags)
6617 static const char *no_head_diff_argv[] = {
6618 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6619 stage_status.new.name)
6621 static const char *index_show_argv[] = {
6622 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6623 stage_status.old.name, stage_status.new.name)
6625 static const char *files_show_argv[] = {
6626 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6627 stage_status.old.name, stage_status.new.name)
6629 /* Diffs for unmerged entries are empty when passing the new
6630 * path, so leave out the new path. */
6631 static const char *files_unmerged_argv[] = {
6632 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6633 opt_diff_context_arg, opt_ignore_space_arg, "--",
6634 stage_status.old.name, NULL
6636 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6637 const char **argv = NULL;
6638 const char *info;
6640 if (!stage_line_type) {
6641 report("No stage content, press %s to open the status view and choose file",
6642 get_view_key(view, REQ_VIEW_STATUS));
6643 return FALSE;
6646 view->encoding = NULL;
6648 switch (stage_line_type) {
6649 case LINE_STAT_STAGED:
6650 if (is_initial_commit()) {
6651 argv = no_head_diff_argv;
6652 } else {
6653 argv = index_show_argv;
6655 if (stage_status.status)
6656 info = "Staged changes to %s";
6657 else
6658 info = "Staged changes";
6659 break;
6661 case LINE_STAT_UNSTAGED:
6662 if (stage_status.status != 'U')
6663 argv = files_show_argv;
6664 else
6665 argv = files_unmerged_argv;
6666 if (stage_status.status)
6667 info = "Unstaged changes to %s";
6668 else
6669 info = "Unstaged changes";
6670 break;
6672 case LINE_STAT_UNTRACKED:
6673 info = "Untracked file %s";
6674 argv = file_argv;
6675 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6676 break;
6678 case LINE_STAT_HEAD:
6679 default:
6680 die("line type %d not handled in switch", stage_line_type);
6683 if (!string_format(view->ref, info, stage_status.new.name)
6684 || !argv_copy(&view->argv, argv)) {
6685 report("Failed to open staged view");
6686 return FALSE;
6689 view->vid[0] = 0;
6690 view->dir = opt_cdup;
6691 return begin_update(view, NULL, NULL, flags);
6694 static bool
6695 stage_read(struct view *view, char *data)
6697 struct stage_state *state = view->private;
6699 if (data && diff_common_read(view, data, &state->diff))
6700 return TRUE;
6702 return pager_read(view, data);
6705 static struct view_ops stage_ops = {
6706 "line",
6707 { "stage" },
6708 VIEW_DIFF_LIKE,
6709 sizeof(struct stage_state),
6710 stage_open,
6711 stage_read,
6712 diff_common_draw,
6713 stage_request,
6714 pager_grep,
6715 pager_select,
6720 * Revision graph
6723 static const enum line_type graph_colors[] = {
6724 LINE_PALETTE_0,
6725 LINE_PALETTE_1,
6726 LINE_PALETTE_2,
6727 LINE_PALETTE_3,
6728 LINE_PALETTE_4,
6729 LINE_PALETTE_5,
6730 LINE_PALETTE_6,
6733 static enum line_type get_graph_color(struct graph_symbol *symbol)
6735 if (symbol->commit)
6736 return LINE_GRAPH_COMMIT;
6737 assert(symbol->color < ARRAY_SIZE(graph_colors));
6738 return graph_colors[symbol->color];
6741 static bool
6742 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6744 const char *chars = graph_symbol_to_utf8(symbol);
6746 return draw_text(view, color, chars + !!first);
6749 static bool
6750 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6752 const char *chars = graph_symbol_to_ascii(symbol);
6754 return draw_text(view, color, chars + !!first);
6757 static bool
6758 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6760 const chtype *chars = graph_symbol_to_chtype(symbol);
6762 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6765 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6767 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6769 static const draw_graph_fn fns[] = {
6770 draw_graph_ascii,
6771 draw_graph_chtype,
6772 draw_graph_utf8
6774 draw_graph_fn fn = fns[opt_line_graphics];
6775 int i;
6777 for (i = 0; i < canvas->size; i++) {
6778 struct graph_symbol *symbol = &canvas->symbols[i];
6779 enum line_type color = get_graph_color(symbol);
6781 if (fn(view, symbol, color, i == 0))
6782 return TRUE;
6785 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6789 * Main view backend
6792 struct commit {
6793 char id[SIZEOF_REV]; /* SHA1 ID. */
6794 char title[128]; /* First line of the commit message. */
6795 const char *author; /* Author of the commit. */
6796 struct time time; /* Date from the author ident. */
6797 struct ref_list *refs; /* Repository references. */
6798 struct graph_canvas graph; /* Ancestry chain graphics. */
6801 static struct commit *
6802 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6804 struct graph *graph = view->private;
6805 struct commit *commit;
6807 commit = calloc(1, sizeof(struct commit));
6808 if (!commit)
6809 return NULL;
6811 string_copy_rev(commit->id, ids);
6812 commit->refs = get_ref_list(commit->id);
6813 add_line_data(view, commit, type);
6814 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6815 return commit;
6818 bool
6819 main_has_changes(const char *argv[])
6821 struct io io;
6823 if (!io_run(&io, IO_BG, NULL, argv, -1))
6824 return FALSE;
6825 io_done(&io);
6826 return io.status == 1;
6829 static void
6830 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6832 char ids[SIZEOF_STR] = NULL_ID " ";
6833 struct graph *graph = view->private;
6834 struct commit *commit;
6835 struct timeval now;
6836 struct timezone tz;
6838 if (!parent)
6839 return;
6841 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6843 commit = main_add_commit(view, type, ids, FALSE);
6844 if (!commit)
6845 return;
6847 view->lineoffset++;
6848 if (!gettimeofday(&now, &tz)) {
6849 commit->time.tz = tz.tz_minuteswest * 60;
6850 commit->time.sec = now.tv_sec - commit->time.tz;
6853 commit->author = "";
6854 string_ncopy(commit->title, title, strlen(title));
6855 graph_render_parents(graph);
6858 static void
6859 main_add_changes_commits(struct view *view, const char *parent)
6861 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6862 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6863 const char *staged_parent = NULL_ID;
6864 const char *unstaged_parent = parent;
6866 if (!main_has_changes(unstaged_argv)) {
6867 unstaged_parent = NULL;
6868 staged_parent = parent;
6871 if (!main_has_changes(staged_argv)) {
6872 staged_parent = NULL;
6875 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6876 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6879 static bool
6880 main_open(struct view *view, enum open_flags flags)
6882 static const char *main_argv[] = {
6883 GIT_MAIN_LOG("%(diffargs)", "%(revargs)", "%(fileargs)")
6886 return begin_update(view, NULL, main_argv, flags);
6889 static bool
6890 main_draw(struct view *view, struct line *line, unsigned int lineno)
6892 struct commit *commit = line->data;
6894 if (!commit->author)
6895 return FALSE;
6897 if (draw_lineno(view, lineno))
6898 return TRUE;
6900 if (draw_date(view, &commit->time))
6901 return TRUE;
6903 if (draw_author(view, commit->author))
6904 return TRUE;
6906 if (opt_rev_graph && draw_graph(view, &commit->graph))
6907 return TRUE;
6909 if (draw_refs(view, commit->refs))
6910 return TRUE;
6912 draw_text(view, LINE_DEFAULT, commit->title);
6913 return TRUE;
6916 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6917 static bool
6918 main_read(struct view *view, char *line)
6920 struct graph *graph = view->private;
6921 enum line_type type;
6922 struct commit *commit;
6924 if (!line) {
6925 if (!view->lines && !view->prev)
6926 die("No revisions match the given arguments.");
6927 if (view->lines > 0) {
6928 commit = view->line[view->lines - 1].data;
6929 view->line[view->lines - 1].dirty = 1;
6930 if (!commit->author) {
6931 view->lines--;
6932 free(commit);
6936 done_graph(graph);
6937 return TRUE;
6940 type = get_line_type(line);
6941 if (type == LINE_COMMIT) {
6942 bool is_boundary;
6944 line += STRING_SIZE("commit ");
6945 is_boundary = *line == '-';
6946 if (is_boundary || !isalnum(*line))
6947 line++;
6949 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6950 main_add_changes_commits(view, line);
6952 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6955 if (!view->lines)
6956 return TRUE;
6957 commit = view->line[view->lines - 1].data;
6959 switch (type) {
6960 case LINE_PARENT:
6961 if (!graph->has_parents)
6962 graph_add_parent(graph, line + STRING_SIZE("parent "));
6963 break;
6965 case LINE_AUTHOR:
6966 parse_author_line(line + STRING_SIZE("author "),
6967 &commit->author, &commit->time);
6968 graph_render_parents(graph);
6969 break;
6971 default:
6972 /* Fill in the commit title if it has not already been set. */
6973 if (commit->title[0])
6974 break;
6976 line += STRING_SIZE("title ");
6977 /* Well, if the title starts with a whitespace character,
6978 * try to be forgiving. Otherwise we end up with no title. */
6979 while (isspace(*line))
6980 line++;
6981 if (*line == '\0')
6982 break;
6983 /* FIXME: More graceful handling of titles; append "..." to
6984 * shortened titles, etc. */
6986 string_expand(commit->title, sizeof(commit->title), line, 1);
6987 view->line[view->lines - 1].dirty = 1;
6990 return TRUE;
6993 static enum request
6994 main_request(struct view *view, enum request request, struct line *line)
6996 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6998 switch (request) {
6999 case REQ_NEXT:
7000 case REQ_PREVIOUS:
7001 if (view_is_displayed(view) && display[0] != view)
7002 return request;
7003 /* Do not pass navigation requests to the branch view
7004 * when the main view is maximized. (GH #38) */
7005 move_view(view, request);
7006 break;
7008 case REQ_ENTER:
7009 if (view_is_displayed(view) && display[0] != view)
7010 maximize_view(view, TRUE);
7012 if (line->type == LINE_STAT_UNSTAGED
7013 || line->type == LINE_STAT_STAGED) {
7014 struct view *diff = VIEW(REQ_VIEW_DIFF);
7015 const char *diff_staged_argv[] = {
7016 GIT_DIFF_STAGED(opt_diff_context_arg,
7017 opt_ignore_space_arg, NULL, NULL)
7019 const char *diff_unstaged_argv[] = {
7020 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
7021 opt_ignore_space_arg, NULL, NULL)
7023 const char **diff_argv = line->type == LINE_STAT_STAGED
7024 ? diff_staged_argv : diff_unstaged_argv;
7026 open_argv(view, diff, diff_argv, NULL, flags);
7027 break;
7030 open_view(view, REQ_VIEW_DIFF, flags);
7031 break;
7032 case REQ_REFRESH:
7033 load_refs();
7034 refresh_view(view);
7035 break;
7037 case REQ_JUMP_COMMIT:
7039 int lineno;
7041 for (lineno = 0; lineno < view->lines; lineno++) {
7042 struct commit *commit = view->line[lineno].data;
7044 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7045 select_view_line(view, lineno);
7046 report("");
7047 return REQ_NONE;
7051 report("Unable to find commit '%s'", opt_search);
7052 break;
7054 default:
7055 return request;
7058 return REQ_NONE;
7061 static bool
7062 grep_refs(struct ref_list *list, regex_t *regex)
7064 regmatch_t pmatch;
7065 size_t i;
7067 if (!opt_show_refs || !list)
7068 return FALSE;
7070 for (i = 0; i < list->size; i++) {
7071 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7072 return TRUE;
7075 return FALSE;
7078 static bool
7079 main_grep(struct view *view, struct line *line)
7081 struct commit *commit = line->data;
7082 const char *text[] = {
7083 commit->title,
7084 mkauthor(commit->author, opt_author_cols, opt_author),
7085 mkdate(&commit->time, opt_date),
7086 NULL
7089 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7092 static void
7093 main_select(struct view *view, struct line *line)
7095 struct commit *commit = line->data;
7097 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7098 string_copy(view->ref, commit->title);
7099 else
7100 string_copy_rev(view->ref, commit->id);
7101 string_copy_rev(ref_commit, commit->id);
7104 static struct view_ops main_ops = {
7105 "commit",
7106 { "main" },
7107 VIEW_NO_FLAGS,
7108 sizeof(struct graph),
7109 main_open,
7110 main_read,
7111 main_draw,
7112 main_request,
7113 main_grep,
7114 main_select,
7119 * Status management
7122 /* Whether or not the curses interface has been initialized. */
7123 static bool cursed = FALSE;
7125 /* Terminal hacks and workarounds. */
7126 static bool use_scroll_redrawwin;
7127 static bool use_scroll_status_wclear;
7129 /* The status window is used for polling keystrokes. */
7130 static WINDOW *status_win;
7132 /* Reading from the prompt? */
7133 static bool input_mode = FALSE;
7135 static bool status_empty = FALSE;
7137 /* Update status and title window. */
7138 static void
7139 report(const char *msg, ...)
7141 struct view *view = display[current_view];
7143 if (input_mode)
7144 return;
7146 if (!view) {
7147 char buf[SIZEOF_STR];
7148 int retval;
7150 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7151 die("%s", buf);
7154 if (!status_empty || *msg) {
7155 va_list args;
7157 va_start(args, msg);
7159 wmove(status_win, 0, 0);
7160 if (view->has_scrolled && use_scroll_status_wclear)
7161 wclear(status_win);
7162 if (*msg) {
7163 vwprintw(status_win, msg, args);
7164 status_empty = FALSE;
7165 } else {
7166 status_empty = TRUE;
7168 wclrtoeol(status_win);
7169 wnoutrefresh(status_win);
7171 va_end(args);
7174 update_view_title(view);
7177 static void
7178 init_display(void)
7180 const char *term;
7181 int x, y;
7183 /* Initialize the curses library */
7184 if (isatty(STDIN_FILENO)) {
7185 cursed = !!initscr();
7186 opt_tty = stdin;
7187 } else {
7188 /* Leave stdin and stdout alone when acting as a pager. */
7189 opt_tty = fopen("/dev/tty", "r+");
7190 if (!opt_tty)
7191 die("Failed to open /dev/tty");
7192 cursed = !!newterm(NULL, opt_tty, opt_tty);
7195 if (!cursed)
7196 die("Failed to initialize curses");
7198 nonl(); /* Disable conversion and detect newlines from input. */
7199 cbreak(); /* Take input chars one at a time, no wait for \n */
7200 noecho(); /* Don't echo input */
7201 leaveok(stdscr, FALSE);
7203 if (has_colors())
7204 init_colors();
7206 getmaxyx(stdscr, y, x);
7207 status_win = newwin(1, x, y - 1, 0);
7208 if (!status_win)
7209 die("Failed to create status window");
7211 /* Enable keyboard mapping */
7212 keypad(status_win, TRUE);
7213 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7215 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7216 set_tabsize(opt_tab_size);
7217 #else
7218 TABSIZE = opt_tab_size;
7219 #endif
7221 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7222 if (term && !strcmp(term, "gnome-terminal")) {
7223 /* In the gnome-terminal-emulator, the message from
7224 * scrolling up one line when impossible followed by
7225 * scrolling down one line causes corruption of the
7226 * status line. This is fixed by calling wclear. */
7227 use_scroll_status_wclear = TRUE;
7228 use_scroll_redrawwin = FALSE;
7230 } else if (term && !strcmp(term, "xrvt-xpm")) {
7231 /* No problems with full optimizations in xrvt-(unicode)
7232 * and aterm. */
7233 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7235 } else {
7236 /* When scrolling in (u)xterm the last line in the
7237 * scrolling direction will update slowly. */
7238 use_scroll_redrawwin = TRUE;
7239 use_scroll_status_wclear = FALSE;
7243 static int
7244 get_input(int prompt_position)
7246 struct view *view;
7247 int i, key, cursor_y, cursor_x;
7249 if (prompt_position)
7250 input_mode = TRUE;
7252 while (TRUE) {
7253 bool loading = FALSE;
7255 foreach_view (view, i) {
7256 update_view(view);
7257 if (view_is_displayed(view) && view->has_scrolled &&
7258 use_scroll_redrawwin)
7259 redrawwin(view->win);
7260 view->has_scrolled = FALSE;
7261 if (view->pipe)
7262 loading = TRUE;
7265 /* Update the cursor position. */
7266 if (prompt_position) {
7267 getbegyx(status_win, cursor_y, cursor_x);
7268 cursor_x = prompt_position;
7269 } else {
7270 view = display[current_view];
7271 getbegyx(view->win, cursor_y, cursor_x);
7272 cursor_x = view->width - 1;
7273 cursor_y += view->pos.lineno - view->pos.offset;
7275 setsyx(cursor_y, cursor_x);
7277 /* Refresh, accept single keystroke of input */
7278 doupdate();
7279 nodelay(status_win, loading);
7280 key = wgetch(status_win);
7282 /* wgetch() with nodelay() enabled returns ERR when
7283 * there's no input. */
7284 if (key == ERR) {
7286 } else if (key == KEY_RESIZE) {
7287 int height, width;
7289 getmaxyx(stdscr, height, width);
7291 wresize(status_win, 1, width);
7292 mvwin(status_win, height - 1, 0);
7293 wnoutrefresh(status_win);
7294 resize_display();
7295 redraw_display(TRUE);
7297 } else {
7298 input_mode = FALSE;
7299 if (key == erasechar())
7300 key = KEY_BACKSPACE;
7301 return key;
7306 static char *
7307 prompt_input(const char *prompt, input_handler handler, void *data)
7309 enum input_status status = INPUT_OK;
7310 static char buf[SIZEOF_STR];
7311 size_t pos = 0;
7313 buf[pos] = 0;
7315 while (status == INPUT_OK || status == INPUT_SKIP) {
7316 int key;
7318 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7319 wclrtoeol(status_win);
7321 key = get_input(pos + 1);
7322 switch (key) {
7323 case KEY_RETURN:
7324 case KEY_ENTER:
7325 case '\n':
7326 status = pos ? INPUT_STOP : INPUT_CANCEL;
7327 break;
7329 case KEY_BACKSPACE:
7330 if (pos > 0)
7331 buf[--pos] = 0;
7332 else
7333 status = INPUT_CANCEL;
7334 break;
7336 case KEY_ESC:
7337 status = INPUT_CANCEL;
7338 break;
7340 default:
7341 if (pos >= sizeof(buf)) {
7342 report("Input string too long");
7343 return NULL;
7346 status = handler(data, buf, key);
7347 if (status == INPUT_OK)
7348 buf[pos++] = (char) key;
7352 /* Clear the status window */
7353 status_empty = FALSE;
7354 report("");
7356 if (status == INPUT_CANCEL)
7357 return NULL;
7359 buf[pos++] = 0;
7361 return buf;
7364 static enum input_status
7365 prompt_yesno_handler(void *data, char *buf, int c)
7367 if (c == 'y' || c == 'Y')
7368 return INPUT_STOP;
7369 if (c == 'n' || c == 'N')
7370 return INPUT_CANCEL;
7371 return INPUT_SKIP;
7374 static bool
7375 prompt_yesno(const char *prompt)
7377 char prompt2[SIZEOF_STR];
7379 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7380 return FALSE;
7382 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7385 static enum input_status
7386 read_prompt_handler(void *data, char *buf, int c)
7388 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7391 static char *
7392 read_prompt(const char *prompt)
7394 return prompt_input(prompt, read_prompt_handler, NULL);
7397 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7399 enum input_status status = INPUT_OK;
7400 int size = 0;
7402 while (items[size].text)
7403 size++;
7405 assert(size > 0);
7407 while (status == INPUT_OK) {
7408 const struct menu_item *item = &items[*selected];
7409 int key;
7410 int i;
7412 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7413 prompt, *selected + 1, size);
7414 if (item->hotkey)
7415 wprintw(status_win, "[%c] ", (char) item->hotkey);
7416 wprintw(status_win, "%s", item->text);
7417 wclrtoeol(status_win);
7419 key = get_input(COLS - 1);
7420 switch (key) {
7421 case KEY_RETURN:
7422 case KEY_ENTER:
7423 case '\n':
7424 status = INPUT_STOP;
7425 break;
7427 case KEY_LEFT:
7428 case KEY_UP:
7429 *selected = *selected - 1;
7430 if (*selected < 0)
7431 *selected = size - 1;
7432 break;
7434 case KEY_RIGHT:
7435 case KEY_DOWN:
7436 *selected = (*selected + 1) % size;
7437 break;
7439 case KEY_ESC:
7440 status = INPUT_CANCEL;
7441 break;
7443 default:
7444 for (i = 0; items[i].text; i++)
7445 if (items[i].hotkey == key) {
7446 *selected = i;
7447 status = INPUT_STOP;
7448 break;
7453 /* Clear the status window */
7454 status_empty = FALSE;
7455 report("");
7457 return status != INPUT_CANCEL;
7461 * Repository properties
7465 static void
7466 set_remote_branch(const char *name, const char *value, size_t valuelen)
7468 if (!strcmp(name, ".remote")) {
7469 string_ncopy(opt_remote, value, valuelen);
7471 } else if (*opt_remote && !strcmp(name, ".merge")) {
7472 size_t from = strlen(opt_remote);
7474 if (!prefixcmp(value, "refs/heads/"))
7475 value += STRING_SIZE("refs/heads/");
7477 if (!string_format_from(opt_remote, &from, "/%s", value))
7478 opt_remote[0] = 0;
7482 static void
7483 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7485 const char *argv[SIZEOF_ARG] = { name, "=" };
7486 int argc = 1 + (cmd == option_set_command);
7487 enum option_code error;
7489 if (!argv_from_string(argv, &argc, value))
7490 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7491 else
7492 error = cmd(argc, argv);
7494 if (error != OPT_OK)
7495 warn("Option 'tig.%s': %s", name, option_errors[error]);
7498 static bool
7499 set_environment_variable(const char *name, const char *value)
7501 size_t len = strlen(name) + 1 + strlen(value) + 1;
7502 char *env = malloc(len);
7504 if (env &&
7505 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7506 putenv(env) == 0)
7507 return TRUE;
7508 free(env);
7509 return FALSE;
7512 static void
7513 set_work_tree(const char *value)
7515 char cwd[SIZEOF_STR];
7517 if (!getcwd(cwd, sizeof(cwd)))
7518 die("Failed to get cwd path: %s", strerror(errno));
7519 if (chdir(opt_git_dir) < 0)
7520 die("Failed to chdir(%s): %s", strerror(errno));
7521 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7522 die("Failed to get git path: %s", strerror(errno));
7523 if (chdir(cwd) < 0)
7524 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7525 if (chdir(value) < 0)
7526 die("Failed to chdir(%s): %s", value, strerror(errno));
7527 if (!getcwd(cwd, sizeof(cwd)))
7528 die("Failed to get cwd path: %s", strerror(errno));
7529 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7530 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7531 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7532 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7533 opt_is_inside_work_tree = TRUE;
7536 static void
7537 parse_git_color_option(enum line_type type, char *value)
7539 struct line_info *info = &line_info[type];
7540 const char *argv[SIZEOF_ARG];
7541 int argc = 0;
7542 bool first_color = TRUE;
7543 int i;
7545 if (!argv_from_string(argv, &argc, value))
7546 return;
7548 info->fg = COLOR_DEFAULT;
7549 info->bg = COLOR_DEFAULT;
7550 info->attr = 0;
7552 for (i = 0; i < argc; i++) {
7553 int attr = 0;
7555 if (set_attribute(&attr, argv[i])) {
7556 info->attr |= attr;
7558 } else if (set_color(&attr, argv[i])) {
7559 if (first_color)
7560 info->fg = attr;
7561 else
7562 info->bg = attr;
7563 first_color = FALSE;
7568 static void
7569 set_git_color_option(const char *name, char *value)
7571 static const struct enum_map color_option_map[] = {
7572 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7573 ENUM_MAP("branch.local", LINE_MAIN_REF),
7574 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7575 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7577 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7578 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7579 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7580 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7581 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7582 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7583 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7585 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7587 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7588 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7589 ENUM_MAP("status.added", LINE_STAT_STAGED),
7590 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7591 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7592 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7595 int type = LINE_NONE;
7597 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7598 parse_git_color_option(type, value);
7602 static int
7603 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7605 if (!strcmp(name, "gui.encoding"))
7606 parse_encoding(&opt_encoding, value, TRUE);
7608 else if (!strcmp(name, "core.editor"))
7609 string_ncopy(opt_editor, value, valuelen);
7611 else if (!strcmp(name, "core.worktree"))
7612 set_work_tree(value);
7614 else if (!prefixcmp(name, "tig.color."))
7615 set_repo_config_option(name + 10, value, option_color_command);
7617 else if (!prefixcmp(name, "tig.bind."))
7618 set_repo_config_option(name + 9, value, option_bind_command);
7620 else if (!prefixcmp(name, "tig."))
7621 set_repo_config_option(name + 4, value, option_set_command);
7623 else if (!prefixcmp(name, "color."))
7624 set_git_color_option(name + STRING_SIZE("color."), value);
7626 else if (*opt_head && !prefixcmp(name, "branch.") &&
7627 !strncmp(name + 7, opt_head, strlen(opt_head)))
7628 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7630 return OK;
7633 static int
7634 load_git_config(void)
7636 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7638 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7641 static int
7642 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7644 if (!opt_git_dir[0]) {
7645 string_ncopy(opt_git_dir, name, namelen);
7647 } else if (opt_is_inside_work_tree == -1) {
7648 /* This can be 3 different values depending on the
7649 * version of git being used. If git-rev-parse does not
7650 * understand --is-inside-work-tree it will simply echo
7651 * the option else either "true" or "false" is printed.
7652 * Default to true for the unknown case. */
7653 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7655 } else if (*name == '.') {
7656 string_ncopy(opt_cdup, name, namelen);
7658 } else {
7659 string_ncopy(opt_prefix, name, namelen);
7662 return OK;
7665 static int
7666 load_repo_info(void)
7668 const char *rev_parse_argv[] = {
7669 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7670 "--show-cdup", "--show-prefix", NULL
7673 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7678 * Main
7681 static const char usage[] =
7682 "tig " TIG_VERSION " (" __DATE__ ")\n"
7683 "\n"
7684 "Usage: tig [options] [revs] [--] [paths]\n"
7685 " or: tig show [options] [revs] [--] [paths]\n"
7686 " or: tig blame [options] [rev] [--] path\n"
7687 " or: tig status\n"
7688 " or: tig < [git command output]\n"
7689 "\n"
7690 "Options:\n"
7691 " +<number> Select line <number> in the first view\n"
7692 " -v, --version Show version and exit\n"
7693 " -h, --help Show help message and exit";
7695 static void __NORETURN
7696 quit(int sig)
7698 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7699 if (cursed)
7700 endwin();
7701 exit(0);
7704 static void __NORETURN
7705 die(const char *err, ...)
7707 va_list args;
7709 endwin();
7711 va_start(args, err);
7712 fputs("tig: ", stderr);
7713 vfprintf(stderr, err, args);
7714 fputs("\n", stderr);
7715 va_end(args);
7717 exit(1);
7720 static void
7721 warn(const char *msg, ...)
7723 va_list args;
7725 va_start(args, msg);
7726 fputs("tig warning: ", stderr);
7727 vfprintf(stderr, msg, args);
7728 fputs("\n", stderr);
7729 va_end(args);
7732 static int
7733 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7735 const char ***filter_args = data;
7737 return argv_append(filter_args, name) ? OK : ERR;
7740 static void
7741 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7743 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7744 const char **all_argv = NULL;
7746 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7747 !argv_append_array(&all_argv, argv) ||
7748 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7749 die("Failed to split arguments");
7750 argv_free(all_argv);
7751 free(all_argv);
7754 static void
7755 filter_options(const char *argv[], bool blame)
7757 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7759 if (blame)
7760 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7761 else
7762 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7764 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7767 static enum request
7768 parse_options(int argc, const char *argv[])
7770 enum request request = REQ_VIEW_MAIN;
7771 const char *subcommand;
7772 bool seen_dashdash = FALSE;
7773 const char **filter_argv = NULL;
7774 int i;
7776 if (!isatty(STDIN_FILENO))
7777 return REQ_VIEW_PAGER;
7779 if (argc <= 1)
7780 return REQ_VIEW_MAIN;
7782 subcommand = argv[1];
7783 if (!strcmp(subcommand, "status")) {
7784 if (argc > 2)
7785 warn("ignoring arguments after `%s'", subcommand);
7786 return REQ_VIEW_STATUS;
7788 } else if (!strcmp(subcommand, "blame")) {
7789 request = REQ_VIEW_BLAME;
7791 } else if (!strcmp(subcommand, "show")) {
7792 request = REQ_VIEW_DIFF;
7794 } else {
7795 subcommand = NULL;
7798 for (i = 1 + !!subcommand; i < argc; i++) {
7799 const char *opt = argv[i];
7801 // stop parsing our options after -- and let rev-parse handle the rest
7802 if (!seen_dashdash) {
7803 if (!strcmp(opt, "--")) {
7804 seen_dashdash = TRUE;
7805 continue;
7807 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7808 printf("tig version %s\n", TIG_VERSION);
7809 quit(0);
7811 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7812 printf("%s\n", usage);
7813 quit(0);
7815 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7816 opt_lineno = atoi(opt + 1);
7817 continue;
7822 if (!argv_append(&filter_argv, opt))
7823 die("command too long");
7826 if (filter_argv)
7827 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7829 /* Finish validating and setting up blame options */
7830 if (request == REQ_VIEW_BLAME) {
7831 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7832 die("invalid number of options to blame\n\n%s", usage);
7834 if (opt_rev_argv) {
7835 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7838 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7841 return request;
7845 main(int argc, const char *argv[])
7847 const char *codeset = ENCODING_UTF8;
7848 enum request request = parse_options(argc, argv);
7849 struct view *view;
7850 int i;
7852 signal(SIGINT, quit);
7853 signal(SIGPIPE, SIG_IGN);
7855 if (setlocale(LC_ALL, "")) {
7856 codeset = nl_langinfo(CODESET);
7859 foreach_view(view, i) {
7860 add_keymap(&view->ops->keymap);
7863 if (load_repo_info() == ERR)
7864 die("Failed to load repo info.");
7866 if (load_options() == ERR)
7867 die("Failed to load user config.");
7869 if (load_git_config() == ERR)
7870 die("Failed to load repo config.");
7872 /* Require a git repository unless when running in pager mode. */
7873 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7874 die("Not a git repository");
7876 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7877 char translit[SIZEOF_STR];
7879 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7880 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7881 else
7882 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7883 if (opt_iconv_out == ICONV_NONE)
7884 die("Failed to initialize character set conversion");
7887 if (load_refs() == ERR)
7888 die("Failed to load refs.");
7890 init_display();
7892 while (view_driver(display[current_view], request)) {
7893 int key = get_input(0);
7895 view = display[current_view];
7896 request = get_keybinding(&view->ops->keymap, key);
7898 /* Some low-level request handling. This keeps access to
7899 * status_win restricted. */
7900 switch (request) {
7901 case REQ_NONE:
7902 report("Unknown key, press %s for help",
7903 get_view_key(view, REQ_VIEW_HELP));
7904 break;
7905 case REQ_PROMPT:
7907 char *cmd = read_prompt(":");
7909 if (cmd && string_isnumber(cmd)) {
7910 int lineno = view->pos.lineno + 1;
7912 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7913 select_view_line(view, lineno - 1);
7914 report("");
7915 } else {
7916 report("Unable to parse '%s' as a line number", cmd);
7918 } else if (cmd && iscommit(cmd)) {
7919 string_ncopy(opt_search, cmd, strlen(cmd));
7921 request = view_request(view, REQ_JUMP_COMMIT);
7922 if (request == REQ_JUMP_COMMIT) {
7923 report("Jumping to commits is not supported by the '%s' view", view->name);
7926 } else if (cmd) {
7927 struct view *next = VIEW(REQ_VIEW_PAGER);
7928 const char *argv[SIZEOF_ARG] = { "git" };
7929 int argc = 1;
7931 /* When running random commands, initially show the
7932 * command in the title. However, it maybe later be
7933 * overwritten if a commit line is selected. */
7934 string_ncopy(next->ref, cmd, strlen(cmd));
7936 if (!argv_from_string(argv, &argc, cmd)) {
7937 report("Too many arguments");
7938 } else if (!format_argv(&next->argv, argv, FALSE)) {
7939 report("Argument formatting failed");
7940 } else {
7941 next->dir = NULL;
7942 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7946 request = REQ_NONE;
7947 break;
7949 case REQ_SEARCH:
7950 case REQ_SEARCH_BACK:
7952 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7953 char *search = read_prompt(prompt);
7955 if (search)
7956 string_ncopy(opt_search, search, strlen(search));
7957 else if (*opt_search)
7958 request = request == REQ_SEARCH ?
7959 REQ_FIND_NEXT :
7960 REQ_FIND_PREV;
7961 else
7962 request = REQ_NONE;
7963 break;
7965 default:
7966 break;
7970 quit(0);
7972 return 0;