Move refs code to separate file
[tig.git] / tig.c
blob91c4b22726130ac6b25ae5986de5290800d813e1
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 struct line_info *info;
649 if (type > LINE_NONE) {
650 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
651 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
652 } else {
653 assert(type < ARRAY_SIZE(line_info));
654 return &line_info[type];
658 static inline int
659 get_line_color(enum line_type type)
661 return COLOR_ID(get_line(type)->color_pair);
664 static inline int
665 get_line_attr(enum line_type type)
667 struct line_info *info = get_line(type);
669 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
672 static struct line_info *
673 get_line_info(const char *name)
675 size_t namelen = strlen(name);
676 enum line_type type;
678 for (type = 0; type < ARRAY_SIZE(line_info); type++)
679 if (enum_equals(line_info[type], name, namelen))
680 return &line_info[type];
682 return NULL;
685 static struct line_info *
686 add_custom_color(const char *quoted_line)
688 struct line_info *info;
689 char *line;
690 size_t linelen;
692 if (!realloc_custom_color(&custom_color, custom_colors, 1))
693 die("Failed to alloc custom line info");
695 linelen = strlen(quoted_line) - 1;
696 line = malloc(linelen);
697 if (!line)
698 return NULL;
700 strncpy(line, quoted_line + 1, linelen);
701 line[linelen - 1] = 0;
703 info = &custom_color[custom_colors++];
704 info->name = info->line = line;
705 info->namelen = info->linelen = strlen(line);
707 return info;
710 static void
711 init_line_info_color_pair(struct line_info *info, enum line_type type,
712 int default_bg, int default_fg)
714 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
715 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
716 int i;
718 for (i = 0; i < color_pairs; i++) {
719 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
720 info->color_pair = i;
721 return;
725 if (!realloc_color_pair(&color_pair, color_pairs, 1))
726 die("Failed to alloc color pair");
728 color_pair[color_pairs] = info;
729 info->color_pair = color_pairs++;
730 init_pair(COLOR_ID(info->color_pair), fg, bg);
733 static void
734 init_colors(void)
736 int default_bg = line_info[LINE_DEFAULT].bg;
737 int default_fg = line_info[LINE_DEFAULT].fg;
738 enum line_type type;
740 start_color();
742 if (assume_default_colors(default_fg, default_bg) == ERR) {
743 default_bg = COLOR_BLACK;
744 default_fg = COLOR_WHITE;
747 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
748 struct line_info *info = &line_info[type];
750 init_line_info_color_pair(info, type, default_bg, default_fg);
753 for (type = 0; type < custom_colors; type++) {
754 struct line_info *info = &custom_color[type];
756 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
757 default_bg, default_fg);
761 struct line {
762 enum line_type type;
764 /* State flags */
765 unsigned int selected:1;
766 unsigned int dirty:1;
767 unsigned int cleareol:1;
768 unsigned int dont_free:1;
769 unsigned int other:16;
771 void *data; /* User data */
776 * Keys
779 struct keybinding {
780 int alias;
781 enum request request;
784 static struct keybinding default_keybindings[] = {
785 /* View switching */
786 { 'm', REQ_VIEW_MAIN },
787 { 'd', REQ_VIEW_DIFF },
788 { 'l', REQ_VIEW_LOG },
789 { 't', REQ_VIEW_TREE },
790 { 'f', REQ_VIEW_BLOB },
791 { 'B', REQ_VIEW_BLAME },
792 { 'H', REQ_VIEW_BRANCH },
793 { 'p', REQ_VIEW_PAGER },
794 { 'h', REQ_VIEW_HELP },
795 { 'S', REQ_VIEW_STATUS },
796 { 'c', REQ_VIEW_STAGE },
798 /* View manipulation */
799 { 'q', REQ_VIEW_CLOSE },
800 { KEY_TAB, REQ_VIEW_NEXT },
801 { KEY_RETURN, REQ_ENTER },
802 { KEY_UP, REQ_PREVIOUS },
803 { KEY_CTL('P'), REQ_PREVIOUS },
804 { KEY_DOWN, REQ_NEXT },
805 { KEY_CTL('N'), REQ_NEXT },
806 { 'R', REQ_REFRESH },
807 { KEY_F(5), REQ_REFRESH },
808 { 'O', REQ_MAXIMIZE },
809 { ',', REQ_PARENT },
811 /* View specific */
812 { 'u', REQ_STATUS_UPDATE },
813 { '!', REQ_STATUS_REVERT },
814 { 'M', REQ_STATUS_MERGE },
815 { '1', REQ_STAGE_UPDATE_LINE },
816 { '@', REQ_STAGE_NEXT },
817 { '[', REQ_DIFF_CONTEXT_DOWN },
818 { ']', REQ_DIFF_CONTEXT_UP },
820 /* Cursor navigation */
821 { 'k', REQ_MOVE_UP },
822 { 'j', REQ_MOVE_DOWN },
823 { KEY_HOME, REQ_MOVE_FIRST_LINE },
824 { KEY_END, REQ_MOVE_LAST_LINE },
825 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
826 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
827 { ' ', REQ_MOVE_PAGE_DOWN },
828 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
829 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
830 { 'b', REQ_MOVE_PAGE_UP },
831 { '-', REQ_MOVE_PAGE_UP },
833 /* Scrolling */
834 { '|', REQ_SCROLL_FIRST_COL },
835 { KEY_LEFT, REQ_SCROLL_LEFT },
836 { KEY_RIGHT, REQ_SCROLL_RIGHT },
837 { KEY_IC, REQ_SCROLL_LINE_UP },
838 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
839 { KEY_DC, REQ_SCROLL_LINE_DOWN },
840 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
841 { 'w', REQ_SCROLL_PAGE_UP },
842 { 's', REQ_SCROLL_PAGE_DOWN },
844 /* Searching */
845 { '/', REQ_SEARCH },
846 { '?', REQ_SEARCH_BACK },
847 { 'n', REQ_FIND_NEXT },
848 { 'N', REQ_FIND_PREV },
850 /* Misc */
851 { 'Q', REQ_QUIT },
852 { 'z', REQ_STOP_LOADING },
853 { 'v', REQ_SHOW_VERSION },
854 { 'r', REQ_SCREEN_REDRAW },
855 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
856 { 'o', REQ_OPTIONS },
857 { '.', REQ_TOGGLE_LINENO },
858 { 'D', REQ_TOGGLE_DATE },
859 { 'A', REQ_TOGGLE_AUTHOR },
860 { 'g', REQ_TOGGLE_REV_GRAPH },
861 { '~', REQ_TOGGLE_GRAPHIC },
862 { '#', REQ_TOGGLE_FILENAME },
863 { 'F', REQ_TOGGLE_REFS },
864 { 'I', REQ_TOGGLE_SORT_ORDER },
865 { 'i', REQ_TOGGLE_SORT_FIELD },
866 { 'W', REQ_TOGGLE_IGNORE_SPACE },
867 { ':', REQ_PROMPT },
868 { 'e', REQ_EDIT },
871 struct keymap {
872 const char *name;
873 struct keymap *next;
874 struct keybinding *data;
875 size_t size;
876 bool hidden;
879 static struct keymap generic_keymap = { "generic" };
880 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
882 static struct keymap *keymaps = &generic_keymap;
884 static void
885 add_keymap(struct keymap *keymap)
887 keymap->next = keymaps;
888 keymaps = keymap;
891 static struct keymap *
892 get_keymap(const char *name)
894 struct keymap *keymap = keymaps;
896 while (keymap) {
897 if (!strcasecmp(keymap->name, name))
898 return keymap;
899 keymap = keymap->next;
902 return NULL;
906 static void
907 add_keybinding(struct keymap *table, enum request request, int key)
909 size_t i;
911 for (i = 0; i < table->size; i++) {
912 if (table->data[i].alias == key) {
913 table->data[i].request = request;
914 return;
918 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
919 if (!table->data)
920 die("Failed to allocate keybinding");
921 table->data[table->size].alias = key;
922 table->data[table->size++].request = request;
924 if (request == REQ_NONE && is_generic_keymap(table)) {
925 int i;
927 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
928 if (default_keybindings[i].alias == key)
929 default_keybindings[i].request = REQ_NONE;
933 /* Looks for a key binding first in the given map, then in the generic map, and
934 * lastly in the default keybindings. */
935 static enum request
936 get_keybinding(struct keymap *keymap, int key)
938 size_t i;
940 for (i = 0; i < keymap->size; i++)
941 if (keymap->data[i].alias == key)
942 return keymap->data[i].request;
944 for (i = 0; i < generic_keymap.size; i++)
945 if (generic_keymap.data[i].alias == key)
946 return generic_keymap.data[i].request;
948 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
949 if (default_keybindings[i].alias == key)
950 return default_keybindings[i].request;
952 return (enum request) key;
956 struct key {
957 const char *name;
958 int value;
961 static const struct key key_table[] = {
962 { "Enter", KEY_RETURN },
963 { "Space", ' ' },
964 { "Backspace", KEY_BACKSPACE },
965 { "Tab", KEY_TAB },
966 { "Escape", KEY_ESC },
967 { "Left", KEY_LEFT },
968 { "Right", KEY_RIGHT },
969 { "Up", KEY_UP },
970 { "Down", KEY_DOWN },
971 { "Insert", KEY_IC },
972 { "Delete", KEY_DC },
973 { "Hash", '#' },
974 { "Home", KEY_HOME },
975 { "End", KEY_END },
976 { "PageUp", KEY_PPAGE },
977 { "PageDown", KEY_NPAGE },
978 { "F1", KEY_F(1) },
979 { "F2", KEY_F(2) },
980 { "F3", KEY_F(3) },
981 { "F4", KEY_F(4) },
982 { "F5", KEY_F(5) },
983 { "F6", KEY_F(6) },
984 { "F7", KEY_F(7) },
985 { "F8", KEY_F(8) },
986 { "F9", KEY_F(9) },
987 { "F10", KEY_F(10) },
988 { "F11", KEY_F(11) },
989 { "F12", KEY_F(12) },
992 static int
993 get_key_value(const char *name)
995 int i;
997 for (i = 0; i < ARRAY_SIZE(key_table); i++)
998 if (!strcasecmp(key_table[i].name, name))
999 return key_table[i].value;
1001 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1002 return (int)name[1] & 0x1f;
1003 if (strlen(name) == 1 && isprint(*name))
1004 return (int) *name;
1005 return ERR;
1008 static const char *
1009 get_key_name(int key_value)
1011 static char key_char[] = "'X'\0";
1012 const char *seq = NULL;
1013 int key;
1015 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1016 if (key_table[key].value == key_value)
1017 seq = key_table[key].name;
1019 if (seq == NULL && key_value < 0x7f) {
1020 char *s = key_char + 1;
1022 if (key_value >= 0x20) {
1023 *s++ = key_value;
1024 } else {
1025 *s++ = '^';
1026 *s++ = 0x40 | (key_value & 0x1f);
1028 *s++ = '\'';
1029 *s++ = '\0';
1030 seq = key_char;
1033 return seq ? seq : "(no key)";
1036 static bool
1037 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1039 const char *sep = *pos > 0 ? ", " : "";
1040 const char *keyname = get_key_name(keybinding->alias);
1042 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1045 static bool
1046 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1047 struct keymap *keymap, bool all)
1049 int i;
1051 for (i = 0; i < keymap->size; i++) {
1052 if (keymap->data[i].request == request) {
1053 if (!append_key(buf, pos, &keymap->data[i]))
1054 return FALSE;
1055 if (!all)
1056 break;
1060 return TRUE;
1063 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1065 static const char *
1066 get_keys(struct keymap *keymap, enum request request, bool all)
1068 static char buf[BUFSIZ];
1069 size_t pos = 0;
1070 int i;
1072 buf[pos] = 0;
1074 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1075 return "Too many keybindings!";
1076 if (pos > 0 && !all)
1077 return buf;
1079 if (!is_generic_keymap(keymap)) {
1080 /* Only the generic keymap includes the default keybindings when
1081 * listing all keys. */
1082 if (all)
1083 return buf;
1085 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1086 return "Too many keybindings!";
1087 if (pos)
1088 return buf;
1091 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1092 if (default_keybindings[i].request == request) {
1093 if (!append_key(buf, &pos, &default_keybindings[i]))
1094 return "Too many keybindings!";
1095 if (!all)
1096 return buf;
1100 return buf;
1103 struct run_request {
1104 struct keymap *keymap;
1105 int key;
1106 const char **argv;
1107 bool silent;
1110 static struct run_request *run_request;
1111 static size_t run_requests;
1113 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1115 static bool
1116 add_run_request(struct keymap *keymap, int key, const char **argv, bool silent, bool force)
1118 struct run_request *req;
1120 if (!force && get_keybinding(keymap, key) != key)
1121 return TRUE;
1123 if (!realloc_run_requests(&run_request, run_requests, 1))
1124 return FALSE;
1126 if (!argv_copy(&run_request[run_requests].argv, argv))
1127 return FALSE;
1129 req = &run_request[run_requests++];
1130 req->silent = silent;
1131 req->keymap = keymap;
1132 req->key = key;
1134 add_keybinding(keymap, REQ_NONE + run_requests, key);
1135 return TRUE;
1138 static struct run_request *
1139 get_run_request(enum request request)
1141 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1142 return NULL;
1143 return &run_request[request - REQ_NONE - 1];
1146 static void
1147 add_builtin_run_requests(void)
1149 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1150 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1151 const char *commit[] = { "git", "commit", NULL };
1152 const char *gc[] = { "git", "gc", NULL };
1154 add_run_request(get_keymap("main"), 'C', cherry_pick, FALSE, FALSE);
1155 add_run_request(get_keymap("status"), 'C', commit, FALSE, FALSE);
1156 add_run_request(get_keymap("branch"), 'C', checkout, FALSE, FALSE);
1157 add_run_request(get_keymap("generic"), 'G', gc, FALSE, FALSE);
1161 * User config file handling.
1164 #define OPT_ERR_INFO \
1165 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1166 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1167 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1168 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1169 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1170 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1171 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1172 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1173 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1174 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1175 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1176 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1177 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1178 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1179 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1180 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1181 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1182 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1183 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1185 enum option_code {
1186 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1187 OPT_ERR_INFO
1188 #undef OPT_ERR_
1189 OPT_OK
1192 static const char *option_errors[] = {
1193 #define OPT_ERR_(name, msg) msg
1194 OPT_ERR_INFO
1195 #undef OPT_ERR_
1198 static const struct enum_map color_map[] = {
1199 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1200 COLOR_MAP(DEFAULT),
1201 COLOR_MAP(BLACK),
1202 COLOR_MAP(BLUE),
1203 COLOR_MAP(CYAN),
1204 COLOR_MAP(GREEN),
1205 COLOR_MAP(MAGENTA),
1206 COLOR_MAP(RED),
1207 COLOR_MAP(WHITE),
1208 COLOR_MAP(YELLOW),
1211 static const struct enum_map attr_map[] = {
1212 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1213 ATTR_MAP(NORMAL),
1214 ATTR_MAP(BLINK),
1215 ATTR_MAP(BOLD),
1216 ATTR_MAP(DIM),
1217 ATTR_MAP(REVERSE),
1218 ATTR_MAP(STANDOUT),
1219 ATTR_MAP(UNDERLINE),
1222 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1224 static enum option_code
1225 parse_step(double *opt, const char *arg)
1227 *opt = atoi(arg);
1228 if (!strchr(arg, '%'))
1229 return OPT_OK;
1231 /* "Shift down" so 100% and 1 does not conflict. */
1232 *opt = (*opt - 1) / 100;
1233 if (*opt >= 1.0) {
1234 *opt = 0.99;
1235 return OPT_ERR_INVALID_STEP_VALUE;
1237 if (*opt < 0.0) {
1238 *opt = 1;
1239 return OPT_ERR_INVALID_STEP_VALUE;
1241 return OPT_OK;
1244 static enum option_code
1245 parse_int(int *opt, const char *arg, int min, int max)
1247 int value = atoi(arg);
1249 if (min <= value && value <= max) {
1250 *opt = value;
1251 return OPT_OK;
1254 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1257 static bool
1258 set_color(int *color, const char *name)
1260 if (map_enum(color, color_map, name))
1261 return TRUE;
1262 if (!prefixcmp(name, "color"))
1263 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1264 return FALSE;
1267 /* Wants: object fgcolor bgcolor [attribute] */
1268 static enum option_code
1269 option_color_command(int argc, const char *argv[])
1271 struct line_info *info;
1273 if (argc < 3)
1274 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1276 if (*argv[0] == '"' || *argv[0] == '\'') {
1277 info = add_custom_color(argv[0]);
1278 } else {
1279 info = get_line_info(argv[0]);
1281 if (!info) {
1282 static const struct enum_map obsolete[] = {
1283 ENUM_MAP("main-delim", LINE_DELIMITER),
1284 ENUM_MAP("main-date", LINE_DATE),
1285 ENUM_MAP("main-author", LINE_AUTHOR),
1287 int index;
1289 if (!map_enum(&index, obsolete, argv[0]))
1290 return OPT_ERR_UNKNOWN_COLOR_NAME;
1291 info = &line_info[index];
1294 if (!set_color(&info->fg, argv[1]) ||
1295 !set_color(&info->bg, argv[2]))
1296 return OPT_ERR_UNKNOWN_COLOR;
1298 info->attr = 0;
1299 while (argc-- > 3) {
1300 int attr;
1302 if (!set_attribute(&attr, argv[argc]))
1303 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1304 info->attr |= attr;
1307 return OPT_OK;
1310 static enum option_code
1311 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1313 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1314 ? TRUE : FALSE;
1315 if (matched)
1316 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1317 return OPT_OK;
1320 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1322 static enum option_code
1323 parse_enum_do(unsigned int *opt, const char *arg,
1324 const struct enum_map *map, size_t map_size)
1326 bool is_true;
1328 assert(map_size > 1);
1330 if (map_enum_do(map, map_size, (int *) opt, arg))
1331 return OPT_OK;
1333 parse_bool(&is_true, arg);
1334 *opt = is_true ? map[1].value : map[0].value;
1335 return OPT_OK;
1338 #define parse_enum(opt, arg, map) \
1339 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1341 static enum option_code
1342 parse_string(char *opt, const char *arg, size_t optsize)
1344 int arglen = strlen(arg);
1346 switch (arg[0]) {
1347 case '\"':
1348 case '\'':
1349 if (arglen == 1 || arg[arglen - 1] != arg[0])
1350 return OPT_ERR_UNMATCHED_QUOTATION;
1351 arg += 1; arglen -= 2;
1352 default:
1353 string_ncopy_do(opt, optsize, arg, arglen);
1354 return OPT_OK;
1358 static enum option_code
1359 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1361 char buf[SIZEOF_STR];
1362 enum option_code code = parse_string(buf, arg, sizeof(buf));
1364 if (code == OPT_OK) {
1365 struct encoding *encoding = *encoding_ref;
1367 if (encoding && !priority)
1368 return code;
1369 encoding = encoding_open(buf);
1370 if (encoding)
1371 *encoding_ref = encoding;
1374 return code;
1377 static enum option_code
1378 parse_args(const char ***args, const char *argv[])
1380 if (*args == NULL && !argv_copy(args, argv))
1381 return OPT_ERR_OUT_OF_MEMORY;
1382 return OPT_OK;
1385 /* Wants: name = value */
1386 static enum option_code
1387 option_set_command(int argc, const char *argv[])
1389 if (argc < 3)
1390 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1392 if (strcmp(argv[1], "="))
1393 return OPT_ERR_NO_VALUE_ASSIGNED;
1395 if (!strcmp(argv[0], "blame-options"))
1396 return parse_args(&opt_blame_argv, argv + 2);
1398 if (argc != 3)
1399 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1401 if (!strcmp(argv[0], "show-author"))
1402 return parse_enum(&opt_author, argv[2], author_map);
1404 if (!strcmp(argv[0], "show-date"))
1405 return parse_enum(&opt_date, argv[2], date_map);
1407 if (!strcmp(argv[0], "show-rev-graph"))
1408 return parse_bool(&opt_rev_graph, argv[2]);
1410 if (!strcmp(argv[0], "show-refs"))
1411 return parse_bool(&opt_show_refs, argv[2]);
1413 if (!strcmp(argv[0], "show-changes"))
1414 return parse_bool(&opt_show_changes, argv[2]);
1416 if (!strcmp(argv[0], "show-notes")) {
1417 bool matched = FALSE;
1418 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1420 if (res == OPT_OK && matched) {
1421 update_notes_arg();
1422 return res;
1425 opt_notes = TRUE;
1426 strcpy(opt_notes_arg, "--show-notes=");
1427 res = parse_string(opt_notes_arg + 8, argv[2],
1428 sizeof(opt_notes_arg) - 8);
1429 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1430 opt_notes_arg[7] = '\0';
1431 return res;
1434 if (!strcmp(argv[0], "show-line-numbers"))
1435 return parse_bool(&opt_line_number, argv[2]);
1437 if (!strcmp(argv[0], "line-graphics"))
1438 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1440 if (!strcmp(argv[0], "line-number-interval"))
1441 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1443 if (!strcmp(argv[0], "author-width"))
1444 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1446 if (!strcmp(argv[0], "filename-width"))
1447 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1449 if (!strcmp(argv[0], "show-filename"))
1450 return parse_enum(&opt_filename, argv[2], filename_map);
1452 if (!strcmp(argv[0], "horizontal-scroll"))
1453 return parse_step(&opt_hscroll, argv[2]);
1455 if (!strcmp(argv[0], "split-view-height"))
1456 return parse_step(&opt_scale_split_view, argv[2]);
1458 if (!strcmp(argv[0], "tab-size"))
1459 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1461 if (!strcmp(argv[0], "diff-context")) {
1462 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1464 if (code == OPT_OK)
1465 update_diff_context_arg(opt_diff_context);
1466 return code;
1469 if (!strcmp(argv[0], "ignore-space")) {
1470 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1472 if (code == OPT_OK)
1473 update_ignore_space_arg();
1474 return code;
1477 if (!strcmp(argv[0], "commit-order")) {
1478 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1480 if (code == OPT_OK)
1481 update_commit_order_arg();
1482 return code;
1485 if (!strcmp(argv[0], "status-untracked-dirs"))
1486 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1488 if (!strcmp(argv[0], "use-git-colors"))
1489 return parse_bool(&opt_read_git_colors, argv[2]);
1491 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1494 /* Wants: mode request key */
1495 static enum option_code
1496 option_bind_command(int argc, const char *argv[])
1498 enum request request;
1499 struct keymap *keymap;
1500 int key;
1502 if (argc < 3)
1503 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1505 if (!(keymap = get_keymap(argv[0])))
1506 return OPT_ERR_UNKNOWN_KEY_MAP;
1508 key = get_key_value(argv[1]);
1509 if (key == ERR)
1510 return OPT_ERR_UNKNOWN_KEY;
1512 request = get_request(argv[2]);
1513 if (request == REQ_UNKNOWN) {
1514 static const struct enum_map obsolete[] = {
1515 ENUM_MAP("cherry-pick", REQ_NONE),
1516 ENUM_MAP("screen-resize", REQ_NONE),
1517 ENUM_MAP("tree-parent", REQ_PARENT),
1519 int alias;
1521 if (map_enum(&alias, obsolete, argv[2])) {
1522 if (alias != REQ_NONE)
1523 add_keybinding(keymap, alias, key);
1524 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1527 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1528 bool silent = *argv[2] == '@';
1530 if (silent)
1531 argv[2]++;
1532 return add_run_request(keymap, key, argv + 2, silent, TRUE)
1533 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1535 if (request == REQ_UNKNOWN)
1536 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1538 add_keybinding(keymap, request, key);
1540 return OPT_OK;
1544 static enum option_code load_option_file(const char *path);
1546 static enum option_code
1547 option_source_command(int argc, const char *argv[])
1549 if (argc < 1)
1550 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1552 return load_option_file(argv[0]);
1555 static enum option_code
1556 set_option(const char *opt, char *value)
1558 const char *argv[SIZEOF_ARG];
1559 int argc = 0;
1561 if (!argv_from_string(argv, &argc, value))
1562 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1564 if (!strcmp(opt, "color"))
1565 return option_color_command(argc, argv);
1567 if (!strcmp(opt, "set"))
1568 return option_set_command(argc, argv);
1570 if (!strcmp(opt, "bind"))
1571 return option_bind_command(argc, argv);
1573 if (!strcmp(opt, "source"))
1574 return option_source_command(argc, argv);
1576 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1579 struct config_state {
1580 const char *path;
1581 int lineno;
1582 bool errors;
1585 static int
1586 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1588 struct config_state *config = data;
1589 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1591 config->lineno++;
1593 /* Check for comment markers, since read_properties() will
1594 * only ensure opt and value are split at first " \t". */
1595 optlen = strcspn(opt, "#");
1596 if (optlen == 0)
1597 return OK;
1599 if (opt[optlen] == 0) {
1600 /* Look for comment endings in the value. */
1601 size_t len = strcspn(value, "#");
1603 if (len < valuelen) {
1604 valuelen = len;
1605 value[valuelen] = 0;
1608 status = set_option(opt, value);
1611 if (status != OPT_OK) {
1612 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1613 option_errors[status], (int) optlen, opt);
1614 config->errors = TRUE;
1617 /* Always keep going if errors are encountered. */
1618 return OK;
1621 static enum option_code
1622 load_option_file(const char *path)
1624 struct config_state config = { path, 0, FALSE };
1625 struct io io;
1627 /* Do not read configuration from stdin if set to "" */
1628 if (!path || !strlen(path))
1629 return OPT_OK;
1631 /* It's OK that the file doesn't exist. */
1632 if (!io_open(&io, "%s", path))
1633 return OPT_ERR_FILE_DOES_NOT_EXIST;
1635 if (io_load(&io, " \t", read_option, &config) == ERR ||
1636 config.errors == TRUE)
1637 warn("Errors while loading %s.", path);
1638 return OPT_OK;
1641 static int
1642 load_options(void)
1644 const char *home = getenv("HOME");
1645 const char *tigrc_user = getenv("TIGRC_USER");
1646 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1647 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1648 char buf[SIZEOF_STR];
1650 if (!tigrc_system)
1651 tigrc_system = SYSCONFDIR "/tigrc";
1652 load_option_file(tigrc_system);
1654 if (!tigrc_user) {
1655 if (!home || !string_format(buf, "%s/.tigrc", home))
1656 return ERR;
1657 tigrc_user = buf;
1659 load_option_file(tigrc_user);
1661 /* Add _after_ loading config files to avoid adding run requests
1662 * that conflict with keybindings. */
1663 add_builtin_run_requests();
1665 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1666 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1667 int argc = 0;
1669 if (!string_format(buf, "%s", tig_diff_opts) ||
1670 !argv_from_string(diff_opts, &argc, buf))
1671 die("TIG_DIFF_OPTS contains too many arguments");
1672 else if (!argv_copy(&opt_diff_argv, diff_opts))
1673 die("Failed to format TIG_DIFF_OPTS arguments");
1676 return OK;
1681 * The viewer
1684 struct view;
1685 struct view_ops;
1687 /* The display array of active views and the index of the current view. */
1688 static struct view *display[2];
1689 static WINDOW *display_win[2];
1690 static WINDOW *display_title[2];
1691 static unsigned int current_view;
1693 #define foreach_displayed_view(view, i) \
1694 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1696 #define displayed_views() (display[1] != NULL ? 2 : 1)
1698 /* Current head and commit ID */
1699 static char ref_blob[SIZEOF_REF] = "";
1700 static char ref_commit[SIZEOF_REF] = "HEAD";
1701 static char ref_head[SIZEOF_REF] = "HEAD";
1702 static char ref_branch[SIZEOF_REF] = "";
1704 enum view_flag {
1705 VIEW_NO_FLAGS = 0,
1706 VIEW_ALWAYS_LINENO = 1 << 0,
1707 VIEW_CUSTOM_STATUS = 1 << 1,
1708 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1709 VIEW_ADD_PAGER_REFS = 1 << 3,
1710 VIEW_OPEN_DIFF = 1 << 4,
1711 VIEW_NO_REF = 1 << 5,
1712 VIEW_NO_GIT_DIR = 1 << 6,
1713 VIEW_DIFF_LIKE = 1 << 7,
1716 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1718 struct position {
1719 unsigned long offset; /* Offset of the window top */
1720 unsigned long col; /* Offset from the window side. */
1721 unsigned long lineno; /* Current line number */
1724 struct view {
1725 const char *name; /* View name */
1726 const char *id; /* Points to either of ref_{head,commit,blob} */
1728 struct view_ops *ops; /* View operations */
1730 char ref[SIZEOF_REF]; /* Hovered commit reference */
1731 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1733 int height, width; /* The width and height of the main window */
1734 WINDOW *win; /* The main window */
1736 /* Navigation */
1737 struct position pos; /* Current position. */
1738 struct position prev_pos; /* Previous position. */
1740 /* Searching */
1741 char grep[SIZEOF_STR]; /* Search string */
1742 regex_t *regex; /* Pre-compiled regexp */
1744 /* If non-NULL, points to the view that opened this view. If this view
1745 * is closed tig will switch back to the parent view. */
1746 struct view *parent;
1747 struct view *prev;
1749 /* Buffering */
1750 size_t lines; /* Total number of lines */
1751 struct line *line; /* Line index */
1752 unsigned int digits; /* Number of digits in the lines member. */
1754 /* Drawing */
1755 struct line *curline; /* Line currently being drawn. */
1756 enum line_type curtype; /* Attribute currently used for drawing. */
1757 unsigned long col; /* Column when drawing. */
1758 bool has_scrolled; /* View was scrolled. */
1760 /* Loading */
1761 const char **argv; /* Shell command arguments. */
1762 const char *dir; /* Directory from which to execute. */
1763 struct io io;
1764 struct io *pipe;
1765 time_t start_time;
1766 time_t update_secs;
1767 struct encoding *encoding;
1769 /* Private data */
1770 void *private;
1773 enum open_flags {
1774 OPEN_DEFAULT = 0, /* Use default view switching. */
1775 OPEN_SPLIT = 1, /* Split current view. */
1776 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1777 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1778 OPEN_PREPARED = 32, /* Open already prepared command. */
1779 OPEN_EXTRA = 64, /* Open extra data from command. */
1782 struct view_ops {
1783 /* What type of content being displayed. Used in the title bar. */
1784 const char *type;
1785 /* What keymap does this view have */
1786 struct keymap keymap;
1787 /* Flags to control the view behavior. */
1788 enum view_flag flags;
1789 /* Size of private data. */
1790 size_t private_size;
1791 /* Open and reads in all view content. */
1792 bool (*open)(struct view *view, enum open_flags flags);
1793 /* Read one line; updates view->line. */
1794 bool (*read)(struct view *view, char *data);
1795 /* Draw one line; @lineno must be < view->height. */
1796 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1797 /* Depending on view handle a special requests. */
1798 enum request (*request)(struct view *view, enum request request, struct line *line);
1799 /* Search for regexp in a line. */
1800 bool (*grep)(struct view *view, struct line *line);
1801 /* Select line */
1802 void (*select)(struct view *view, struct line *line);
1805 #define VIEW_OPS(id, name, ref) name##_ops
1806 static struct view_ops VIEW_INFO(VIEW_OPS);
1808 static struct view views[] = {
1809 #define VIEW_DATA(id, name, ref) \
1810 { #name, ref, &name##_ops }
1811 VIEW_INFO(VIEW_DATA)
1814 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1816 #define foreach_view(view, i) \
1817 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1819 #define view_is_displayed(view) \
1820 (view == display[0] || view == display[1])
1822 static enum request
1823 view_request(struct view *view, enum request request)
1825 if (!view || !view->lines)
1826 return request;
1827 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1831 * View drawing.
1834 static inline void
1835 set_view_attr(struct view *view, enum line_type type)
1837 if (!view->curline->selected && view->curtype != type) {
1838 (void) wattrset(view->win, get_line_attr(type));
1839 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1840 view->curtype = type;
1844 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1846 static bool
1847 draw_chars(struct view *view, enum line_type type, const char *string,
1848 int max_len, bool use_tilde)
1850 static char out_buffer[BUFSIZ * 2];
1851 int len = 0;
1852 int col = 0;
1853 int trimmed = FALSE;
1854 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1856 if (max_len <= 0)
1857 return VIEW_MAX_LEN(view) <= 0;
1859 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1861 set_view_attr(view, type);
1862 if (len > 0) {
1863 if (opt_iconv_out != ICONV_NONE) {
1864 size_t inlen = len + 1;
1865 char *instr = calloc(1, inlen);
1866 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1867 if (!instr)
1868 return VIEW_MAX_LEN(view) <= 0;
1870 strncpy(instr, string, len);
1872 char *outbuf = out_buffer;
1873 size_t outlen = sizeof(out_buffer);
1875 size_t ret;
1877 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1878 if (ret != (size_t) -1) {
1879 string = out_buffer;
1880 len = sizeof(out_buffer) - outlen;
1882 free(instr);
1885 waddnstr(view->win, string, len);
1887 if (trimmed && use_tilde) {
1888 set_view_attr(view, LINE_DELIMITER);
1889 waddch(view->win, '~');
1890 col++;
1894 view->col += col;
1895 return VIEW_MAX_LEN(view) <= 0;
1898 static bool
1899 draw_space(struct view *view, enum line_type type, int max, int spaces)
1901 static char space[] = " ";
1903 spaces = MIN(max, spaces);
1905 while (spaces > 0) {
1906 int len = MIN(spaces, sizeof(space) - 1);
1908 if (draw_chars(view, type, space, len, FALSE))
1909 return TRUE;
1910 spaces -= len;
1913 return VIEW_MAX_LEN(view) <= 0;
1916 static bool
1917 draw_text(struct view *view, enum line_type type, const char *string)
1919 static char text[SIZEOF_STR];
1921 do {
1922 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1924 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1925 return TRUE;
1926 string += pos;
1927 } while (*string);
1929 return VIEW_MAX_LEN(view) <= 0;
1932 static bool
1933 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1935 char text[SIZEOF_STR];
1936 int retval;
1938 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1939 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1942 static bool
1943 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1945 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1946 int max = VIEW_MAX_LEN(view);
1947 int i;
1949 if (max < size)
1950 size = max;
1952 set_view_attr(view, type);
1953 /* Using waddch() instead of waddnstr() ensures that
1954 * they'll be rendered correctly for the cursor line. */
1955 for (i = skip; i < size; i++)
1956 waddch(view->win, graphic[i]);
1958 view->col += size;
1959 if (separator) {
1960 if (size < max && skip <= size)
1961 waddch(view->win, ' ');
1962 view->col++;
1965 return VIEW_MAX_LEN(view) <= 0;
1968 static bool
1969 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1971 int max = MIN(VIEW_MAX_LEN(view), len);
1972 int col = view->col;
1974 if (!text)
1975 return draw_space(view, type, max, max);
1977 return draw_chars(view, type, text, max - 1, trim)
1978 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1981 static bool
1982 draw_date(struct view *view, struct time *time)
1984 const char *date = mkdate(time, opt_date);
1985 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1987 if (opt_date == DATE_NO)
1988 return FALSE;
1990 return draw_field(view, LINE_DATE, date, cols, FALSE);
1993 static bool
1994 draw_author(struct view *view, const char *author)
1996 bool trim = author_trim(opt_author_cols);
1997 const char *text = mkauthor(author, opt_author_cols, opt_author);
1999 if (opt_author == AUTHOR_NO)
2000 return FALSE;
2002 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2005 static bool
2006 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2008 bool trim = filename && strlen(filename) >= opt_filename_cols;
2010 if (opt_filename == FILENAME_NO)
2011 return FALSE;
2013 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2014 return FALSE;
2016 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2019 static bool
2020 draw_mode(struct view *view, mode_t mode)
2022 const char *str = mkmode(mode);
2024 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2027 static bool
2028 draw_lineno(struct view *view, unsigned int lineno)
2030 char number[10];
2031 int digits3 = view->digits < 3 ? 3 : view->digits;
2032 int max = MIN(VIEW_MAX_LEN(view), digits3);
2033 char *text = NULL;
2034 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2036 if (!opt_line_number)
2037 return FALSE;
2039 lineno += view->pos.offset + 1;
2040 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2041 static char fmt[] = "%1ld";
2043 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2044 if (string_format(number, fmt, lineno))
2045 text = number;
2047 if (text)
2048 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2049 else
2050 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2051 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2054 static bool
2055 draw_refs(struct view *view, struct ref_list *refs)
2057 size_t i;
2059 if (!opt_show_refs || !refs)
2060 return FALSE;
2062 for (i = 0; i < refs->size; i++) {
2063 struct ref *ref = refs->refs[i];
2064 enum line_type type = get_line_type_from_ref(ref);
2066 if (draw_formatted(view, type, "[%s]", ref->name))
2067 return TRUE;
2069 if (draw_text(view, LINE_DEFAULT, " "))
2070 return TRUE;
2073 return FALSE;
2076 static bool
2077 draw_view_line(struct view *view, unsigned int lineno)
2079 struct line *line;
2080 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2082 assert(view_is_displayed(view));
2084 if (view->pos.offset + lineno >= view->lines)
2085 return FALSE;
2087 line = &view->line[view->pos.offset + lineno];
2089 wmove(view->win, lineno, 0);
2090 if (line->cleareol)
2091 wclrtoeol(view->win);
2092 view->col = 0;
2093 view->curline = line;
2094 view->curtype = LINE_NONE;
2095 line->selected = FALSE;
2096 line->dirty = line->cleareol = 0;
2098 if (selected) {
2099 set_view_attr(view, LINE_CURSOR);
2100 line->selected = TRUE;
2101 view->ops->select(view, line);
2104 return view->ops->draw(view, line, lineno);
2107 static void
2108 redraw_view_dirty(struct view *view)
2110 bool dirty = FALSE;
2111 int lineno;
2113 for (lineno = 0; lineno < view->height; lineno++) {
2114 if (view->pos.offset + lineno >= view->lines)
2115 break;
2116 if (!view->line[view->pos.offset + lineno].dirty)
2117 continue;
2118 dirty = TRUE;
2119 if (!draw_view_line(view, lineno))
2120 break;
2123 if (!dirty)
2124 return;
2125 wnoutrefresh(view->win);
2128 static void
2129 redraw_view_from(struct view *view, int lineno)
2131 assert(0 <= lineno && lineno < view->height);
2133 for (; lineno < view->height; lineno++) {
2134 if (!draw_view_line(view, lineno))
2135 break;
2138 wnoutrefresh(view->win);
2141 static void
2142 redraw_view(struct view *view)
2144 werase(view->win);
2145 redraw_view_from(view, 0);
2149 static void
2150 update_view_title(struct view *view)
2152 char buf[SIZEOF_STR];
2153 char state[SIZEOF_STR];
2154 size_t bufpos = 0, statelen = 0;
2155 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2157 assert(view_is_displayed(view));
2159 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2160 unsigned int view_lines = view->pos.offset + view->height;
2161 unsigned int lines = view->lines
2162 ? MIN(view_lines, view->lines) * 100 / view->lines
2163 : 0;
2165 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2166 view->ops->type,
2167 view->pos.lineno + 1,
2168 view->lines,
2169 lines);
2173 if (view->pipe) {
2174 time_t secs = time(NULL) - view->start_time;
2176 /* Three git seconds are a long time ... */
2177 if (secs > 2)
2178 string_format_from(state, &statelen, " loading %lds", secs);
2181 string_format_from(buf, &bufpos, "[%s]", view->name);
2182 if (*view->ref && bufpos < view->width) {
2183 size_t refsize = strlen(view->ref);
2184 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2186 if (minsize < view->width)
2187 refsize = view->width - minsize + 7;
2188 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2191 if (statelen && bufpos < view->width) {
2192 string_format_from(buf, &bufpos, "%s", state);
2195 if (view == display[current_view])
2196 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2197 else
2198 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2200 mvwaddnstr(window, 0, 0, buf, bufpos);
2201 wclrtoeol(window);
2202 wnoutrefresh(window);
2205 static int
2206 apply_step(double step, int value)
2208 if (step >= 1)
2209 return (int) step;
2210 value *= step + 0.01;
2211 return value ? value : 1;
2214 static void
2215 resize_display(void)
2217 int offset, i;
2218 struct view *base = display[0];
2219 struct view *view = display[1] ? display[1] : display[0];
2221 /* Setup window dimensions */
2223 getmaxyx(stdscr, base->height, base->width);
2225 /* Make room for the status window. */
2226 base->height -= 1;
2228 if (view != base) {
2229 /* Horizontal split. */
2230 view->width = base->width;
2231 view->height = apply_step(opt_scale_split_view, base->height);
2232 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2233 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2234 base->height -= view->height;
2236 /* Make room for the title bar. */
2237 view->height -= 1;
2240 /* Make room for the title bar. */
2241 base->height -= 1;
2243 offset = 0;
2245 foreach_displayed_view (view, i) {
2246 if (!display_win[i]) {
2247 display_win[i] = newwin(view->height, view->width, offset, 0);
2248 if (!display_win[i])
2249 die("Failed to create %s view", view->name);
2251 scrollok(display_win[i], FALSE);
2253 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2254 if (!display_title[i])
2255 die("Failed to create title window");
2257 } else {
2258 wresize(display_win[i], view->height, view->width);
2259 mvwin(display_win[i], offset, 0);
2260 mvwin(display_title[i], offset + view->height, 0);
2263 view->win = display_win[i];
2265 offset += view->height + 1;
2269 static void
2270 redraw_display(bool clear)
2272 struct view *view;
2273 int i;
2275 foreach_displayed_view (view, i) {
2276 if (clear)
2277 wclear(view->win);
2278 redraw_view(view);
2279 update_view_title(view);
2285 * Option management
2288 #define TOGGLE_MENU \
2289 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2290 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2291 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2292 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2293 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2294 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2295 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2296 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2297 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2298 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2300 static bool
2301 toggle_option(enum request request)
2303 const struct {
2304 enum request request;
2305 const struct enum_map *map;
2306 size_t map_size;
2307 } data[] = {
2308 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2309 TOGGLE_MENU
2310 #undef TOGGLE_
2312 const struct menu_item menu[] = {
2313 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2314 TOGGLE_MENU
2315 #undef TOGGLE_
2316 { 0 }
2318 int i = 0;
2320 if (request == REQ_OPTIONS) {
2321 if (!prompt_menu("Toggle option", menu, &i))
2322 return FALSE;
2323 } else {
2324 while (i < ARRAY_SIZE(data) && data[i].request != request)
2325 i++;
2326 if (i >= ARRAY_SIZE(data))
2327 die("Invalid request (%d)", request);
2330 if (data[i].map != NULL) {
2331 unsigned int *opt = menu[i].data;
2333 *opt = (*opt + 1) % data[i].map_size;
2334 if (data[i].map == ignore_space_map) {
2335 update_ignore_space_arg();
2336 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2337 return TRUE;
2339 } else if (data[i].map == commit_order_map) {
2340 update_commit_order_arg();
2341 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2342 return TRUE;
2345 redraw_display(FALSE);
2346 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2348 } else {
2349 bool *option = menu[i].data;
2351 *option = !*option;
2352 redraw_display(FALSE);
2353 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2356 return FALSE;
2359 static void
2360 maximize_view(struct view *view, bool redraw)
2362 memset(display, 0, sizeof(display));
2363 current_view = 0;
2364 display[current_view] = view;
2365 resize_display();
2366 if (redraw) {
2367 redraw_display(FALSE);
2368 report("");
2374 * Navigation
2377 static bool
2378 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2380 if (lineno >= view->lines)
2381 lineno = view->lines > 0 ? view->lines - 1 : 0;
2383 if (offset > lineno || offset + view->height <= lineno) {
2384 unsigned long half = view->height / 2;
2386 if (lineno > half)
2387 offset = lineno - half;
2388 else
2389 offset = 0;
2392 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2393 view->pos.offset = offset;
2394 view->pos.lineno = lineno;
2395 return TRUE;
2398 return FALSE;
2401 /* Scrolling backend */
2402 static void
2403 do_scroll_view(struct view *view, int lines)
2405 bool redraw_current_line = FALSE;
2407 /* The rendering expects the new offset. */
2408 view->pos.offset += lines;
2410 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2411 assert(lines);
2413 /* Move current line into the view. */
2414 if (view->pos.lineno < view->pos.offset) {
2415 view->pos.lineno = view->pos.offset;
2416 redraw_current_line = TRUE;
2417 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2418 view->pos.lineno = view->pos.offset + view->height - 1;
2419 redraw_current_line = TRUE;
2422 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2424 /* Redraw the whole screen if scrolling is pointless. */
2425 if (view->height < ABS(lines)) {
2426 redraw_view(view);
2428 } else {
2429 int line = lines > 0 ? view->height - lines : 0;
2430 int end = line + ABS(lines);
2432 scrollok(view->win, TRUE);
2433 wscrl(view->win, lines);
2434 scrollok(view->win, FALSE);
2436 while (line < end && draw_view_line(view, line))
2437 line++;
2439 if (redraw_current_line)
2440 draw_view_line(view, view->pos.lineno - view->pos.offset);
2441 wnoutrefresh(view->win);
2444 view->has_scrolled = TRUE;
2445 report("");
2448 /* Scroll frontend */
2449 static void
2450 scroll_view(struct view *view, enum request request)
2452 int lines = 1;
2454 assert(view_is_displayed(view));
2456 switch (request) {
2457 case REQ_SCROLL_FIRST_COL:
2458 view->pos.col = 0;
2459 redraw_view_from(view, 0);
2460 report("");
2461 return;
2462 case REQ_SCROLL_LEFT:
2463 if (view->pos.col == 0) {
2464 report("Cannot scroll beyond the first column");
2465 return;
2467 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2468 view->pos.col = 0;
2469 else
2470 view->pos.col -= apply_step(opt_hscroll, view->width);
2471 redraw_view_from(view, 0);
2472 report("");
2473 return;
2474 case REQ_SCROLL_RIGHT:
2475 view->pos.col += apply_step(opt_hscroll, view->width);
2476 redraw_view(view);
2477 report("");
2478 return;
2479 case REQ_SCROLL_PAGE_DOWN:
2480 lines = view->height;
2481 case REQ_SCROLL_LINE_DOWN:
2482 if (view->pos.offset + lines > view->lines)
2483 lines = view->lines - view->pos.offset;
2485 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2486 report("Cannot scroll beyond the last line");
2487 return;
2489 break;
2491 case REQ_SCROLL_PAGE_UP:
2492 lines = view->height;
2493 case REQ_SCROLL_LINE_UP:
2494 if (lines > view->pos.offset)
2495 lines = view->pos.offset;
2497 if (lines == 0) {
2498 report("Cannot scroll beyond the first line");
2499 return;
2502 lines = -lines;
2503 break;
2505 default:
2506 die("request %d not handled in switch", request);
2509 do_scroll_view(view, lines);
2512 /* Cursor moving */
2513 static void
2514 move_view(struct view *view, enum request request)
2516 int scroll_steps = 0;
2517 int steps;
2519 switch (request) {
2520 case REQ_MOVE_FIRST_LINE:
2521 steps = -view->pos.lineno;
2522 break;
2524 case REQ_MOVE_LAST_LINE:
2525 steps = view->lines - view->pos.lineno - 1;
2526 break;
2528 case REQ_MOVE_PAGE_UP:
2529 steps = view->height > view->pos.lineno
2530 ? -view->pos.lineno : -view->height;
2531 break;
2533 case REQ_MOVE_PAGE_DOWN:
2534 steps = view->pos.lineno + view->height >= view->lines
2535 ? view->lines - view->pos.lineno - 1 : view->height;
2536 break;
2538 case REQ_MOVE_UP:
2539 case REQ_PREVIOUS:
2540 steps = -1;
2541 break;
2543 case REQ_MOVE_DOWN:
2544 case REQ_NEXT:
2545 steps = 1;
2546 break;
2548 default:
2549 die("request %d not handled in switch", request);
2552 if (steps <= 0 && view->pos.lineno == 0) {
2553 report("Cannot move beyond the first line");
2554 return;
2556 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2557 report("Cannot move beyond the last line");
2558 return;
2561 /* Move the current line */
2562 view->pos.lineno += steps;
2563 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2565 /* Check whether the view needs to be scrolled */
2566 if (view->pos.lineno < view->pos.offset ||
2567 view->pos.lineno >= view->pos.offset + view->height) {
2568 scroll_steps = steps;
2569 if (steps < 0 && -steps > view->pos.offset) {
2570 scroll_steps = -view->pos.offset;
2572 } else if (steps > 0) {
2573 if (view->pos.lineno == view->lines - 1 &&
2574 view->lines > view->height) {
2575 scroll_steps = view->lines - view->pos.offset - 1;
2576 if (scroll_steps >= view->height)
2577 scroll_steps -= view->height - 1;
2582 if (!view_is_displayed(view)) {
2583 view->pos.offset += scroll_steps;
2584 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2585 view->ops->select(view, &view->line[view->pos.lineno]);
2586 return;
2589 /* Repaint the old "current" line if we be scrolling */
2590 if (ABS(steps) < view->height)
2591 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2593 if (scroll_steps) {
2594 do_scroll_view(view, scroll_steps);
2595 return;
2598 /* Draw the current line */
2599 draw_view_line(view, view->pos.lineno - view->pos.offset);
2601 wnoutrefresh(view->win);
2602 report("");
2607 * Searching
2610 static void search_view(struct view *view, enum request request);
2612 static bool
2613 grep_text(struct view *view, const char *text[])
2615 regmatch_t pmatch;
2616 size_t i;
2618 for (i = 0; text[i]; i++)
2619 if (*text[i] &&
2620 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2621 return TRUE;
2622 return FALSE;
2625 static void
2626 select_view_line(struct view *view, unsigned long lineno)
2628 struct position old = view->pos;
2630 if (goto_view_line(view, view->pos.offset, lineno)) {
2631 if (view_is_displayed(view)) {
2632 if (old.offset != view->pos.offset) {
2633 redraw_view(view);
2634 } else {
2635 draw_view_line(view, old.lineno - view->pos.offset);
2636 draw_view_line(view, view->pos.lineno - view->pos.offset);
2637 wnoutrefresh(view->win);
2639 } else {
2640 view->ops->select(view, &view->line[view->pos.lineno]);
2645 static void
2646 find_next(struct view *view, enum request request)
2648 unsigned long lineno = view->pos.lineno;
2649 int direction;
2651 if (!*view->grep) {
2652 if (!*opt_search)
2653 report("No previous search");
2654 else
2655 search_view(view, request);
2656 return;
2659 switch (request) {
2660 case REQ_SEARCH:
2661 case REQ_FIND_NEXT:
2662 direction = 1;
2663 break;
2665 case REQ_SEARCH_BACK:
2666 case REQ_FIND_PREV:
2667 direction = -1;
2668 break;
2670 default:
2671 return;
2674 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2675 lineno += direction;
2677 /* Note, lineno is unsigned long so will wrap around in which case it
2678 * will become bigger than view->lines. */
2679 for (; lineno < view->lines; lineno += direction) {
2680 if (view->ops->grep(view, &view->line[lineno])) {
2681 select_view_line(view, lineno);
2682 report("Line %ld matches '%s'", lineno + 1, view->grep);
2683 return;
2687 report("No match found for '%s'", view->grep);
2690 static void
2691 search_view(struct view *view, enum request request)
2693 int regex_err;
2695 if (view->regex) {
2696 regfree(view->regex);
2697 *view->grep = 0;
2698 } else {
2699 view->regex = calloc(1, sizeof(*view->regex));
2700 if (!view->regex)
2701 return;
2704 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2705 if (regex_err != 0) {
2706 char buf[SIZEOF_STR] = "unknown error";
2708 regerror(regex_err, view->regex, buf, sizeof(buf));
2709 report("Search failed: %s", buf);
2710 return;
2713 string_copy(view->grep, opt_search);
2715 find_next(view, request);
2719 * Incremental updating
2722 static inline bool
2723 check_position(struct position *pos)
2725 return pos->lineno || pos->col || pos->offset;
2728 static inline void
2729 clear_position(struct position *pos)
2731 memset(pos, 0, sizeof(*pos));
2734 static void
2735 reset_view(struct view *view)
2737 int i;
2739 for (i = 0; i < view->lines; i++)
2740 if (!view->line[i].dont_free)
2741 free(view->line[i].data);
2742 free(view->line);
2744 view->prev_pos = view->pos;
2745 clear_position(&view->pos);
2747 view->line = NULL;
2748 view->lines = 0;
2749 view->vid[0] = 0;
2750 view->update_secs = 0;
2753 static const char *
2754 format_arg(const char *name)
2756 static struct {
2757 const char *name;
2758 size_t namelen;
2759 const char *value;
2760 const char *value_if_empty;
2761 } vars[] = {
2762 #define FORMAT_VAR(name, value, value_if_empty) \
2763 { name, STRING_SIZE(name), value, value_if_empty }
2764 FORMAT_VAR("%(directory)", opt_path, "."),
2765 FORMAT_VAR("%(file)", opt_file, ""),
2766 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2767 FORMAT_VAR("%(head)", ref_head, ""),
2768 FORMAT_VAR("%(commit)", ref_commit, ""),
2769 FORMAT_VAR("%(blob)", ref_blob, ""),
2770 FORMAT_VAR("%(branch)", ref_branch, ""),
2772 int i;
2774 if (!prefixcmp(name, "%(prompt"))
2775 return read_prompt("Command argument: ");
2777 for (i = 0; i < ARRAY_SIZE(vars); i++)
2778 if (!strncmp(name, vars[i].name, vars[i].namelen))
2779 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2781 report("Unknown replacement: `%s`", name);
2782 return NULL;
2785 static bool
2786 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2788 char buf[SIZEOF_STR];
2789 int argc;
2791 argv_free(*dst_argv);
2793 for (argc = 0; src_argv[argc]; argc++) {
2794 const char *arg = src_argv[argc];
2795 size_t bufpos = 0;
2797 if (!strcmp(arg, "%(fileargs)")) {
2798 if (!argv_append_array(dst_argv, opt_file_argv))
2799 break;
2800 continue;
2802 } else if (!strcmp(arg, "%(diffargs)")) {
2803 if (!argv_append_array(dst_argv, opt_diff_argv))
2804 break;
2805 continue;
2807 } else if (!strcmp(arg, "%(blameargs)")) {
2808 if (!argv_append_array(dst_argv, opt_blame_argv))
2809 break;
2810 continue;
2812 } else if (!strcmp(arg, "%(revargs)") ||
2813 (first && !strcmp(arg, "%(commit)"))) {
2814 if (!argv_append_array(dst_argv, opt_rev_argv))
2815 break;
2816 continue;
2819 while (arg) {
2820 char *next = strstr(arg, "%(");
2821 int len = next - arg;
2822 const char *value;
2824 if (!next) {
2825 len = strlen(arg);
2826 value = "";
2828 } else {
2829 value = format_arg(next);
2831 if (!value) {
2832 return FALSE;
2836 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2837 return FALSE;
2839 arg = next ? strchr(next, ')') + 1 : NULL;
2842 if (!argv_append(dst_argv, buf))
2843 break;
2846 return src_argv[argc] == NULL;
2849 static bool
2850 restore_view_position(struct view *view)
2852 /* A view without a previous view is the first view */
2853 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2854 select_view_line(view, opt_lineno - 1);
2855 opt_lineno = 0;
2858 /* Ensure that the view position is in a valid state. */
2859 if (!check_position(&view->prev_pos) ||
2860 (view->pipe && view->lines <= view->prev_pos.lineno))
2861 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2863 /* Changing the view position cancels the restoring. */
2864 /* FIXME: Changing back to the first line is not detected. */
2865 if (check_position(&view->pos)) {
2866 clear_position(&view->prev_pos);
2867 return FALSE;
2870 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2871 view_is_displayed(view))
2872 werase(view->win);
2874 view->pos.col = view->prev_pos.col;
2875 clear_position(&view->prev_pos);
2877 return TRUE;
2880 static void
2881 end_update(struct view *view, bool force)
2883 if (!view->pipe)
2884 return;
2885 while (!view->ops->read(view, NULL))
2886 if (!force)
2887 return;
2888 if (force)
2889 io_kill(view->pipe);
2890 io_done(view->pipe);
2891 view->pipe = NULL;
2894 static void
2895 setup_update(struct view *view, const char *vid)
2897 reset_view(view);
2898 string_copy_rev(view->vid, vid);
2899 view->pipe = &view->io;
2900 view->start_time = time(NULL);
2903 static bool
2904 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2906 bool extra = !!(flags & (OPEN_EXTRA));
2907 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2908 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2910 if (!reload && !strcmp(view->vid, view->id))
2911 return TRUE;
2913 if (view->pipe) {
2914 if (extra)
2915 io_done(view->pipe);
2916 else
2917 end_update(view, TRUE);
2920 if (!refresh && argv) {
2921 view->dir = dir;
2922 if (!format_argv(&view->argv, argv, !view->prev))
2923 return FALSE;
2925 /* Put the current ref_* value to the view title ref
2926 * member. This is needed by the blob view. Most other
2927 * views sets it automatically after loading because the
2928 * first line is a commit line. */
2929 string_copy_rev(view->ref, view->id);
2932 if (view->argv && view->argv[0] &&
2933 !io_run(&view->io, IO_RD, view->dir, view->argv))
2934 return FALSE;
2936 if (!extra)
2937 setup_update(view, view->id);
2939 return TRUE;
2942 static bool
2943 update_view(struct view *view)
2945 char *line;
2946 /* Clear the view and redraw everything since the tree sorting
2947 * might have rearranged things. */
2948 bool redraw = view->lines == 0;
2949 bool can_read = TRUE;
2951 if (!view->pipe)
2952 return TRUE;
2954 if (!io_can_read(view->pipe, FALSE)) {
2955 if (view->lines == 0 && view_is_displayed(view)) {
2956 time_t secs = time(NULL) - view->start_time;
2958 if (secs > 1 && secs > view->update_secs) {
2959 if (view->update_secs == 0)
2960 redraw_view(view);
2961 update_view_title(view);
2962 view->update_secs = secs;
2965 return TRUE;
2968 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2969 if (view->encoding) {
2970 line = encoding_convert(view->encoding, line);
2973 if (!view->ops->read(view, line)) {
2974 report("Allocation failure");
2975 end_update(view, TRUE);
2976 return FALSE;
2981 unsigned long lines = view->lines;
2982 int digits;
2984 for (digits = 0; lines; digits++)
2985 lines /= 10;
2987 /* Keep the displayed view in sync with line number scaling. */
2988 if (digits != view->digits) {
2989 view->digits = digits;
2990 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2991 redraw = TRUE;
2995 if (io_error(view->pipe)) {
2996 report("Failed to read: %s", io_strerror(view->pipe));
2997 end_update(view, TRUE);
2999 } else if (io_eof(view->pipe)) {
3000 if (view_is_displayed(view))
3001 report("");
3002 end_update(view, FALSE);
3005 if (restore_view_position(view))
3006 redraw = TRUE;
3008 if (!view_is_displayed(view))
3009 return TRUE;
3011 if (redraw)
3012 redraw_view_from(view, 0);
3013 else
3014 redraw_view_dirty(view);
3016 /* Update the title _after_ the redraw so that if the redraw picks up a
3017 * commit reference in view->ref it'll be available here. */
3018 update_view_title(view);
3019 return TRUE;
3022 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3024 static struct line *
3025 add_line_data(struct view *view, void *data, enum line_type type)
3027 struct line *line;
3029 if (!realloc_lines(&view->line, view->lines, 1))
3030 return NULL;
3032 line = &view->line[view->lines++];
3033 memset(line, 0, sizeof(*line));
3034 line->type = type;
3035 line->data = data;
3036 line->dirty = 1;
3038 return line;
3041 static struct line *
3042 add_line_static_data(struct view *view, void *data, enum line_type type)
3044 struct line *line = add_line_data(view, data, type);
3046 if (line)
3047 line->dont_free = TRUE;
3048 return line;
3051 static struct line *
3052 add_line_text(struct view *view, const char *text, enum line_type type)
3054 char *data = text ? strdup(text) : NULL;
3056 return data ? add_line_data(view, data, type) : NULL;
3059 static struct line *
3060 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3062 char buf[SIZEOF_STR];
3063 int retval;
3065 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3066 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3070 * View opening
3073 static void
3074 load_view(struct view *view, enum open_flags flags)
3076 if (view->pipe)
3077 end_update(view, TRUE);
3078 if (view->ops->private_size) {
3079 if (!view->private)
3080 view->private = calloc(1, view->ops->private_size);
3081 else
3082 memset(view->private, 0, view->ops->private_size);
3084 if (!view->ops->open(view, flags)) {
3085 report("Failed to load %s view", view->name);
3086 return;
3088 restore_view_position(view);
3090 if (view->pipe && view->lines == 0) {
3091 /* Clear the old view and let the incremental updating refill
3092 * the screen. */
3093 werase(view->win);
3094 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3095 clear_position(&view->prev_pos);
3096 report("");
3097 } else if (view_is_displayed(view)) {
3098 redraw_view(view);
3099 report("");
3103 #define refresh_view(view) load_view(view, OPEN_REFRESH)
3104 #define reload_view(view) load_view(view, OPEN_RELOAD)
3106 static void
3107 split_view(struct view *prev, struct view *view)
3109 display[1] = view;
3110 current_view = 1;
3111 view->parent = prev;
3112 resize_display();
3114 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3115 /* Take the title line into account. */
3116 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3118 /* Scroll the view that was split if the current line is
3119 * outside the new limited view. */
3120 do_scroll_view(prev, lines);
3123 if (view != prev && view_is_displayed(prev)) {
3124 /* "Blur" the previous view. */
3125 update_view_title(prev);
3129 static void
3130 open_view(struct view *prev, enum request request, enum open_flags flags)
3132 bool split = !!(flags & OPEN_SPLIT);
3133 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3134 struct view *view = VIEW(request);
3135 int nviews = displayed_views();
3137 assert(flags ^ OPEN_REFRESH);
3139 if (view == prev && nviews == 1 && !reload) {
3140 report("Already in %s view", view->name);
3141 return;
3144 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3145 report("The %s view is disabled in pager view", view->name);
3146 return;
3149 if (split) {
3150 split_view(prev, view);
3151 } else {
3152 maximize_view(view, FALSE);
3155 /* No prev signals that this is the first loaded view. */
3156 if (prev && view != prev) {
3157 view->prev = prev;
3160 load_view(view, flags);
3163 static void
3164 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3166 enum request request = view - views + REQ_OFFSET + 1;
3168 if (view->pipe)
3169 end_update(view, TRUE);
3170 view->dir = dir;
3172 if (!argv_copy(&view->argv, argv)) {
3173 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3174 } else {
3175 open_view(prev, request, flags | OPEN_PREPARED);
3179 static void
3180 open_external_viewer(const char *argv[], const char *dir)
3182 def_prog_mode(); /* save current tty modes */
3183 endwin(); /* restore original tty modes */
3184 io_run_fg(argv, dir);
3185 fprintf(stderr, "Press Enter to continue");
3186 getc(opt_tty);
3187 reset_prog_mode();
3188 redraw_display(TRUE);
3191 static void
3192 open_mergetool(const char *file)
3194 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3196 open_external_viewer(mergetool_argv, opt_cdup);
3199 static void
3200 open_editor(const char *file)
3202 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3203 char editor_cmd[SIZEOF_STR];
3204 const char *editor;
3205 int argc = 0;
3207 editor = getenv("GIT_EDITOR");
3208 if (!editor && *opt_editor)
3209 editor = opt_editor;
3210 if (!editor)
3211 editor = getenv("VISUAL");
3212 if (!editor)
3213 editor = getenv("EDITOR");
3214 if (!editor)
3215 editor = "vi";
3217 string_ncopy(editor_cmd, editor, strlen(editor));
3218 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3219 report("Failed to read editor command");
3220 return;
3223 editor_argv[argc] = file;
3224 open_external_viewer(editor_argv, opt_cdup);
3227 static void
3228 open_run_request(enum request request)
3230 struct run_request *req = get_run_request(request);
3231 const char **argv = NULL;
3233 if (!req) {
3234 report("Unknown run request");
3235 return;
3238 if (format_argv(&argv, req->argv, FALSE)) {
3239 if (req->silent)
3240 io_run_bg(argv);
3241 else
3242 open_external_viewer(argv, NULL);
3244 if (argv)
3245 argv_free(argv);
3246 free(argv);
3250 * User request switch noodle
3253 static int
3254 view_driver(struct view *view, enum request request)
3256 int i;
3258 if (request == REQ_NONE)
3259 return TRUE;
3261 if (request > REQ_NONE) {
3262 open_run_request(request);
3263 view_request(view, REQ_REFRESH);
3264 return TRUE;
3267 request = view_request(view, request);
3268 if (request == REQ_NONE)
3269 return TRUE;
3271 switch (request) {
3272 case REQ_MOVE_UP:
3273 case REQ_MOVE_DOWN:
3274 case REQ_MOVE_PAGE_UP:
3275 case REQ_MOVE_PAGE_DOWN:
3276 case REQ_MOVE_FIRST_LINE:
3277 case REQ_MOVE_LAST_LINE:
3278 move_view(view, request);
3279 break;
3281 case REQ_SCROLL_FIRST_COL:
3282 case REQ_SCROLL_LEFT:
3283 case REQ_SCROLL_RIGHT:
3284 case REQ_SCROLL_LINE_DOWN:
3285 case REQ_SCROLL_LINE_UP:
3286 case REQ_SCROLL_PAGE_DOWN:
3287 case REQ_SCROLL_PAGE_UP:
3288 scroll_view(view, request);
3289 break;
3291 case REQ_VIEW_BLAME:
3292 if (!opt_file[0]) {
3293 report("No file chosen, press %s to open tree view",
3294 get_view_key(view, REQ_VIEW_TREE));
3295 break;
3297 open_view(view, request, OPEN_DEFAULT);
3298 break;
3300 case REQ_VIEW_BLOB:
3301 if (!ref_blob[0]) {
3302 report("No file chosen, press %s to open tree view",
3303 get_view_key(view, REQ_VIEW_TREE));
3304 break;
3306 open_view(view, request, OPEN_DEFAULT);
3307 break;
3309 case REQ_VIEW_PAGER:
3310 if (view == NULL) {
3311 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3312 die("Failed to open stdin");
3313 open_view(view, request, OPEN_PREPARED);
3314 break;
3317 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3318 report("No pager content, press %s to run command from prompt",
3319 get_view_key(view, REQ_PROMPT));
3320 break;
3322 open_view(view, request, OPEN_DEFAULT);
3323 break;
3325 case REQ_VIEW_STAGE:
3326 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3327 report("No stage content, press %s to open the status view and choose file",
3328 get_view_key(view, REQ_VIEW_STATUS));
3329 break;
3331 open_view(view, request, OPEN_DEFAULT);
3332 break;
3334 case REQ_VIEW_STATUS:
3335 if (opt_is_inside_work_tree == FALSE) {
3336 report("The status view requires a working tree");
3337 break;
3339 open_view(view, request, OPEN_DEFAULT);
3340 break;
3342 case REQ_VIEW_MAIN:
3343 case REQ_VIEW_DIFF:
3344 case REQ_VIEW_LOG:
3345 case REQ_VIEW_TREE:
3346 case REQ_VIEW_HELP:
3347 case REQ_VIEW_BRANCH:
3348 open_view(view, request, OPEN_DEFAULT);
3349 break;
3351 case REQ_NEXT:
3352 case REQ_PREVIOUS:
3353 if (view->parent) {
3354 int line;
3356 view = view->parent;
3357 line = view->pos.lineno;
3358 move_view(view, request);
3359 if (view_is_displayed(view))
3360 update_view_title(view);
3361 if (line != view->pos.lineno)
3362 view_request(view, REQ_ENTER);
3363 } else {
3364 move_view(view, request);
3366 break;
3368 case REQ_VIEW_NEXT:
3370 int nviews = displayed_views();
3371 int next_view = (current_view + 1) % nviews;
3373 if (next_view == current_view) {
3374 report("Only one view is displayed");
3375 break;
3378 current_view = next_view;
3379 /* Blur out the title of the previous view. */
3380 update_view_title(view);
3381 report("");
3382 break;
3384 case REQ_REFRESH:
3385 report("Refreshing is not yet supported for the %s view", view->name);
3386 break;
3388 case REQ_MAXIMIZE:
3389 if (displayed_views() == 2)
3390 maximize_view(view, TRUE);
3391 break;
3393 case REQ_OPTIONS:
3394 case REQ_TOGGLE_LINENO:
3395 case REQ_TOGGLE_DATE:
3396 case REQ_TOGGLE_AUTHOR:
3397 case REQ_TOGGLE_FILENAME:
3398 case REQ_TOGGLE_GRAPHIC:
3399 case REQ_TOGGLE_REV_GRAPH:
3400 case REQ_TOGGLE_REFS:
3401 case REQ_TOGGLE_CHANGES:
3402 case REQ_TOGGLE_IGNORE_SPACE:
3403 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3404 reload_view(view);
3405 break;
3407 case REQ_TOGGLE_SORT_FIELD:
3408 case REQ_TOGGLE_SORT_ORDER:
3409 report("Sorting is not yet supported for the %s view", view->name);
3410 break;
3412 case REQ_DIFF_CONTEXT_UP:
3413 case REQ_DIFF_CONTEXT_DOWN:
3414 report("Changing the diff context is not yet supported for the %s view", view->name);
3415 break;
3417 case REQ_SEARCH:
3418 case REQ_SEARCH_BACK:
3419 search_view(view, request);
3420 break;
3422 case REQ_FIND_NEXT:
3423 case REQ_FIND_PREV:
3424 find_next(view, request);
3425 break;
3427 case REQ_STOP_LOADING:
3428 foreach_view(view, i) {
3429 if (view->pipe)
3430 report("Stopped loading the %s view", view->name),
3431 end_update(view, TRUE);
3433 break;
3435 case REQ_SHOW_VERSION:
3436 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3437 return TRUE;
3439 case REQ_SCREEN_REDRAW:
3440 redraw_display(TRUE);
3441 break;
3443 case REQ_EDIT:
3444 report("Nothing to edit");
3445 break;
3447 case REQ_ENTER:
3448 report("Nothing to enter");
3449 break;
3451 case REQ_VIEW_CLOSE:
3452 /* XXX: Mark closed views by letting view->prev point to the
3453 * view itself. Parents to closed view should never be
3454 * followed. */
3455 if (view->prev && view->prev != view) {
3456 maximize_view(view->prev, TRUE);
3457 view->prev = view;
3458 break;
3460 /* Fall-through */
3461 case REQ_QUIT:
3462 return FALSE;
3464 default:
3465 report("Unknown key, press %s for help",
3466 get_view_key(view, REQ_VIEW_HELP));
3467 return TRUE;
3470 return TRUE;
3475 * View backend utilities
3478 enum sort_field {
3479 ORDERBY_NAME,
3480 ORDERBY_DATE,
3481 ORDERBY_AUTHOR,
3484 struct sort_state {
3485 const enum sort_field *fields;
3486 size_t size, current;
3487 bool reverse;
3490 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3491 #define get_sort_field(state) ((state).fields[(state).current])
3492 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3494 static void
3495 sort_view(struct view *view, enum request request, struct sort_state *state,
3496 int (*compare)(const void *, const void *))
3498 switch (request) {
3499 case REQ_TOGGLE_SORT_FIELD:
3500 state->current = (state->current + 1) % state->size;
3501 break;
3503 case REQ_TOGGLE_SORT_ORDER:
3504 state->reverse = !state->reverse;
3505 break;
3506 default:
3507 die("Not a sort request");
3510 qsort(view->line, view->lines, sizeof(*view->line), compare);
3511 redraw_view(view);
3514 static bool
3515 update_diff_context(enum request request)
3517 int diff_context = opt_diff_context;
3519 switch (request) {
3520 case REQ_DIFF_CONTEXT_UP:
3521 opt_diff_context += 1;
3522 update_diff_context_arg(opt_diff_context);
3523 break;
3525 case REQ_DIFF_CONTEXT_DOWN:
3526 if (opt_diff_context == 0) {
3527 report("Diff context cannot be less than zero");
3528 break;
3530 opt_diff_context -= 1;
3531 update_diff_context_arg(opt_diff_context);
3532 break;
3534 default:
3535 die("Not a diff context request");
3538 return diff_context != opt_diff_context;
3541 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3543 /* Small author cache to reduce memory consumption. It uses binary
3544 * search to lookup or find place to position new entries. No entries
3545 * are ever freed. */
3546 static const char *
3547 get_author(const char *name)
3549 static const char **authors;
3550 static size_t authors_size;
3551 int from = 0, to = authors_size - 1;
3553 while (from <= to) {
3554 size_t pos = (to + from) / 2;
3555 int cmp = strcmp(name, authors[pos]);
3557 if (!cmp)
3558 return authors[pos];
3560 if (cmp < 0)
3561 to = pos - 1;
3562 else
3563 from = pos + 1;
3566 if (!realloc_authors(&authors, authors_size, 1))
3567 return NULL;
3568 name = strdup(name);
3569 if (!name)
3570 return NULL;
3572 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3573 authors[from] = name;
3574 authors_size++;
3576 return name;
3579 static void
3580 parse_timesec(struct time *time, const char *sec)
3582 time->sec = (time_t) atol(sec);
3585 static void
3586 parse_timezone(struct time *time, const char *zone)
3588 long tz;
3590 tz = ('0' - zone[1]) * 60 * 60 * 10;
3591 tz += ('0' - zone[2]) * 60 * 60;
3592 tz += ('0' - zone[3]) * 60 * 10;
3593 tz += ('0' - zone[4]) * 60;
3595 if (zone[0] == '-')
3596 tz = -tz;
3598 time->tz = tz;
3599 time->sec -= tz;
3602 /* Parse author lines where the name may be empty:
3603 * author <email@address.tld> 1138474660 +0100
3605 static void
3606 parse_author_line(char *ident, const char **author, struct time *time)
3608 char *nameend = strchr(ident, '<');
3609 char *emailend = strchr(ident, '>');
3611 if (nameend && emailend)
3612 *nameend = *emailend = 0;
3613 ident = chomp_string(ident);
3614 if (!*ident) {
3615 if (nameend)
3616 ident = chomp_string(nameend + 1);
3617 if (!*ident)
3618 ident = "Unknown";
3621 *author = get_author(ident);
3623 /* Parse epoch and timezone */
3624 if (emailend && emailend[1] == ' ') {
3625 char *secs = emailend + 2;
3626 char *zone = strchr(secs, ' ');
3628 parse_timesec(time, secs);
3630 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3631 parse_timezone(time, zone + 1);
3635 static struct line *
3636 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3638 for (; view->line < line; line--)
3639 if (line->type == type)
3640 return line;
3642 return NULL;
3646 * Blame
3649 struct blame_commit {
3650 char id[SIZEOF_REV]; /* SHA1 ID. */
3651 char title[128]; /* First line of the commit message. */
3652 const char *author; /* Author of the commit. */
3653 struct time time; /* Date from the author ident. */
3654 char filename[128]; /* Name of file. */
3655 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3656 char parent_filename[128]; /* Parent/previous name of file. */
3659 struct blame_header {
3660 char id[SIZEOF_REV]; /* SHA1 ID. */
3661 size_t orig_lineno;
3662 size_t lineno;
3663 size_t group;
3666 static bool
3667 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3669 const char *pos = *posref;
3671 *posref = NULL;
3672 pos = strchr(pos + 1, ' ');
3673 if (!pos || !isdigit(pos[1]))
3674 return FALSE;
3675 *number = atoi(pos + 1);
3676 if (*number < min || *number > max)
3677 return FALSE;
3679 *posref = pos;
3680 return TRUE;
3683 static bool
3684 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3686 const char *pos = text + SIZEOF_REV - 2;
3688 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3689 return FALSE;
3691 string_ncopy(header->id, text, SIZEOF_REV);
3693 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3694 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3695 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3696 return FALSE;
3698 return TRUE;
3701 static bool
3702 match_blame_header(const char *name, char **line)
3704 size_t namelen = strlen(name);
3705 bool matched = !strncmp(name, *line, namelen);
3707 if (matched)
3708 *line += namelen;
3710 return matched;
3713 static bool
3714 parse_blame_info(struct blame_commit *commit, char *line)
3716 if (match_blame_header("author ", &line)) {
3717 commit->author = get_author(line);
3719 } else if (match_blame_header("author-time ", &line)) {
3720 parse_timesec(&commit->time, line);
3722 } else if (match_blame_header("author-tz ", &line)) {
3723 parse_timezone(&commit->time, line);
3725 } else if (match_blame_header("summary ", &line)) {
3726 string_ncopy(commit->title, line, strlen(line));
3728 } else if (match_blame_header("previous ", &line)) {
3729 if (strlen(line) <= SIZEOF_REV)
3730 return FALSE;
3731 string_copy_rev(commit->parent_id, line);
3732 line += SIZEOF_REV;
3733 string_ncopy(commit->parent_filename, line, strlen(line));
3735 } else if (match_blame_header("filename ", &line)) {
3736 string_ncopy(commit->filename, line, strlen(line));
3737 return TRUE;
3740 return FALSE;
3744 * Pager backend
3747 static bool
3748 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3750 if (draw_lineno(view, lineno))
3751 return TRUE;
3753 draw_text(view, line->type, line->data);
3754 return TRUE;
3757 static bool
3758 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3760 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3761 char ref[SIZEOF_STR];
3763 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3764 return TRUE;
3766 /* This is the only fatal call, since it can "corrupt" the buffer. */
3767 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3768 return FALSE;
3770 return TRUE;
3773 static void
3774 add_pager_refs(struct view *view, struct line *line)
3776 char buf[SIZEOF_STR];
3777 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3778 struct ref_list *list;
3779 size_t bufpos = 0, i;
3780 const char *sep = "Refs: ";
3781 bool is_tag = FALSE;
3783 assert(line->type == LINE_COMMIT);
3785 list = get_ref_list(commit_id);
3786 if (!list) {
3787 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3788 goto try_add_describe_ref;
3789 return;
3792 for (i = 0; i < list->size; i++) {
3793 struct ref *ref = list->refs[i];
3794 const char *fmt = ref->tag ? "%s[%s]" :
3795 ref->remote ? "%s<%s>" : "%s%s";
3797 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3798 return;
3799 sep = ", ";
3800 if (ref->tag)
3801 is_tag = TRUE;
3804 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3805 try_add_describe_ref:
3806 /* Add <tag>-g<commit_id> "fake" reference. */
3807 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3808 return;
3811 if (bufpos == 0)
3812 return;
3814 add_line_text(view, buf, LINE_PP_REFS);
3817 static bool
3818 pager_common_read(struct view *view, char *data, enum line_type type)
3820 struct line *line;
3822 if (!data)
3823 return TRUE;
3825 line = add_line_text(view, data, type);
3826 if (!line)
3827 return FALSE;
3829 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3830 add_pager_refs(view, line);
3832 return TRUE;
3835 static bool
3836 pager_read(struct view *view, char *data)
3838 if (!data)
3839 return TRUE;
3841 return pager_common_read(view, data, get_line_type(data));
3844 static enum request
3845 pager_request(struct view *view, enum request request, struct line *line)
3847 int split = 0;
3849 if (request != REQ_ENTER)
3850 return request;
3852 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3853 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3854 split = 1;
3857 /* Always scroll the view even if it was split. That way
3858 * you can use Enter to scroll through the log view and
3859 * split open each commit diff. */
3860 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3862 /* FIXME: A minor workaround. Scrolling the view will call report("")
3863 * but if we are scrolling a non-current view this won't properly
3864 * update the view title. */
3865 if (split)
3866 update_view_title(view);
3868 return REQ_NONE;
3871 static bool
3872 pager_grep(struct view *view, struct line *line)
3874 const char *text[] = { line->data, NULL };
3876 return grep_text(view, text);
3879 static void
3880 pager_select(struct view *view, struct line *line)
3882 if (line->type == LINE_COMMIT) {
3883 char *text = (char *)line->data + STRING_SIZE("commit ");
3885 if (!view_has_flags(view, VIEW_NO_REF))
3886 string_copy_rev(view->ref, text);
3887 string_copy_rev(ref_commit, text);
3891 static bool
3892 pager_open(struct view *view, enum open_flags flags)
3894 return begin_update(view, NULL, NULL, flags);
3897 static struct view_ops pager_ops = {
3898 "line",
3899 { "pager" },
3900 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3902 pager_open,
3903 pager_read,
3904 pager_draw,
3905 pager_request,
3906 pager_grep,
3907 pager_select,
3910 static bool
3911 log_open(struct view *view, enum open_flags flags)
3913 static const char *log_argv[] = {
3914 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3917 return begin_update(view, NULL, log_argv, flags);
3920 static enum request
3921 log_request(struct view *view, enum request request, struct line *line)
3923 switch (request) {
3924 case REQ_REFRESH:
3925 load_refs();
3926 refresh_view(view);
3927 return REQ_NONE;
3928 default:
3929 return pager_request(view, request, line);
3933 static struct view_ops log_ops = {
3934 "line",
3935 { "log" },
3936 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3938 log_open,
3939 pager_read,
3940 pager_draw,
3941 log_request,
3942 pager_grep,
3943 pager_select,
3946 struct diff_state {
3947 bool reading_diff_stat;
3948 bool combined_diff;
3951 static bool
3952 diff_open(struct view *view, enum open_flags flags)
3954 static const char *diff_argv[] = {
3955 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3956 "--patch-with-stat", "--find-copies-harder", "-C",
3957 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3958 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3961 return begin_update(view, NULL, diff_argv, flags);
3964 static bool
3965 diff_common_read(struct view *view, char *data, struct diff_state *state)
3967 enum line_type type;
3969 if (state->reading_diff_stat) {
3970 size_t len = strlen(data);
3971 char *pipe = strchr(data, '|');
3972 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3973 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3975 if (pipe && (has_histogram || has_bin_diff)) {
3976 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3977 } else {
3978 state->reading_diff_stat = FALSE;
3981 } else if (!strcmp(data, "---")) {
3982 state->reading_diff_stat = TRUE;
3985 type = get_line_type(data);
3987 if (type == LINE_DIFF_HEADER) {
3988 const int len = line_info[LINE_DIFF_HEADER].linelen;
3990 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3991 !strncmp(data + len, "cc ", strlen("cc ")))
3992 state->combined_diff = TRUE;
3995 /* ADD2 and DEL2 are only valid in combined diff hunks */
3996 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3997 type = LINE_DEFAULT;
3999 return pager_common_read(view, data, type);
4002 static enum request
4003 diff_common_enter(struct view *view, enum request request, struct line *line)
4005 if (line->type == LINE_DIFF_STAT) {
4006 int file_number = 0;
4008 while (line >= view->line && line->type == LINE_DIFF_STAT) {
4009 file_number++;
4010 line--;
4013 while (line < view->line + view->lines) {
4014 if (line->type == LINE_DIFF_HEADER) {
4015 if (file_number == 1) {
4016 break;
4018 file_number--;
4020 line++;
4024 select_view_line(view, line - view->line);
4025 report("");
4026 return REQ_NONE;
4028 } else {
4029 return pager_request(view, request, line);
4033 static bool
4034 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4036 char *sep = strchr(*text, c);
4038 if (sep != NULL) {
4039 *sep = 0;
4040 draw_text(view, *type, *text);
4041 *sep = c;
4042 *text = sep;
4043 *type = next_type;
4046 return sep != NULL;
4049 static bool
4050 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4052 char *text = line->data;
4053 enum line_type type = line->type;
4055 if (draw_lineno(view, lineno))
4056 return TRUE;
4058 if (type == LINE_DIFF_STAT) {
4059 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4060 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4061 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4062 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4063 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4064 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4065 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4067 } else {
4068 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4069 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4073 draw_text(view, type, text);
4074 return TRUE;
4077 static bool
4078 diff_read(struct view *view, char *data)
4080 struct diff_state *state = view->private;
4082 if (!data) {
4083 /* Fall back to retry if no diff will be shown. */
4084 if (view->lines == 0 && opt_file_argv) {
4085 int pos = argv_size(view->argv)
4086 - argv_size(opt_file_argv) - 1;
4088 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4089 for (; view->argv[pos]; pos++) {
4090 free((void *) view->argv[pos]);
4091 view->argv[pos] = NULL;
4094 if (view->pipe)
4095 io_done(view->pipe);
4096 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4097 return FALSE;
4100 return TRUE;
4103 return diff_common_read(view, data, state);
4106 static bool
4107 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4108 struct blame_header *header, struct blame_commit *commit)
4110 char line_arg[SIZEOF_STR];
4111 const char *blame_argv[] = {
4112 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4114 struct io io;
4115 bool ok = FALSE;
4116 char *buf;
4118 if (!string_format(line_arg, "-L%d,+1", lineno))
4119 return FALSE;
4121 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4122 return FALSE;
4124 while ((buf = io_get(&io, '\n', TRUE))) {
4125 if (header) {
4126 if (!parse_blame_header(header, buf, 9999999))
4127 break;
4128 header = NULL;
4130 } else if (parse_blame_info(commit, buf)) {
4131 ok = TRUE;
4132 break;
4136 if (io_error(&io))
4137 ok = FALSE;
4139 io_done(&io);
4140 return ok;
4143 static bool
4144 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4146 return prefixcmp(chunk, "@@ -") ||
4147 !(chunk = strchr(chunk, marker)) ||
4148 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4151 static enum request
4152 diff_trace_origin(struct view *view, struct line *line)
4154 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4155 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4156 const char *chunk_data;
4157 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4158 int lineno = 0;
4159 const char *file = NULL;
4160 char ref[SIZEOF_REF];
4161 struct blame_header header;
4162 struct blame_commit commit;
4164 if (!diff || !chunk || chunk == line) {
4165 report("The line to trace must be inside a diff chunk");
4166 return REQ_NONE;
4169 for (; diff < line && !file; diff++) {
4170 const char *data = diff->data;
4172 if (!prefixcmp(data, "--- a/")) {
4173 file = data + STRING_SIZE("--- a/");
4174 break;
4178 if (diff == line || !file) {
4179 report("Failed to read the file name");
4180 return REQ_NONE;
4183 chunk_data = chunk->data;
4185 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4186 report("Failed to read the line number");
4187 return REQ_NONE;
4190 if (lineno == 0) {
4191 report("This is the origin of the line");
4192 return REQ_NONE;
4195 for (chunk += 1; chunk < line; chunk++) {
4196 if (chunk->type == LINE_DIFF_ADD) {
4197 lineno += chunk_marker == '+';
4198 } else if (chunk->type == LINE_DIFF_DEL) {
4199 lineno += chunk_marker == '-';
4200 } else {
4201 lineno++;
4205 if (chunk_marker == '+')
4206 string_copy(ref, view->vid);
4207 else
4208 string_format(ref, "%s^", view->vid);
4210 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4211 report("Failed to read blame data");
4212 return REQ_NONE;
4215 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4216 string_copy(opt_ref, header.id);
4217 opt_goto_line = header.orig_lineno - 1;
4219 return REQ_VIEW_BLAME;
4222 static enum request
4223 diff_request(struct view *view, enum request request, struct line *line)
4225 switch (request) {
4226 case REQ_VIEW_BLAME:
4227 return diff_trace_origin(view, line);
4229 case REQ_DIFF_CONTEXT_UP:
4230 case REQ_DIFF_CONTEXT_DOWN:
4231 if (!update_diff_context(request))
4232 return REQ_NONE;
4233 reload_view(view);
4234 return REQ_NONE;
4237 case REQ_ENTER:
4238 return diff_common_enter(view, request, line);
4240 default:
4241 return pager_request(view, request, line);
4245 static void
4246 diff_select(struct view *view, struct line *line)
4248 if (line->type == LINE_DIFF_STAT) {
4249 const char *key = get_view_key(view, REQ_ENTER);
4251 string_format(view->ref, "Press '%s' to jump to file diff", key);
4252 } else {
4253 string_ncopy(view->ref, view->id, strlen(view->id));
4254 return pager_select(view, line);
4258 static struct view_ops diff_ops = {
4259 "line",
4260 { "diff" },
4261 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4262 sizeof(struct diff_state),
4263 diff_open,
4264 diff_read,
4265 diff_common_draw,
4266 diff_request,
4267 pager_grep,
4268 diff_select,
4272 * Help backend
4275 static bool
4276 help_draw(struct view *view, struct line *line, unsigned int lineno)
4278 if (line->type == LINE_HELP_KEYMAP) {
4279 struct keymap *keymap = line->data;
4281 draw_formatted(view, line->type, "[%c] %s bindings",
4282 keymap->hidden ? '+' : '-', keymap->name);
4283 return TRUE;
4284 } else {
4285 return pager_draw(view, line, lineno);
4289 static bool
4290 help_open_keymap_title(struct view *view, struct keymap *keymap)
4292 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4293 return keymap->hidden;
4296 static void
4297 help_open_keymap(struct view *view, struct keymap *keymap)
4299 const char *group = NULL;
4300 char buf[SIZEOF_STR];
4301 size_t bufpos;
4302 bool add_title = TRUE;
4303 int i;
4305 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4306 const char *key = NULL;
4308 if (req_info[i].request == REQ_NONE)
4309 continue;
4311 if (!req_info[i].request) {
4312 group = req_info[i].help;
4313 continue;
4316 key = get_keys(keymap, req_info[i].request, TRUE);
4317 if (!key || !*key)
4318 continue;
4320 if (add_title && help_open_keymap_title(view, keymap))
4321 return;
4322 add_title = FALSE;
4324 if (group) {
4325 add_line_text(view, group, LINE_HELP_GROUP);
4326 group = NULL;
4329 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4330 enum_name(req_info[i]), req_info[i].help);
4333 group = "External commands:";
4335 for (i = 0; i < run_requests; i++) {
4336 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4337 const char *key;
4338 int argc;
4340 if (!req || req->keymap != keymap)
4341 continue;
4343 key = get_key_name(req->key);
4344 if (!*key)
4345 key = "(no key defined)";
4347 if (add_title && help_open_keymap_title(view, keymap))
4348 return;
4349 add_title = FALSE;
4351 if (group) {
4352 add_line_text(view, group, LINE_HELP_GROUP);
4353 group = NULL;
4356 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4357 if (!string_format_from(buf, &bufpos, "%s%s",
4358 argc ? " " : "", req->argv[argc]))
4359 return;
4361 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4365 static bool
4366 help_open(struct view *view, enum open_flags flags)
4368 struct keymap *keymap;
4370 reset_view(view);
4371 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4372 add_line_text(view, "", LINE_DEFAULT);
4374 for (keymap = keymaps; keymap; keymap = keymap->next)
4375 help_open_keymap(view, keymap);
4377 return TRUE;
4380 static enum request
4381 help_request(struct view *view, enum request request, struct line *line)
4383 switch (request) {
4384 case REQ_ENTER:
4385 if (line->type == LINE_HELP_KEYMAP) {
4386 struct keymap *keymap = line->data;
4388 keymap->hidden = !keymap->hidden;
4389 refresh_view(view);
4392 return REQ_NONE;
4393 default:
4394 return pager_request(view, request, line);
4398 static struct view_ops help_ops = {
4399 "line",
4400 { "help" },
4401 VIEW_NO_GIT_DIR,
4403 help_open,
4404 NULL,
4405 help_draw,
4406 help_request,
4407 pager_grep,
4408 pager_select,
4413 * Tree backend
4416 struct tree_stack_entry {
4417 struct tree_stack_entry *prev; /* Entry below this in the stack */
4418 unsigned long lineno; /* Line number to restore */
4419 char *name; /* Position of name in opt_path */
4422 /* The top of the path stack. */
4423 static struct tree_stack_entry *tree_stack = NULL;
4424 unsigned long tree_lineno = 0;
4426 static void
4427 pop_tree_stack_entry(void)
4429 struct tree_stack_entry *entry = tree_stack;
4431 tree_lineno = entry->lineno;
4432 entry->name[0] = 0;
4433 tree_stack = entry->prev;
4434 free(entry);
4437 static void
4438 push_tree_stack_entry(const char *name, unsigned long lineno)
4440 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4441 size_t pathlen = strlen(opt_path);
4443 if (!entry)
4444 return;
4446 entry->prev = tree_stack;
4447 entry->name = opt_path + pathlen;
4448 tree_stack = entry;
4450 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4451 pop_tree_stack_entry();
4452 return;
4455 /* Move the current line to the first tree entry. */
4456 tree_lineno = 1;
4457 entry->lineno = lineno;
4460 /* Parse output from git-ls-tree(1):
4462 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4465 #define SIZEOF_TREE_ATTR \
4466 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4468 #define SIZEOF_TREE_MODE \
4469 STRING_SIZE("100644 ")
4471 #define TREE_ID_OFFSET \
4472 STRING_SIZE("100644 blob ")
4474 struct tree_entry {
4475 char id[SIZEOF_REV];
4476 mode_t mode;
4477 struct time time; /* Date from the author ident. */
4478 const char *author; /* Author of the commit. */
4479 char name[1];
4482 struct tree_state {
4483 const char *author_name;
4484 struct time author_time;
4485 bool read_date;
4488 static const char *
4489 tree_path(const struct line *line)
4491 return ((struct tree_entry *) line->data)->name;
4494 static int
4495 tree_compare_entry(const struct line *line1, const struct line *line2)
4497 if (line1->type != line2->type)
4498 return line1->type == LINE_TREE_DIR ? -1 : 1;
4499 return strcmp(tree_path(line1), tree_path(line2));
4502 static const enum sort_field tree_sort_fields[] = {
4503 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4505 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4507 static int
4508 tree_compare(const void *l1, const void *l2)
4510 const struct line *line1 = (const struct line *) l1;
4511 const struct line *line2 = (const struct line *) l2;
4512 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4513 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4515 if (line1->type == LINE_TREE_HEAD)
4516 return -1;
4517 if (line2->type == LINE_TREE_HEAD)
4518 return 1;
4520 switch (get_sort_field(tree_sort_state)) {
4521 case ORDERBY_DATE:
4522 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4524 case ORDERBY_AUTHOR:
4525 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4527 case ORDERBY_NAME:
4528 default:
4529 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4534 static struct line *
4535 tree_entry(struct view *view, enum line_type type, const char *path,
4536 const char *mode, const char *id)
4538 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4539 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4541 if (!entry || !line) {
4542 free(entry);
4543 return NULL;
4546 strncpy(entry->name, path, strlen(path));
4547 if (mode)
4548 entry->mode = strtoul(mode, NULL, 8);
4549 if (id)
4550 string_copy_rev(entry->id, id);
4552 return line;
4555 static bool
4556 tree_read_date(struct view *view, char *text, struct tree_state *state)
4558 if (!text && state->read_date) {
4559 state->read_date = FALSE;
4560 return TRUE;
4562 } else if (!text) {
4563 /* Find next entry to process */
4564 const char *log_file[] = {
4565 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4566 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4569 if (!view->lines) {
4570 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4571 report("Tree is empty");
4572 return TRUE;
4575 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4576 report("Failed to load tree data");
4577 return TRUE;
4580 state->read_date = TRUE;
4581 return FALSE;
4583 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4584 parse_author_line(text + STRING_SIZE("author "),
4585 &state->author_name, &state->author_time);
4587 } else if (*text == ':') {
4588 char *pos;
4589 size_t annotated = 1;
4590 size_t i;
4592 pos = strchr(text, '\t');
4593 if (!pos)
4594 return TRUE;
4595 text = pos + 1;
4596 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4597 text += strlen(opt_path);
4598 pos = strchr(text, '/');
4599 if (pos)
4600 *pos = 0;
4602 for (i = 1; i < view->lines; i++) {
4603 struct line *line = &view->line[i];
4604 struct tree_entry *entry = line->data;
4606 annotated += !!entry->author;
4607 if (entry->author || strcmp(entry->name, text))
4608 continue;
4610 entry->author = state->author_name;
4611 entry->time = state->author_time;
4612 line->dirty = 1;
4613 break;
4616 if (annotated == view->lines)
4617 io_kill(view->pipe);
4619 return TRUE;
4622 static bool
4623 tree_read(struct view *view, char *text)
4625 struct tree_state *state = view->private;
4626 struct tree_entry *data;
4627 struct line *entry, *line;
4628 enum line_type type;
4629 size_t textlen = text ? strlen(text) : 0;
4630 char *path = text + SIZEOF_TREE_ATTR;
4632 if (state->read_date || !text)
4633 return tree_read_date(view, text, state);
4635 if (textlen <= SIZEOF_TREE_ATTR)
4636 return FALSE;
4637 if (view->lines == 0 &&
4638 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4639 return FALSE;
4641 /* Strip the path part ... */
4642 if (*opt_path) {
4643 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4644 size_t striplen = strlen(opt_path);
4646 if (pathlen > striplen)
4647 memmove(path, path + striplen,
4648 pathlen - striplen + 1);
4650 /* Insert "link" to parent directory. */
4651 if (view->lines == 1 &&
4652 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4653 return FALSE;
4656 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4657 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4658 if (!entry)
4659 return FALSE;
4660 data = entry->data;
4662 /* Skip "Directory ..." and ".." line. */
4663 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4664 if (tree_compare_entry(line, entry) <= 0)
4665 continue;
4667 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4669 line->data = data;
4670 line->type = type;
4671 for (; line <= entry; line++)
4672 line->dirty = line->cleareol = 1;
4673 return TRUE;
4676 if (tree_lineno > view->pos.lineno) {
4677 view->pos.lineno = tree_lineno;
4678 tree_lineno = 0;
4681 return TRUE;
4684 static bool
4685 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4687 struct tree_entry *entry = line->data;
4689 if (line->type == LINE_TREE_HEAD) {
4690 if (draw_text(view, line->type, "Directory path /"))
4691 return TRUE;
4692 } else {
4693 if (draw_mode(view, entry->mode))
4694 return TRUE;
4696 if (draw_author(view, entry->author))
4697 return TRUE;
4699 if (draw_date(view, &entry->time))
4700 return TRUE;
4703 draw_text(view, line->type, entry->name);
4704 return TRUE;
4707 static void
4708 open_blob_editor(const char *id)
4710 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4711 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4712 int fd = mkstemp(file);
4714 if (fd == -1)
4715 report("Failed to create temporary file");
4716 else if (!io_run_append(blob_argv, fd))
4717 report("Failed to save blob data to file");
4718 else
4719 open_editor(file);
4720 if (fd != -1)
4721 unlink(file);
4724 static enum request
4725 tree_request(struct view *view, enum request request, struct line *line)
4727 enum open_flags flags;
4728 struct tree_entry *entry = line->data;
4730 switch (request) {
4731 case REQ_VIEW_BLAME:
4732 if (line->type != LINE_TREE_FILE) {
4733 report("Blame only supported for files");
4734 return REQ_NONE;
4737 string_copy(opt_ref, view->vid);
4738 return request;
4740 case REQ_EDIT:
4741 if (line->type != LINE_TREE_FILE) {
4742 report("Edit only supported for files");
4743 } else if (!is_head_commit(view->vid)) {
4744 open_blob_editor(entry->id);
4745 } else {
4746 open_editor(opt_file);
4748 return REQ_NONE;
4750 case REQ_TOGGLE_SORT_FIELD:
4751 case REQ_TOGGLE_SORT_ORDER:
4752 sort_view(view, request, &tree_sort_state, tree_compare);
4753 return REQ_NONE;
4755 case REQ_PARENT:
4756 if (!*opt_path) {
4757 /* quit view if at top of tree */
4758 return REQ_VIEW_CLOSE;
4760 /* fake 'cd ..' */
4761 line = &view->line[1];
4762 break;
4764 case REQ_ENTER:
4765 break;
4767 default:
4768 return request;
4771 /* Cleanup the stack if the tree view is at a different tree. */
4772 while (!*opt_path && tree_stack)
4773 pop_tree_stack_entry();
4775 switch (line->type) {
4776 case LINE_TREE_DIR:
4777 /* Depending on whether it is a subdirectory or parent link
4778 * mangle the path buffer. */
4779 if (line == &view->line[1] && *opt_path) {
4780 pop_tree_stack_entry();
4782 } else {
4783 const char *basename = tree_path(line);
4785 push_tree_stack_entry(basename, view->pos.lineno);
4788 /* Trees and subtrees share the same ID, so they are not not
4789 * unique like blobs. */
4790 flags = OPEN_RELOAD;
4791 request = REQ_VIEW_TREE;
4792 break;
4794 case LINE_TREE_FILE:
4795 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4796 request = REQ_VIEW_BLOB;
4797 break;
4799 default:
4800 return REQ_NONE;
4803 open_view(view, request, flags);
4804 if (request == REQ_VIEW_TREE)
4805 view->pos.lineno = tree_lineno;
4807 return REQ_NONE;
4810 static bool
4811 tree_grep(struct view *view, struct line *line)
4813 struct tree_entry *entry = line->data;
4814 const char *text[] = {
4815 entry->name,
4816 mkauthor(entry->author, opt_author_cols, opt_author),
4817 mkdate(&entry->time, opt_date),
4818 NULL
4821 return grep_text(view, text);
4824 static void
4825 tree_select(struct view *view, struct line *line)
4827 struct tree_entry *entry = line->data;
4829 if (line->type == LINE_TREE_FILE) {
4830 string_copy_rev(ref_blob, entry->id);
4831 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4833 } else if (line->type != LINE_TREE_DIR) {
4834 return;
4837 string_copy_rev(view->ref, entry->id);
4840 static bool
4841 tree_open(struct view *view, enum open_flags flags)
4843 static const char *tree_argv[] = {
4844 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4847 if (view->lines == 0 && opt_prefix[0]) {
4848 char *pos = opt_prefix;
4850 while (pos && *pos) {
4851 char *end = strchr(pos, '/');
4853 if (end)
4854 *end = 0;
4855 push_tree_stack_entry(pos, 0);
4856 pos = end;
4857 if (end) {
4858 *end = '/';
4859 pos++;
4863 } else if (strcmp(view->vid, view->id)) {
4864 opt_path[0] = 0;
4867 return begin_update(view, opt_cdup, tree_argv, flags);
4870 static struct view_ops tree_ops = {
4871 "file",
4872 { "tree" },
4873 VIEW_NO_FLAGS,
4874 sizeof(struct tree_state),
4875 tree_open,
4876 tree_read,
4877 tree_draw,
4878 tree_request,
4879 tree_grep,
4880 tree_select,
4883 static bool
4884 blob_open(struct view *view, enum open_flags flags)
4886 static const char *blob_argv[] = {
4887 "git", "cat-file", "blob", "%(blob)", NULL
4890 view->encoding = get_path_encoding(opt_file, opt_encoding);
4892 return begin_update(view, NULL, blob_argv, flags);
4895 static bool
4896 blob_read(struct view *view, char *line)
4898 if (!line)
4899 return TRUE;
4900 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4903 static enum request
4904 blob_request(struct view *view, enum request request, struct line *line)
4906 switch (request) {
4907 case REQ_EDIT:
4908 open_blob_editor(view->vid);
4909 return REQ_NONE;
4910 default:
4911 return pager_request(view, request, line);
4915 static struct view_ops blob_ops = {
4916 "line",
4917 { "blob" },
4918 VIEW_NO_FLAGS,
4920 blob_open,
4921 blob_read,
4922 pager_draw,
4923 blob_request,
4924 pager_grep,
4925 pager_select,
4929 * Blame backend
4931 * Loading the blame view is a two phase job:
4933 * 1. File content is read either using opt_file from the
4934 * filesystem or using git-cat-file.
4935 * 2. Then blame information is incrementally added by
4936 * reading output from git-blame.
4939 struct blame {
4940 struct blame_commit *commit;
4941 unsigned long lineno;
4942 char text[1];
4945 struct blame_state {
4946 struct blame_commit *commit;
4947 int blamed;
4948 bool done_reading;
4949 bool auto_filename_display;
4952 static bool
4953 blame_detect_filename_display(struct view *view)
4955 bool show_filenames = FALSE;
4956 const char *filename = NULL;
4957 int i;
4959 if (opt_blame_argv) {
4960 for (i = 0; opt_blame_argv[i]; i++) {
4961 if (prefixcmp(opt_blame_argv[i], "-C"))
4962 continue;
4964 show_filenames = TRUE;
4968 for (i = 0; i < view->lines; i++) {
4969 struct blame *blame = view->line[i].data;
4971 if (blame->commit && blame->commit->id[0]) {
4972 if (!filename)
4973 filename = blame->commit->filename;
4974 else if (strcmp(filename, blame->commit->filename))
4975 show_filenames = TRUE;
4979 return show_filenames;
4982 static bool
4983 blame_open(struct view *view, enum open_flags flags)
4985 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4986 char path[SIZEOF_STR];
4987 size_t i;
4989 if (!view->prev && *opt_prefix) {
4990 string_copy(path, opt_file);
4991 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4992 return FALSE;
4995 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4996 const char *blame_cat_file_argv[] = {
4997 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5000 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5001 return FALSE;
5004 /* First pass: remove multiple references to the same commit. */
5005 for (i = 0; i < view->lines; i++) {
5006 struct blame *blame = view->line[i].data;
5008 if (blame->commit && blame->commit->id[0])
5009 blame->commit->id[0] = 0;
5010 else
5011 blame->commit = NULL;
5014 /* Second pass: free existing references. */
5015 for (i = 0; i < view->lines; i++) {
5016 struct blame *blame = view->line[i].data;
5018 if (blame->commit)
5019 free(blame->commit);
5022 string_format(view->vid, "%s", opt_file);
5023 string_format(view->ref, "%s ...", opt_file);
5025 return TRUE;
5028 static struct blame_commit *
5029 get_blame_commit(struct view *view, const char *id)
5031 size_t i;
5033 for (i = 0; i < view->lines; i++) {
5034 struct blame *blame = view->line[i].data;
5036 if (!blame->commit)
5037 continue;
5039 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5040 return blame->commit;
5044 struct blame_commit *commit = calloc(1, sizeof(*commit));
5046 if (commit)
5047 string_ncopy(commit->id, id, SIZEOF_REV);
5048 return commit;
5052 static struct blame_commit *
5053 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5055 struct blame_header header;
5056 struct blame_commit *commit;
5057 struct blame *blame;
5059 if (!parse_blame_header(&header, text, view->lines))
5060 return NULL;
5062 commit = get_blame_commit(view, text);
5063 if (!commit)
5064 return NULL;
5066 state->blamed += header.group;
5067 while (header.group--) {
5068 struct line *line = &view->line[header.lineno + header.group - 1];
5070 blame = line->data;
5071 blame->commit = commit;
5072 blame->lineno = header.orig_lineno + header.group - 1;
5073 line->dirty = 1;
5076 return commit;
5079 static bool
5080 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5082 if (!line) {
5083 const char *blame_argv[] = {
5084 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5085 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5088 if (view->lines == 0 && !view->prev)
5089 die("No blame exist for %s", view->vid);
5091 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5092 report("Failed to load blame data");
5093 return TRUE;
5096 if (opt_goto_line > 0) {
5097 select_view_line(view, opt_goto_line);
5098 opt_goto_line = 0;
5101 state->done_reading = TRUE;
5102 return FALSE;
5104 } else {
5105 size_t linelen = strlen(line);
5106 struct blame *blame = malloc(sizeof(*blame) + linelen);
5108 if (!blame)
5109 return FALSE;
5111 blame->commit = NULL;
5112 strncpy(blame->text, line, linelen);
5113 blame->text[linelen] = 0;
5114 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5118 static bool
5119 blame_read(struct view *view, char *line)
5121 struct blame_state *state = view->private;
5123 if (!state->done_reading)
5124 return blame_read_file(view, line, state);
5126 if (!line) {
5127 state->auto_filename_display = blame_detect_filename_display(view);
5128 string_format(view->ref, "%s", view->vid);
5129 if (view_is_displayed(view)) {
5130 update_view_title(view);
5131 redraw_view_from(view, 0);
5133 return TRUE;
5136 if (!state->commit) {
5137 state->commit = read_blame_commit(view, line, state);
5138 string_format(view->ref, "%s %2d%%", view->vid,
5139 view->lines ? state->blamed * 100 / view->lines : 0);
5141 } else if (parse_blame_info(state->commit, line)) {
5142 state->commit = NULL;
5145 return TRUE;
5148 static bool
5149 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5151 struct blame_state *state = view->private;
5152 struct blame *blame = line->data;
5153 struct time *time = NULL;
5154 const char *id = NULL, *author = NULL, *filename = NULL;
5155 enum line_type id_type = LINE_BLAME_ID;
5156 static const enum line_type blame_colors[] = {
5157 LINE_PALETTE_0,
5158 LINE_PALETTE_1,
5159 LINE_PALETTE_2,
5160 LINE_PALETTE_3,
5161 LINE_PALETTE_4,
5162 LINE_PALETTE_5,
5163 LINE_PALETTE_6,
5166 #define BLAME_COLOR(i) \
5167 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5169 if (blame->commit && *blame->commit->filename) {
5170 id = blame->commit->id;
5171 author = blame->commit->author;
5172 filename = blame->commit->filename;
5173 time = &blame->commit->time;
5174 id_type = BLAME_COLOR((long) blame->commit);
5177 if (draw_date(view, time))
5178 return TRUE;
5180 if (draw_author(view, author))
5181 return TRUE;
5183 if (draw_filename(view, filename, state->auto_filename_display))
5184 return TRUE;
5186 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5187 return TRUE;
5189 if (draw_lineno(view, lineno))
5190 return TRUE;
5192 draw_text(view, LINE_DEFAULT, blame->text);
5193 return TRUE;
5196 static bool
5197 check_blame_commit(struct blame *blame, bool check_null_id)
5199 if (!blame->commit)
5200 report("Commit data not loaded yet");
5201 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5202 report("No commit exist for the selected line");
5203 else
5204 return TRUE;
5205 return FALSE;
5208 static void
5209 setup_blame_parent_line(struct view *view, struct blame *blame)
5211 char from[SIZEOF_REF + SIZEOF_STR];
5212 char to[SIZEOF_REF + SIZEOF_STR];
5213 const char *diff_tree_argv[] = {
5214 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5215 "--no-color", "-U0", from, to, "--", NULL
5217 struct io io;
5218 int parent_lineno = -1;
5219 int blamed_lineno = -1;
5220 char *line;
5222 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5223 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5224 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5225 return;
5227 while ((line = io_get(&io, '\n', TRUE))) {
5228 if (*line == '@') {
5229 char *pos = strchr(line, '+');
5231 parent_lineno = atoi(line + 4);
5232 if (pos)
5233 blamed_lineno = atoi(pos + 1);
5235 } else if (*line == '+' && parent_lineno != -1) {
5236 if (blame->lineno == blamed_lineno - 1 &&
5237 !strcmp(blame->text, line + 1)) {
5238 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5239 break;
5241 blamed_lineno++;
5245 io_done(&io);
5248 static enum request
5249 blame_request(struct view *view, enum request request, struct line *line)
5251 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5252 struct blame *blame = line->data;
5254 switch (request) {
5255 case REQ_VIEW_BLAME:
5256 if (check_blame_commit(blame, TRUE)) {
5257 string_copy(opt_ref, blame->commit->id);
5258 string_copy(opt_file, blame->commit->filename);
5259 if (blame->lineno)
5260 view->pos.lineno = blame->lineno;
5261 reload_view(view);
5263 break;
5265 case REQ_PARENT:
5266 if (!check_blame_commit(blame, TRUE))
5267 break;
5268 if (!*blame->commit->parent_id) {
5269 report("The selected commit has no parents");
5270 } else {
5271 string_copy_rev(opt_ref, blame->commit->parent_id);
5272 string_copy(opt_file, blame->commit->parent_filename);
5273 setup_blame_parent_line(view, blame);
5274 opt_goto_line = blame->lineno;
5275 reload_view(view);
5277 break;
5279 case REQ_ENTER:
5280 if (!check_blame_commit(blame, FALSE))
5281 break;
5283 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5284 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5285 break;
5287 if (!strcmp(blame->commit->id, NULL_ID)) {
5288 struct view *diff = VIEW(REQ_VIEW_DIFF);
5289 const char *diff_parent_argv[] = {
5290 GIT_DIFF_BLAME(opt_diff_context_arg,
5291 opt_ignore_space_arg, view->vid)
5293 const char *diff_no_parent_argv[] = {
5294 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5295 opt_ignore_space_arg, view->vid)
5297 const char **diff_index_argv = *blame->commit->parent_id
5298 ? diff_parent_argv : diff_no_parent_argv;
5300 open_argv(view, diff, diff_index_argv, NULL, flags);
5301 if (diff->pipe)
5302 string_copy_rev(diff->ref, NULL_ID);
5303 } else {
5304 open_view(view, REQ_VIEW_DIFF, flags);
5306 break;
5308 default:
5309 return request;
5312 return REQ_NONE;
5315 static bool
5316 blame_grep(struct view *view, struct line *line)
5318 struct blame *blame = line->data;
5319 struct blame_commit *commit = blame->commit;
5320 const char *text[] = {
5321 blame->text,
5322 commit ? commit->title : "",
5323 commit ? commit->id : "",
5324 commit && opt_author ? commit->author : "",
5325 commit ? mkdate(&commit->time, opt_date) : "",
5326 NULL
5329 return grep_text(view, text);
5332 static void
5333 blame_select(struct view *view, struct line *line)
5335 struct blame *blame = line->data;
5336 struct blame_commit *commit = blame->commit;
5338 if (!commit)
5339 return;
5341 if (!strcmp(commit->id, NULL_ID))
5342 string_ncopy(ref_commit, "HEAD", 4);
5343 else
5344 string_copy_rev(ref_commit, commit->id);
5347 static struct view_ops blame_ops = {
5348 "line",
5349 { "blame" },
5350 VIEW_ALWAYS_LINENO,
5351 sizeof(struct blame_state),
5352 blame_open,
5353 blame_read,
5354 blame_draw,
5355 blame_request,
5356 blame_grep,
5357 blame_select,
5361 * Branch backend
5364 struct branch {
5365 const char *author; /* Author of the last commit. */
5366 struct time time; /* Date of the last activity. */
5367 const struct ref *ref; /* Name and commit ID information. */
5370 static const struct ref branch_all;
5372 static const enum sort_field branch_sort_fields[] = {
5373 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5375 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5377 struct branch_state {
5378 char id[SIZEOF_REV];
5381 static int
5382 branch_compare(const void *l1, const void *l2)
5384 const struct branch *branch1 = ((const struct line *) l1)->data;
5385 const struct branch *branch2 = ((const struct line *) l2)->data;
5387 if (branch1->ref == &branch_all)
5388 return -1;
5389 else if (branch2->ref == &branch_all)
5390 return 1;
5392 switch (get_sort_field(branch_sort_state)) {
5393 case ORDERBY_DATE:
5394 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5396 case ORDERBY_AUTHOR:
5397 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5399 case ORDERBY_NAME:
5400 default:
5401 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5405 static bool
5406 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5408 struct branch *branch = line->data;
5409 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5411 if (draw_date(view, &branch->time))
5412 return TRUE;
5414 if (draw_author(view, branch->author))
5415 return TRUE;
5417 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5418 return TRUE;
5421 static enum request
5422 branch_request(struct view *view, enum request request, struct line *line)
5424 struct branch *branch = line->data;
5426 switch (request) {
5427 case REQ_REFRESH:
5428 load_refs();
5429 refresh_view(view);
5430 return REQ_NONE;
5432 case REQ_TOGGLE_SORT_FIELD:
5433 case REQ_TOGGLE_SORT_ORDER:
5434 sort_view(view, request, &branch_sort_state, branch_compare);
5435 return REQ_NONE;
5437 case REQ_ENTER:
5439 const struct ref *ref = branch->ref;
5440 const char *all_branches_argv[] = {
5441 "git", "log", ENCODING_ARG, "--no-color",
5442 "--pretty=raw", "--parents", opt_commit_order_arg,
5443 ref == &branch_all ? "--all" : ref->name, NULL
5445 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5447 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5448 return REQ_NONE;
5450 case REQ_JUMP_COMMIT:
5452 int lineno;
5454 for (lineno = 0; lineno < view->lines; lineno++) {
5455 struct branch *branch = view->line[lineno].data;
5457 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5458 select_view_line(view, lineno);
5459 report("");
5460 return REQ_NONE;
5464 default:
5465 return request;
5469 static bool
5470 branch_read(struct view *view, char *line)
5472 struct branch_state *state = view->private;
5473 struct branch *reference;
5474 size_t i;
5476 if (!line)
5477 return TRUE;
5479 switch (get_line_type(line)) {
5480 case LINE_COMMIT:
5481 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5482 return TRUE;
5484 case LINE_AUTHOR:
5485 for (i = 0, reference = NULL; i < view->lines; i++) {
5486 struct branch *branch = view->line[i].data;
5488 if (strcmp(branch->ref->id, state->id))
5489 continue;
5491 view->line[i].dirty = TRUE;
5492 if (reference) {
5493 branch->author = reference->author;
5494 branch->time = reference->time;
5495 continue;
5498 parse_author_line(line + STRING_SIZE("author "),
5499 &branch->author, &branch->time);
5500 reference = branch;
5502 return TRUE;
5504 default:
5505 return TRUE;
5510 static bool
5511 branch_open_visitor(void *data, const struct ref *ref)
5513 struct view *view = data;
5514 struct branch *branch;
5516 if (ref->tag || ref->ltag)
5517 return TRUE;
5519 branch = calloc(1, sizeof(*branch));
5520 if (!branch)
5521 return FALSE;
5523 branch->ref = ref;
5524 return !!add_line_data(view, branch, LINE_DEFAULT);
5527 static bool
5528 branch_open(struct view *view, enum open_flags flags)
5530 const char *branch_log[] = {
5531 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5532 "--simplify-by-decoration", "--all", NULL
5535 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5536 report("Failed to load branch data");
5537 return TRUE;
5540 branch_open_visitor(view, &branch_all);
5541 foreach_ref(branch_open_visitor, view);
5543 return TRUE;
5546 static bool
5547 branch_grep(struct view *view, struct line *line)
5549 struct branch *branch = line->data;
5550 const char *text[] = {
5551 branch->ref->name,
5552 mkauthor(branch->author, opt_author_cols, opt_author),
5553 NULL
5556 return grep_text(view, text);
5559 static void
5560 branch_select(struct view *view, struct line *line)
5562 struct branch *branch = line->data;
5564 string_copy_rev(view->ref, branch->ref->id);
5565 string_copy_rev(ref_commit, branch->ref->id);
5566 string_copy_rev(ref_head, branch->ref->id);
5567 string_copy_rev(ref_branch, branch->ref->name);
5570 static struct view_ops branch_ops = {
5571 "branch",
5572 { "branch" },
5573 VIEW_NO_FLAGS,
5574 sizeof(struct branch_state),
5575 branch_open,
5576 branch_read,
5577 branch_draw,
5578 branch_request,
5579 branch_grep,
5580 branch_select,
5584 * Status backend
5587 struct status {
5588 char status;
5589 struct {
5590 mode_t mode;
5591 char rev[SIZEOF_REV];
5592 char name[SIZEOF_STR];
5593 } old;
5594 struct {
5595 mode_t mode;
5596 char rev[SIZEOF_REV];
5597 char name[SIZEOF_STR];
5598 } new;
5601 static char status_onbranch[SIZEOF_STR];
5602 static struct status stage_status;
5603 static enum line_type stage_line_type;
5605 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5607 /* This should work even for the "On branch" line. */
5608 static inline bool
5609 status_has_none(struct view *view, struct line *line)
5611 return line < view->line + view->lines && !line[1].data;
5614 /* Get fields from the diff line:
5615 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5617 static inline bool
5618 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5620 const char *old_mode = buf + 1;
5621 const char *new_mode = buf + 8;
5622 const char *old_rev = buf + 15;
5623 const char *new_rev = buf + 56;
5624 const char *status = buf + 97;
5626 if (bufsize < 98 ||
5627 old_mode[-1] != ':' ||
5628 new_mode[-1] != ' ' ||
5629 old_rev[-1] != ' ' ||
5630 new_rev[-1] != ' ' ||
5631 status[-1] != ' ')
5632 return FALSE;
5634 file->status = *status;
5636 string_copy_rev(file->old.rev, old_rev);
5637 string_copy_rev(file->new.rev, new_rev);
5639 file->old.mode = strtoul(old_mode, NULL, 8);
5640 file->new.mode = strtoul(new_mode, NULL, 8);
5642 file->old.name[0] = file->new.name[0] = 0;
5644 return TRUE;
5647 static bool
5648 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5650 struct status *unmerged = NULL;
5651 char *buf;
5652 struct io io;
5654 if (!io_run(&io, IO_RD, opt_cdup, argv))
5655 return FALSE;
5657 add_line_data(view, NULL, type);
5659 while ((buf = io_get(&io, 0, TRUE))) {
5660 struct status *file = unmerged;
5662 if (!file) {
5663 file = calloc(1, sizeof(*file));
5664 if (!file || !add_line_data(view, file, type))
5665 goto error_out;
5668 /* Parse diff info part. */
5669 if (status) {
5670 file->status = status;
5671 if (status == 'A')
5672 string_copy(file->old.rev, NULL_ID);
5674 } else if (!file->status || file == unmerged) {
5675 if (!status_get_diff(file, buf, strlen(buf)))
5676 goto error_out;
5678 buf = io_get(&io, 0, TRUE);
5679 if (!buf)
5680 break;
5682 /* Collapse all modified entries that follow an
5683 * associated unmerged entry. */
5684 if (unmerged == file) {
5685 unmerged->status = 'U';
5686 unmerged = NULL;
5687 } else if (file->status == 'U') {
5688 unmerged = file;
5692 /* Grab the old name for rename/copy. */
5693 if (!*file->old.name &&
5694 (file->status == 'R' || file->status == 'C')) {
5695 string_ncopy(file->old.name, buf, strlen(buf));
5697 buf = io_get(&io, 0, TRUE);
5698 if (!buf)
5699 break;
5702 /* git-ls-files just delivers a NUL separated list of
5703 * file names similar to the second half of the
5704 * git-diff-* output. */
5705 string_ncopy(file->new.name, buf, strlen(buf));
5706 if (!*file->old.name)
5707 string_copy(file->old.name, file->new.name);
5708 file = NULL;
5711 if (io_error(&io)) {
5712 error_out:
5713 io_done(&io);
5714 return FALSE;
5717 if (!view->line[view->lines - 1].data)
5718 add_line_data(view, NULL, LINE_STAT_NONE);
5720 io_done(&io);
5721 return TRUE;
5724 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5725 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5727 static const char *status_list_other_argv[] = {
5728 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5731 static const char *status_list_no_head_argv[] = {
5732 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5735 static const char *update_index_argv[] = {
5736 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5739 /* Restore the previous line number to stay in the context or select a
5740 * line with something that can be updated. */
5741 static void
5742 status_restore(struct view *view)
5744 if (view->prev_pos.lineno >= view->lines)
5745 view->prev_pos.lineno = view->lines - 1;
5746 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5747 view->prev_pos.lineno++;
5748 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5749 view->prev_pos.lineno--;
5751 /* If the above fails, always skip the "On branch" line. */
5752 if (view->prev_pos.lineno < view->lines)
5753 view->pos.lineno = view->prev_pos.lineno;
5754 else
5755 view->pos.lineno = 1;
5757 if (view->prev_pos.offset > view->pos.lineno)
5758 view->pos.offset = view->pos.lineno;
5759 else if (view->prev_pos.offset < view->lines)
5760 view->pos.offset = view->prev_pos.offset;
5762 clear_position(&view->prev_pos);
5765 static void
5766 status_update_onbranch(void)
5768 static const char *paths[][2] = {
5769 { "rebase-apply/rebasing", "Rebasing" },
5770 { "rebase-apply/applying", "Applying mailbox" },
5771 { "rebase-apply/", "Rebasing mailbox" },
5772 { "rebase-merge/interactive", "Interactive rebase" },
5773 { "rebase-merge/", "Rebase merge" },
5774 { "MERGE_HEAD", "Merging" },
5775 { "BISECT_LOG", "Bisecting" },
5776 { "HEAD", "On branch" },
5778 char buf[SIZEOF_STR];
5779 struct stat stat;
5780 int i;
5782 if (is_initial_commit()) {
5783 string_copy(status_onbranch, "Initial commit");
5784 return;
5787 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5788 char *head = opt_head;
5790 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5791 lstat(buf, &stat) < 0)
5792 continue;
5794 if (!*opt_head) {
5795 struct io io;
5797 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5798 io_read_buf(&io, buf, sizeof(buf))) {
5799 head = buf;
5800 if (!prefixcmp(head, "refs/heads/"))
5801 head += STRING_SIZE("refs/heads/");
5805 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5806 string_copy(status_onbranch, opt_head);
5807 return;
5810 string_copy(status_onbranch, "Not currently on any branch");
5813 /* First parse staged info using git-diff-index(1), then parse unstaged
5814 * info using git-diff-files(1), and finally untracked files using
5815 * git-ls-files(1). */
5816 static bool
5817 status_open(struct view *view, enum open_flags flags)
5819 reset_view(view);
5821 add_line_data(view, NULL, LINE_STAT_HEAD);
5822 status_update_onbranch();
5824 io_run_bg(update_index_argv);
5826 if (is_initial_commit()) {
5827 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5828 return FALSE;
5829 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5830 return FALSE;
5833 if (!opt_untracked_dirs_content)
5834 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5836 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5837 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5838 return FALSE;
5840 /* Restore the exact position or use the specialized restore
5841 * mode? */
5842 status_restore(view);
5843 return TRUE;
5846 static bool
5847 status_draw(struct view *view, struct line *line, unsigned int lineno)
5849 struct status *status = line->data;
5850 enum line_type type;
5851 const char *text;
5853 if (!status) {
5854 switch (line->type) {
5855 case LINE_STAT_STAGED:
5856 type = LINE_STAT_SECTION;
5857 text = "Changes to be committed:";
5858 break;
5860 case LINE_STAT_UNSTAGED:
5861 type = LINE_STAT_SECTION;
5862 text = "Changed but not updated:";
5863 break;
5865 case LINE_STAT_UNTRACKED:
5866 type = LINE_STAT_SECTION;
5867 text = "Untracked files:";
5868 break;
5870 case LINE_STAT_NONE:
5871 type = LINE_DEFAULT;
5872 text = " (no files)";
5873 break;
5875 case LINE_STAT_HEAD:
5876 type = LINE_STAT_HEAD;
5877 text = status_onbranch;
5878 break;
5880 default:
5881 return FALSE;
5883 } else {
5884 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5886 buf[0] = status->status;
5887 if (draw_text(view, line->type, buf))
5888 return TRUE;
5889 type = LINE_DEFAULT;
5890 text = status->new.name;
5893 draw_text(view, type, text);
5894 return TRUE;
5897 static enum request
5898 status_enter(struct view *view, struct line *line)
5900 struct status *status = line->data;
5901 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5903 if (line->type == LINE_STAT_NONE ||
5904 (!status && line[1].type == LINE_STAT_NONE)) {
5905 report("No file to diff");
5906 return REQ_NONE;
5909 switch (line->type) {
5910 case LINE_STAT_STAGED:
5911 case LINE_STAT_UNSTAGED:
5912 break;
5914 case LINE_STAT_UNTRACKED:
5915 if (!status) {
5916 report("No file to show");
5917 return REQ_NONE;
5920 if (!suffixcmp(status->new.name, -1, "/")) {
5921 report("Cannot display a directory");
5922 return REQ_NONE;
5924 break;
5926 case LINE_STAT_HEAD:
5927 return REQ_NONE;
5929 default:
5930 die("line type %d not handled in switch", line->type);
5933 if (status) {
5934 stage_status = *status;
5935 } else {
5936 memset(&stage_status, 0, sizeof(stage_status));
5939 stage_line_type = line->type;
5941 open_view(view, REQ_VIEW_STAGE, flags);
5942 return REQ_NONE;
5945 static bool
5946 status_exists(struct view *view, struct status *status, enum line_type type)
5948 unsigned long lineno;
5950 for (lineno = 0; lineno < view->lines; lineno++) {
5951 struct line *line = &view->line[lineno];
5952 struct status *pos = line->data;
5954 if (line->type != type)
5955 continue;
5956 if (!pos && (!status || !status->status) && line[1].data) {
5957 select_view_line(view, lineno);
5958 return TRUE;
5960 if (pos && !strcmp(status->new.name, pos->new.name)) {
5961 select_view_line(view, lineno);
5962 return TRUE;
5966 return FALSE;
5970 static bool
5971 status_update_prepare(struct io *io, enum line_type type)
5973 const char *staged_argv[] = {
5974 "git", "update-index", "-z", "--index-info", NULL
5976 const char *others_argv[] = {
5977 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5980 switch (type) {
5981 case LINE_STAT_STAGED:
5982 return io_run(io, IO_WR, opt_cdup, staged_argv);
5984 case LINE_STAT_UNSTAGED:
5985 case LINE_STAT_UNTRACKED:
5986 return io_run(io, IO_WR, opt_cdup, others_argv);
5988 default:
5989 die("line type %d not handled in switch", type);
5990 return FALSE;
5994 static bool
5995 status_update_write(struct io *io, struct status *status, enum line_type type)
5997 switch (type) {
5998 case LINE_STAT_STAGED:
5999 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6000 status->old.rev, status->old.name, 0);
6002 case LINE_STAT_UNSTAGED:
6003 case LINE_STAT_UNTRACKED:
6004 return io_printf(io, "%s%c", status->new.name, 0);
6006 default:
6007 die("line type %d not handled in switch", type);
6008 return FALSE;
6012 static bool
6013 status_update_file(struct status *status, enum line_type type)
6015 struct io io;
6016 bool result;
6018 if (!status_update_prepare(&io, type))
6019 return FALSE;
6021 result = status_update_write(&io, status, type);
6022 return io_done(&io) && result;
6025 static bool
6026 status_update_files(struct view *view, struct line *line)
6028 char buf[sizeof(view->ref)];
6029 struct io io;
6030 bool result = TRUE;
6031 struct line *pos = view->line + view->lines;
6032 int files = 0;
6033 int file, done;
6034 int cursor_y = -1, cursor_x = -1;
6036 if (!status_update_prepare(&io, line->type))
6037 return FALSE;
6039 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
6040 files++;
6042 string_copy(buf, view->ref);
6043 getsyx(cursor_y, cursor_x);
6044 for (file = 0, done = 5; result && file < files; line++, file++) {
6045 int almost_done = file * 100 / files;
6047 if (almost_done > done) {
6048 done = almost_done;
6049 string_format(view->ref, "updating file %u of %u (%d%% done)",
6050 file, files, done);
6051 update_view_title(view);
6052 setsyx(cursor_y, cursor_x);
6053 doupdate();
6055 result = status_update_write(&io, line->data, line->type);
6057 string_copy(view->ref, buf);
6059 return io_done(&io) && result;
6062 static bool
6063 status_update(struct view *view)
6065 struct line *line = &view->line[view->pos.lineno];
6067 assert(view->lines);
6069 if (!line->data) {
6070 /* This should work even for the "On branch" line. */
6071 if (line < view->line + view->lines && !line[1].data) {
6072 report("Nothing to update");
6073 return FALSE;
6076 if (!status_update_files(view, line + 1)) {
6077 report("Failed to update file status");
6078 return FALSE;
6081 } else if (!status_update_file(line->data, line->type)) {
6082 report("Failed to update file status");
6083 return FALSE;
6086 return TRUE;
6089 static bool
6090 status_revert(struct status *status, enum line_type type, bool has_none)
6092 if (!status || type != LINE_STAT_UNSTAGED) {
6093 if (type == LINE_STAT_STAGED) {
6094 report("Cannot revert changes to staged files");
6095 } else if (type == LINE_STAT_UNTRACKED) {
6096 report("Cannot revert changes to untracked files");
6097 } else if (has_none) {
6098 report("Nothing to revert");
6099 } else {
6100 report("Cannot revert changes to multiple files");
6103 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6104 char mode[10] = "100644";
6105 const char *reset_argv[] = {
6106 "git", "update-index", "--cacheinfo", mode,
6107 status->old.rev, status->old.name, NULL
6109 const char *checkout_argv[] = {
6110 "git", "checkout", "--", status->old.name, NULL
6113 if (status->status == 'U') {
6114 string_format(mode, "%5o", status->old.mode);
6116 if (status->old.mode == 0 && status->new.mode == 0) {
6117 reset_argv[2] = "--force-remove";
6118 reset_argv[3] = status->old.name;
6119 reset_argv[4] = NULL;
6122 if (!io_run_fg(reset_argv, opt_cdup))
6123 return FALSE;
6124 if (status->old.mode == 0 && status->new.mode == 0)
6125 return TRUE;
6128 return io_run_fg(checkout_argv, opt_cdup);
6131 return FALSE;
6134 static enum request
6135 status_request(struct view *view, enum request request, struct line *line)
6137 struct status *status = line->data;
6139 switch (request) {
6140 case REQ_STATUS_UPDATE:
6141 if (!status_update(view))
6142 return REQ_NONE;
6143 break;
6145 case REQ_STATUS_REVERT:
6146 if (!status_revert(status, line->type, status_has_none(view, line)))
6147 return REQ_NONE;
6148 break;
6150 case REQ_STATUS_MERGE:
6151 if (!status || status->status != 'U') {
6152 report("Merging only possible for files with unmerged status ('U').");
6153 return REQ_NONE;
6155 open_mergetool(status->new.name);
6156 break;
6158 case REQ_EDIT:
6159 if (!status)
6160 return request;
6161 if (status->status == 'D') {
6162 report("File has been deleted.");
6163 return REQ_NONE;
6166 open_editor(status->new.name);
6167 break;
6169 case REQ_VIEW_BLAME:
6170 if (status)
6171 opt_ref[0] = 0;
6172 return request;
6174 case REQ_ENTER:
6175 /* After returning the status view has been split to
6176 * show the stage view. No further reloading is
6177 * necessary. */
6178 return status_enter(view, line);
6180 case REQ_REFRESH:
6181 /* Simply reload the view. */
6182 break;
6184 default:
6185 return request;
6188 refresh_view(view);
6190 return REQ_NONE;
6193 static void
6194 status_select(struct view *view, struct line *line)
6196 struct status *status = line->data;
6197 char file[SIZEOF_STR] = "all files";
6198 const char *text;
6199 const char *key;
6201 if (status && !string_format(file, "'%s'", status->new.name))
6202 return;
6204 if (!status && line[1].type == LINE_STAT_NONE)
6205 line++;
6207 switch (line->type) {
6208 case LINE_STAT_STAGED:
6209 text = "Press %s to unstage %s for commit";
6210 break;
6212 case LINE_STAT_UNSTAGED:
6213 text = "Press %s to stage %s for commit";
6214 break;
6216 case LINE_STAT_UNTRACKED:
6217 text = "Press %s to stage %s for addition";
6218 break;
6220 case LINE_STAT_HEAD:
6221 case LINE_STAT_NONE:
6222 text = "Nothing to update";
6223 break;
6225 default:
6226 die("line type %d not handled in switch", line->type);
6229 if (status && status->status == 'U') {
6230 text = "Press %s to resolve conflict in %s";
6231 key = get_view_key(view, REQ_STATUS_MERGE);
6233 } else {
6234 key = get_view_key(view, REQ_STATUS_UPDATE);
6237 string_format(view->ref, text, key, file);
6238 if (status)
6239 string_copy(opt_file, status->new.name);
6242 static bool
6243 status_grep(struct view *view, struct line *line)
6245 struct status *status = line->data;
6247 if (status) {
6248 const char buf[2] = { status->status, 0 };
6249 const char *text[] = { status->new.name, buf, NULL };
6251 return grep_text(view, text);
6254 return FALSE;
6257 static struct view_ops status_ops = {
6258 "file",
6259 { "status" },
6260 VIEW_CUSTOM_STATUS,
6262 status_open,
6263 NULL,
6264 status_draw,
6265 status_request,
6266 status_grep,
6267 status_select,
6271 struct stage_state {
6272 struct diff_state diff;
6273 size_t chunks;
6274 int *chunk;
6277 static bool
6278 stage_diff_write(struct io *io, struct line *line, struct line *end)
6280 while (line < end) {
6281 if (!io_write(io, line->data, strlen(line->data)) ||
6282 !io_write(io, "\n", 1))
6283 return FALSE;
6284 line++;
6285 if (line->type == LINE_DIFF_CHUNK ||
6286 line->type == LINE_DIFF_HEADER)
6287 break;
6290 return TRUE;
6293 static bool
6294 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6296 const char *apply_argv[SIZEOF_ARG] = {
6297 "git", "apply", "--whitespace=nowarn", NULL
6299 struct line *diff_hdr;
6300 struct io io;
6301 int argc = 3;
6303 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6304 if (!diff_hdr)
6305 return FALSE;
6307 if (!revert)
6308 apply_argv[argc++] = "--cached";
6309 if (line != NULL)
6310 apply_argv[argc++] = "--unidiff-zero";
6311 if (revert || stage_line_type == LINE_STAT_STAGED)
6312 apply_argv[argc++] = "-R";
6313 apply_argv[argc++] = "-";
6314 apply_argv[argc++] = NULL;
6315 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6316 return FALSE;
6318 if (line != NULL) {
6319 int lineno = 0;
6320 struct line *context = chunk + 1;
6321 const char *markers[] = {
6322 line->type == LINE_DIFF_DEL ? "" : ",0",
6323 line->type == LINE_DIFF_DEL ? ",0" : "",
6326 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6328 while (context < line) {
6329 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6330 break;
6331 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6332 lineno++;
6334 context++;
6337 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6338 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6339 lineno, markers[0], lineno, markers[1]) ||
6340 !stage_diff_write(&io, line, line + 1)) {
6341 chunk = NULL;
6343 } else {
6344 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6345 !stage_diff_write(&io, chunk, view->line + view->lines))
6346 chunk = NULL;
6349 io_done(&io);
6350 io_run_bg(update_index_argv);
6352 return chunk ? TRUE : FALSE;
6355 static bool
6356 stage_update(struct view *view, struct line *line, bool single)
6358 struct line *chunk = NULL;
6360 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6361 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6363 if (chunk) {
6364 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6365 report("Failed to apply chunk");
6366 return FALSE;
6369 } else if (!stage_status.status) {
6370 view = view->parent;
6372 for (line = view->line; line < view->line + view->lines; line++)
6373 if (line->type == stage_line_type)
6374 break;
6376 if (!status_update_files(view, line + 1)) {
6377 report("Failed to update files");
6378 return FALSE;
6381 } else if (!status_update_file(&stage_status, stage_line_type)) {
6382 report("Failed to update file");
6383 return FALSE;
6386 return TRUE;
6389 static bool
6390 stage_revert(struct view *view, struct line *line)
6392 struct line *chunk = NULL;
6394 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6395 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6397 if (chunk) {
6398 if (!prompt_yesno("Are you sure you want to revert changes?"))
6399 return FALSE;
6401 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6402 report("Failed to revert chunk");
6403 return FALSE;
6405 return TRUE;
6407 } else {
6408 return status_revert(stage_status.status ? &stage_status : NULL,
6409 stage_line_type, FALSE);
6414 static void
6415 stage_next(struct view *view, struct line *line)
6417 struct stage_state *state = view->private;
6418 int i;
6420 if (!state->chunks) {
6421 for (line = view->line; line < view->line + view->lines; line++) {
6422 if (line->type != LINE_DIFF_CHUNK)
6423 continue;
6425 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6426 report("Allocation failure");
6427 return;
6430 state->chunk[state->chunks++] = line - view->line;
6434 for (i = 0; i < state->chunks; i++) {
6435 if (state->chunk[i] > view->pos.lineno) {
6436 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6437 report("Chunk %d of %d", i + 1, state->chunks);
6438 return;
6442 report("No next chunk found");
6445 static enum request
6446 stage_request(struct view *view, enum request request, struct line *line)
6448 switch (request) {
6449 case REQ_STATUS_UPDATE:
6450 if (!stage_update(view, line, FALSE))
6451 return REQ_NONE;
6452 break;
6454 case REQ_STATUS_REVERT:
6455 if (!stage_revert(view, line))
6456 return REQ_NONE;
6457 break;
6459 case REQ_STAGE_UPDATE_LINE:
6460 if (stage_line_type == LINE_STAT_UNTRACKED ||
6461 stage_status.status == 'A') {
6462 report("Staging single lines is not supported for new files");
6463 return REQ_NONE;
6465 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6466 report("Please select a change to stage");
6467 return REQ_NONE;
6469 if (!stage_update(view, line, TRUE))
6470 return REQ_NONE;
6471 break;
6473 case REQ_STAGE_NEXT:
6474 if (stage_line_type == LINE_STAT_UNTRACKED) {
6475 report("File is untracked; press %s to add",
6476 get_view_key(view, REQ_STATUS_UPDATE));
6477 return REQ_NONE;
6479 stage_next(view, line);
6480 return REQ_NONE;
6482 case REQ_EDIT:
6483 if (!stage_status.new.name[0])
6484 return request;
6485 if (stage_status.status == 'D') {
6486 report("File has been deleted.");
6487 return REQ_NONE;
6490 open_editor(stage_status.new.name);
6491 break;
6493 case REQ_REFRESH:
6494 /* Reload everything ... */
6495 break;
6497 case REQ_VIEW_BLAME:
6498 if (stage_status.new.name[0]) {
6499 string_copy(opt_file, stage_status.new.name);
6500 opt_ref[0] = 0;
6502 return request;
6504 case REQ_ENTER:
6505 return diff_common_enter(view, request, line);
6507 case REQ_DIFF_CONTEXT_UP:
6508 case REQ_DIFF_CONTEXT_DOWN:
6509 if (!update_diff_context(request))
6510 return REQ_NONE;
6511 break;
6513 default:
6514 return request;
6517 refresh_view(view->parent);
6519 /* Check whether the staged entry still exists, and close the
6520 * stage view if it doesn't. */
6521 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6522 status_restore(view->parent);
6523 return REQ_VIEW_CLOSE;
6526 refresh_view(view);
6528 return REQ_NONE;
6531 static bool
6532 stage_open(struct view *view, enum open_flags flags)
6534 static const char *no_head_diff_argv[] = {
6535 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6536 stage_status.new.name)
6538 static const char *index_show_argv[] = {
6539 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6540 stage_status.old.name, stage_status.new.name)
6542 static const char *files_show_argv[] = {
6543 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6544 stage_status.old.name, stage_status.new.name)
6546 /* Diffs for unmerged entries are empty when passing the new
6547 * path, so leave out the new path. */
6548 static const char *files_unmerged_argv[] = {
6549 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6550 opt_diff_context_arg, opt_ignore_space_arg, "--",
6551 stage_status.old.name, NULL
6553 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6554 const char **argv = NULL;
6555 const char *info;
6557 view->encoding = NULL;
6559 switch (stage_line_type) {
6560 case LINE_STAT_STAGED:
6561 if (is_initial_commit()) {
6562 argv = no_head_diff_argv;
6563 } else {
6564 argv = index_show_argv;
6566 if (stage_status.status)
6567 info = "Staged changes to %s";
6568 else
6569 info = "Staged changes";
6570 break;
6572 case LINE_STAT_UNSTAGED:
6573 if (stage_status.status != 'U')
6574 argv = files_show_argv;
6575 else
6576 argv = files_unmerged_argv;
6577 if (stage_status.status)
6578 info = "Unstaged changes to %s";
6579 else
6580 info = "Unstaged changes";
6581 break;
6583 case LINE_STAT_UNTRACKED:
6584 info = "Untracked file %s";
6585 argv = file_argv;
6586 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6587 break;
6589 case LINE_STAT_HEAD:
6590 default:
6591 die("line type %d not handled in switch", stage_line_type);
6594 string_format(view->ref, info, stage_status.new.name);
6595 view->vid[0] = 0;
6596 view->dir = opt_cdup;
6597 return argv_copy(&view->argv, argv)
6598 && begin_update(view, NULL, NULL, flags);
6601 static bool
6602 stage_read(struct view *view, char *data)
6604 struct stage_state *state = view->private;
6606 if (data && diff_common_read(view, data, &state->diff))
6607 return TRUE;
6609 return pager_read(view, data);
6612 static struct view_ops stage_ops = {
6613 "line",
6614 { "stage" },
6615 VIEW_DIFF_LIKE,
6616 sizeof(struct stage_state),
6617 stage_open,
6618 stage_read,
6619 diff_common_draw,
6620 stage_request,
6621 pager_grep,
6622 pager_select,
6627 * Revision graph
6630 static const enum line_type graph_colors[] = {
6631 LINE_PALETTE_0,
6632 LINE_PALETTE_1,
6633 LINE_PALETTE_2,
6634 LINE_PALETTE_3,
6635 LINE_PALETTE_4,
6636 LINE_PALETTE_5,
6637 LINE_PALETTE_6,
6640 static enum line_type get_graph_color(struct graph_symbol *symbol)
6642 if (symbol->commit)
6643 return LINE_GRAPH_COMMIT;
6644 assert(symbol->color < ARRAY_SIZE(graph_colors));
6645 return graph_colors[symbol->color];
6648 static bool
6649 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6651 const char *chars = graph_symbol_to_utf8(symbol);
6653 return draw_text(view, color, chars + !!first);
6656 static bool
6657 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6659 const char *chars = graph_symbol_to_ascii(symbol);
6661 return draw_text(view, color, chars + !!first);
6664 static bool
6665 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6667 const chtype *chars = graph_symbol_to_chtype(symbol);
6669 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6672 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6674 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6676 static const draw_graph_fn fns[] = {
6677 draw_graph_ascii,
6678 draw_graph_chtype,
6679 draw_graph_utf8
6681 draw_graph_fn fn = fns[opt_line_graphics];
6682 int i;
6684 for (i = 0; i < canvas->size; i++) {
6685 struct graph_symbol *symbol = &canvas->symbols[i];
6686 enum line_type color = get_graph_color(symbol);
6688 if (fn(view, symbol, color, i == 0))
6689 return TRUE;
6692 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6696 * Main view backend
6699 struct commit {
6700 char id[SIZEOF_REV]; /* SHA1 ID. */
6701 char title[128]; /* First line of the commit message. */
6702 const char *author; /* Author of the commit. */
6703 struct time time; /* Date from the author ident. */
6704 struct ref_list *refs; /* Repository references. */
6705 struct graph_canvas graph; /* Ancestry chain graphics. */
6708 static struct commit *
6709 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6711 struct graph *graph = view->private;
6712 struct commit *commit;
6714 commit = calloc(1, sizeof(struct commit));
6715 if (!commit)
6716 return NULL;
6718 string_copy_rev(commit->id, ids);
6719 commit->refs = get_ref_list(commit->id);
6720 add_line_data(view, commit, type);
6721 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6722 return commit;
6725 bool
6726 main_has_changes(const char *argv[])
6728 struct io io;
6730 if (!io_run(&io, IO_BG, NULL, argv, -1))
6731 return FALSE;
6732 io_done(&io);
6733 return io.status == 1;
6736 static void
6737 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6739 char ids[SIZEOF_STR] = NULL_ID " ";
6740 struct graph *graph = view->private;
6741 struct commit *commit;
6742 struct timeval now;
6743 struct timezone tz;
6745 if (!parent)
6746 return;
6748 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6750 commit = main_add_commit(view, type, ids, FALSE);
6751 if (!commit)
6752 return;
6754 if (!gettimeofday(&now, &tz)) {
6755 commit->time.tz = tz.tz_minuteswest * 60;
6756 commit->time.sec = now.tv_sec - commit->time.tz;
6759 commit->author = "";
6760 string_ncopy(commit->title, title, strlen(title));
6761 graph_render_parents(graph);
6764 static void
6765 main_add_changes_commits(struct view *view, const char *parent)
6767 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6768 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6769 const char *staged_parent = NULL_ID;
6770 const char *unstaged_parent = parent;
6772 if (!main_has_changes(unstaged_argv)) {
6773 unstaged_parent = NULL;
6774 staged_parent = parent;
6777 if (!main_has_changes(staged_argv)) {
6778 staged_parent = NULL;
6781 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6782 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6785 static bool
6786 main_open(struct view *view, enum open_flags flags)
6788 static const char *main_argv[] = {
6789 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6790 opt_commit_order_arg, "%(diffargs)", "%(revargs)",
6791 "--", "%(fileargs)", NULL
6794 return begin_update(view, NULL, main_argv, flags);
6797 static bool
6798 main_draw(struct view *view, struct line *line, unsigned int lineno)
6800 struct commit *commit = line->data;
6802 if (!commit->author)
6803 return FALSE;
6805 if (draw_lineno(view, lineno))
6806 return TRUE;
6808 if (draw_date(view, &commit->time))
6809 return TRUE;
6811 if (draw_author(view, commit->author))
6812 return TRUE;
6814 if (opt_rev_graph && draw_graph(view, &commit->graph))
6815 return TRUE;
6817 if (draw_refs(view, commit->refs))
6818 return TRUE;
6820 draw_text(view, LINE_DEFAULT, commit->title);
6821 return TRUE;
6824 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6825 static bool
6826 main_read(struct view *view, char *line)
6828 struct graph *graph = view->private;
6829 enum line_type type;
6830 struct commit *commit;
6831 static bool in_header;
6833 if (!line) {
6834 if (!view->lines && !view->prev)
6835 die("No revisions match the given arguments.");
6836 if (view->lines > 0) {
6837 commit = view->line[view->lines - 1].data;
6838 view->line[view->lines - 1].dirty = 1;
6839 if (!commit->author) {
6840 view->lines--;
6841 free(commit);
6845 done_graph(graph);
6846 return TRUE;
6849 type = get_line_type(line);
6850 if (type == LINE_COMMIT) {
6851 bool is_boundary;
6853 in_header = TRUE;
6854 line += STRING_SIZE("commit ");
6855 is_boundary = *line == '-';
6856 if (is_boundary)
6857 line++;
6859 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6860 main_add_changes_commits(view, line);
6862 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6865 if (!view->lines)
6866 return TRUE;
6867 commit = view->line[view->lines - 1].data;
6869 /* Empty line separates the commit header from the log itself. */
6870 if (*line == '\0')
6871 in_header = FALSE;
6873 switch (type) {
6874 case LINE_PARENT:
6875 if (!graph->has_parents)
6876 graph_add_parent(graph, line + STRING_SIZE("parent "));
6877 break;
6879 case LINE_AUTHOR:
6880 parse_author_line(line + STRING_SIZE("author "),
6881 &commit->author, &commit->time);
6882 graph_render_parents(graph);
6883 break;
6885 default:
6886 /* Fill in the commit title if it has not already been set. */
6887 if (commit->title[0])
6888 break;
6890 /* Skip lines in the commit header. */
6891 if (in_header)
6892 break;
6894 /* Require titles to start with a non-space character at the
6895 * offset used by git log. */
6896 if (strncmp(line, " ", 4))
6897 break;
6898 line += 4;
6899 /* Well, if the title starts with a whitespace character,
6900 * try to be forgiving. Otherwise we end up with no title. */
6901 while (isspace(*line))
6902 line++;
6903 if (*line == '\0')
6904 break;
6905 /* FIXME: More graceful handling of titles; append "..." to
6906 * shortened titles, etc. */
6908 string_expand(commit->title, sizeof(commit->title), line, 1);
6909 view->line[view->lines - 1].dirty = 1;
6912 return TRUE;
6915 static enum request
6916 main_request(struct view *view, enum request request, struct line *line)
6918 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6920 switch (request) {
6921 case REQ_NEXT:
6922 case REQ_PREVIOUS:
6923 if (view_is_displayed(view) && display[0] != view)
6924 return request;
6925 /* Do not pass navigation requests to the branch view
6926 * when the main view is maximized. (GH #38) */
6927 move_view(view, request);
6928 break;
6930 case REQ_ENTER:
6931 if (view_is_displayed(view) && display[0] != view)
6932 maximize_view(view, TRUE);
6934 if (line->type == LINE_STAT_UNSTAGED
6935 || line->type == LINE_STAT_STAGED) {
6936 struct view *diff = VIEW(REQ_VIEW_DIFF);
6937 const char *diff_staged_argv[] = {
6938 GIT_DIFF_STAGED(opt_diff_context_arg,
6939 opt_ignore_space_arg, NULL, NULL)
6941 const char *diff_unstaged_argv[] = {
6942 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6943 opt_ignore_space_arg, NULL, NULL)
6945 const char **diff_argv = line->type == LINE_STAT_STAGED
6946 ? diff_staged_argv : diff_unstaged_argv;
6948 open_argv(view, diff, diff_argv, NULL, flags);
6949 break;
6952 open_view(view, REQ_VIEW_DIFF, flags);
6953 break;
6954 case REQ_REFRESH:
6955 load_refs();
6956 refresh_view(view);
6957 break;
6959 case REQ_JUMP_COMMIT:
6961 int lineno;
6963 for (lineno = 0; lineno < view->lines; lineno++) {
6964 struct commit *commit = view->line[lineno].data;
6966 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6967 select_view_line(view, lineno);
6968 report("");
6969 return REQ_NONE;
6973 report("Unable to find commit '%s'", opt_search);
6974 break;
6976 default:
6977 return request;
6980 return REQ_NONE;
6983 static bool
6984 grep_refs(struct ref_list *list, regex_t *regex)
6986 regmatch_t pmatch;
6987 size_t i;
6989 if (!opt_show_refs || !list)
6990 return FALSE;
6992 for (i = 0; i < list->size; i++) {
6993 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6994 return TRUE;
6997 return FALSE;
7000 static bool
7001 main_grep(struct view *view, struct line *line)
7003 struct commit *commit = line->data;
7004 const char *text[] = {
7005 commit->title,
7006 mkauthor(commit->author, opt_author_cols, opt_author),
7007 mkdate(&commit->time, opt_date),
7008 NULL
7011 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7014 static void
7015 main_select(struct view *view, struct line *line)
7017 struct commit *commit = line->data;
7019 string_copy_rev(view->ref, commit->id);
7020 string_copy_rev(ref_commit, view->ref);
7023 static struct view_ops main_ops = {
7024 "commit",
7025 { "main" },
7026 VIEW_NO_FLAGS,
7027 sizeof(struct graph),
7028 main_open,
7029 main_read,
7030 main_draw,
7031 main_request,
7032 main_grep,
7033 main_select,
7038 * Status management
7041 /* Whether or not the curses interface has been initialized. */
7042 static bool cursed = FALSE;
7044 /* Terminal hacks and workarounds. */
7045 static bool use_scroll_redrawwin;
7046 static bool use_scroll_status_wclear;
7048 /* The status window is used for polling keystrokes. */
7049 static WINDOW *status_win;
7051 /* Reading from the prompt? */
7052 static bool input_mode = FALSE;
7054 static bool status_empty = FALSE;
7056 /* Update status and title window. */
7057 static void
7058 report(const char *msg, ...)
7060 struct view *view = display[current_view];
7062 if (input_mode)
7063 return;
7065 if (!view) {
7066 char buf[SIZEOF_STR];
7067 int retval;
7069 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7070 die("%s", buf);
7073 if (!status_empty || *msg) {
7074 va_list args;
7076 va_start(args, msg);
7078 wmove(status_win, 0, 0);
7079 if (view->has_scrolled && use_scroll_status_wclear)
7080 wclear(status_win);
7081 if (*msg) {
7082 vwprintw(status_win, msg, args);
7083 status_empty = FALSE;
7084 } else {
7085 status_empty = TRUE;
7087 wclrtoeol(status_win);
7088 wnoutrefresh(status_win);
7090 va_end(args);
7093 update_view_title(view);
7096 static void
7097 init_display(void)
7099 const char *term;
7100 int x, y;
7102 /* Initialize the curses library */
7103 if (isatty(STDIN_FILENO)) {
7104 cursed = !!initscr();
7105 opt_tty = stdin;
7106 } else {
7107 /* Leave stdin and stdout alone when acting as a pager. */
7108 opt_tty = fopen("/dev/tty", "r+");
7109 if (!opt_tty)
7110 die("Failed to open /dev/tty");
7111 cursed = !!newterm(NULL, opt_tty, opt_tty);
7114 if (!cursed)
7115 die("Failed to initialize curses");
7117 nonl(); /* Disable conversion and detect newlines from input. */
7118 cbreak(); /* Take input chars one at a time, no wait for \n */
7119 noecho(); /* Don't echo input */
7120 leaveok(stdscr, FALSE);
7122 if (has_colors())
7123 init_colors();
7125 getmaxyx(stdscr, y, x);
7126 status_win = newwin(1, x, y - 1, 0);
7127 if (!status_win)
7128 die("Failed to create status window");
7130 /* Enable keyboard mapping */
7131 keypad(status_win, TRUE);
7132 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7134 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7135 set_tabsize(opt_tab_size);
7136 #else
7137 TABSIZE = opt_tab_size;
7138 #endif
7140 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7141 if (term && !strcmp(term, "gnome-terminal")) {
7142 /* In the gnome-terminal-emulator, the message from
7143 * scrolling up one line when impossible followed by
7144 * scrolling down one line causes corruption of the
7145 * status line. This is fixed by calling wclear. */
7146 use_scroll_status_wclear = TRUE;
7147 use_scroll_redrawwin = FALSE;
7149 } else if (term && !strcmp(term, "xrvt-xpm")) {
7150 /* No problems with full optimizations in xrvt-(unicode)
7151 * and aterm. */
7152 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7154 } else {
7155 /* When scrolling in (u)xterm the last line in the
7156 * scrolling direction will update slowly. */
7157 use_scroll_redrawwin = TRUE;
7158 use_scroll_status_wclear = FALSE;
7162 static int
7163 get_input(int prompt_position)
7165 struct view *view;
7166 int i, key, cursor_y, cursor_x;
7168 if (prompt_position)
7169 input_mode = TRUE;
7171 while (TRUE) {
7172 bool loading = FALSE;
7174 foreach_view (view, i) {
7175 update_view(view);
7176 if (view_is_displayed(view) && view->has_scrolled &&
7177 use_scroll_redrawwin)
7178 redrawwin(view->win);
7179 view->has_scrolled = FALSE;
7180 if (view->pipe)
7181 loading = TRUE;
7184 /* Update the cursor position. */
7185 if (prompt_position) {
7186 getbegyx(status_win, cursor_y, cursor_x);
7187 cursor_x = prompt_position;
7188 } else {
7189 view = display[current_view];
7190 getbegyx(view->win, cursor_y, cursor_x);
7191 cursor_x = view->width - 1;
7192 cursor_y += view->pos.lineno - view->pos.offset;
7194 setsyx(cursor_y, cursor_x);
7196 /* Refresh, accept single keystroke of input */
7197 doupdate();
7198 nodelay(status_win, loading);
7199 key = wgetch(status_win);
7201 /* wgetch() with nodelay() enabled returns ERR when
7202 * there's no input. */
7203 if (key == ERR) {
7205 } else if (key == KEY_RESIZE) {
7206 int height, width;
7208 getmaxyx(stdscr, height, width);
7210 wresize(status_win, 1, width);
7211 mvwin(status_win, height - 1, 0);
7212 wnoutrefresh(status_win);
7213 resize_display();
7214 redraw_display(TRUE);
7216 } else {
7217 input_mode = FALSE;
7218 if (key == erasechar())
7219 key = KEY_BACKSPACE;
7220 return key;
7225 static char *
7226 prompt_input(const char *prompt, input_handler handler, void *data)
7228 enum input_status status = INPUT_OK;
7229 static char buf[SIZEOF_STR];
7230 size_t pos = 0;
7232 buf[pos] = 0;
7234 while (status == INPUT_OK || status == INPUT_SKIP) {
7235 int key;
7237 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7238 wclrtoeol(status_win);
7240 key = get_input(pos + 1);
7241 switch (key) {
7242 case KEY_RETURN:
7243 case KEY_ENTER:
7244 case '\n':
7245 status = pos ? INPUT_STOP : INPUT_CANCEL;
7246 break;
7248 case KEY_BACKSPACE:
7249 if (pos > 0)
7250 buf[--pos] = 0;
7251 else
7252 status = INPUT_CANCEL;
7253 break;
7255 case KEY_ESC:
7256 status = INPUT_CANCEL;
7257 break;
7259 default:
7260 if (pos >= sizeof(buf)) {
7261 report("Input string too long");
7262 return NULL;
7265 status = handler(data, buf, key);
7266 if (status == INPUT_OK)
7267 buf[pos++] = (char) key;
7271 /* Clear the status window */
7272 status_empty = FALSE;
7273 report("");
7275 if (status == INPUT_CANCEL)
7276 return NULL;
7278 buf[pos++] = 0;
7280 return buf;
7283 static enum input_status
7284 prompt_yesno_handler(void *data, char *buf, int c)
7286 if (c == 'y' || c == 'Y')
7287 return INPUT_STOP;
7288 if (c == 'n' || c == 'N')
7289 return INPUT_CANCEL;
7290 return INPUT_SKIP;
7293 static bool
7294 prompt_yesno(const char *prompt)
7296 char prompt2[SIZEOF_STR];
7298 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7299 return FALSE;
7301 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7304 static enum input_status
7305 read_prompt_handler(void *data, char *buf, int c)
7307 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7310 static char *
7311 read_prompt(const char *prompt)
7313 return prompt_input(prompt, read_prompt_handler, NULL);
7316 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7318 enum input_status status = INPUT_OK;
7319 int size = 0;
7321 while (items[size].text)
7322 size++;
7324 while (status == INPUT_OK) {
7325 const struct menu_item *item = &items[*selected];
7326 int key;
7327 int i;
7329 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7330 prompt, *selected + 1, size);
7331 if (item->hotkey)
7332 wprintw(status_win, "[%c] ", (char) item->hotkey);
7333 wprintw(status_win, "%s", item->text);
7334 wclrtoeol(status_win);
7336 key = get_input(COLS - 1);
7337 switch (key) {
7338 case KEY_RETURN:
7339 case KEY_ENTER:
7340 case '\n':
7341 status = INPUT_STOP;
7342 break;
7344 case KEY_LEFT:
7345 case KEY_UP:
7346 *selected = *selected - 1;
7347 if (*selected < 0)
7348 *selected = size - 1;
7349 break;
7351 case KEY_RIGHT:
7352 case KEY_DOWN:
7353 *selected = (*selected + 1) % size;
7354 break;
7356 case KEY_ESC:
7357 status = INPUT_CANCEL;
7358 break;
7360 default:
7361 for (i = 0; items[i].text; i++)
7362 if (items[i].hotkey == key) {
7363 *selected = i;
7364 status = INPUT_STOP;
7365 break;
7370 /* Clear the status window */
7371 status_empty = FALSE;
7372 report("");
7374 return status != INPUT_CANCEL;
7378 * Repository properties
7382 static void
7383 set_remote_branch(const char *name, const char *value, size_t valuelen)
7385 if (!strcmp(name, ".remote")) {
7386 string_ncopy(opt_remote, value, valuelen);
7388 } else if (*opt_remote && !strcmp(name, ".merge")) {
7389 size_t from = strlen(opt_remote);
7391 if (!prefixcmp(value, "refs/heads/"))
7392 value += STRING_SIZE("refs/heads/");
7394 if (!string_format_from(opt_remote, &from, "/%s", value))
7395 opt_remote[0] = 0;
7399 static void
7400 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7402 const char *argv[SIZEOF_ARG] = { name, "=" };
7403 int argc = 1 + (cmd == option_set_command);
7404 enum option_code error;
7406 if (!argv_from_string(argv, &argc, value))
7407 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7408 else
7409 error = cmd(argc, argv);
7411 if (error != OPT_OK)
7412 warn("Option 'tig.%s': %s", name, option_errors[error]);
7415 static bool
7416 set_environment_variable(const char *name, const char *value)
7418 size_t len = strlen(name) + 1 + strlen(value) + 1;
7419 char *env = malloc(len);
7421 if (env &&
7422 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7423 putenv(env) == 0)
7424 return TRUE;
7425 free(env);
7426 return FALSE;
7429 static void
7430 set_work_tree(const char *value)
7432 char cwd[SIZEOF_STR];
7434 if (!getcwd(cwd, sizeof(cwd)))
7435 die("Failed to get cwd path: %s", strerror(errno));
7436 if (chdir(opt_git_dir) < 0)
7437 die("Failed to chdir(%s): %s", strerror(errno));
7438 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7439 die("Failed to get git path: %s", strerror(errno));
7440 if (chdir(cwd) < 0)
7441 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7442 if (chdir(value) < 0)
7443 die("Failed to chdir(%s): %s", value, strerror(errno));
7444 if (!getcwd(cwd, sizeof(cwd)))
7445 die("Failed to get cwd path: %s", strerror(errno));
7446 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7447 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7448 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7449 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7450 opt_is_inside_work_tree = TRUE;
7453 static void
7454 parse_git_color_option(enum line_type type, char *value)
7456 struct line_info *info = &line_info[type];
7457 const char *argv[SIZEOF_ARG];
7458 int argc = 0;
7459 bool first_color = TRUE;
7460 int i;
7462 if (!argv_from_string(argv, &argc, value))
7463 return;
7465 info->fg = COLOR_DEFAULT;
7466 info->bg = COLOR_DEFAULT;
7467 info->attr = 0;
7469 for (i = 0; i < argc; i++) {
7470 int attr = 0;
7472 if (set_attribute(&attr, argv[i])) {
7473 info->attr |= attr;
7475 } else if (set_color(&attr, argv[i])) {
7476 if (first_color)
7477 info->fg = attr;
7478 else
7479 info->bg = attr;
7480 first_color = FALSE;
7485 static void
7486 set_git_color_option(const char *name, char *value)
7488 static const struct enum_map color_option_map[] = {
7489 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7490 ENUM_MAP("branch.local", LINE_MAIN_REF),
7491 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7492 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7494 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7495 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7496 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7497 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7498 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7499 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7500 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7502 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7504 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7505 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7506 ENUM_MAP("status.added", LINE_STAT_STAGED),
7507 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7508 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7509 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7512 int type = LINE_NONE;
7514 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7515 parse_git_color_option(type, value);
7519 static int
7520 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7522 if (!strcmp(name, "gui.encoding"))
7523 parse_encoding(&opt_encoding, value, TRUE);
7525 else if (!strcmp(name, "core.editor"))
7526 string_ncopy(opt_editor, value, valuelen);
7528 else if (!strcmp(name, "core.worktree"))
7529 set_work_tree(value);
7531 else if (!prefixcmp(name, "tig.color."))
7532 set_repo_config_option(name + 10, value, option_color_command);
7534 else if (!prefixcmp(name, "tig.bind."))
7535 set_repo_config_option(name + 9, value, option_bind_command);
7537 else if (!prefixcmp(name, "tig."))
7538 set_repo_config_option(name + 4, value, option_set_command);
7540 else if (!prefixcmp(name, "color."))
7541 set_git_color_option(name + STRING_SIZE("color."), value);
7543 else if (*opt_head && !prefixcmp(name, "branch.") &&
7544 !strncmp(name + 7, opt_head, strlen(opt_head)))
7545 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7547 return OK;
7550 static int
7551 load_git_config(void)
7553 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7555 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7558 static int
7559 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7561 if (!opt_git_dir[0]) {
7562 string_ncopy(opt_git_dir, name, namelen);
7564 } else if (opt_is_inside_work_tree == -1) {
7565 /* This can be 3 different values depending on the
7566 * version of git being used. If git-rev-parse does not
7567 * understand --is-inside-work-tree it will simply echo
7568 * the option else either "true" or "false" is printed.
7569 * Default to true for the unknown case. */
7570 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7572 } else if (*name == '.') {
7573 string_ncopy(opt_cdup, name, namelen);
7575 } else {
7576 string_ncopy(opt_prefix, name, namelen);
7579 return OK;
7582 static int
7583 load_repo_info(void)
7585 const char *rev_parse_argv[] = {
7586 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7587 "--show-cdup", "--show-prefix", NULL
7590 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7595 * Main
7598 static const char usage[] =
7599 "tig " TIG_VERSION " (" __DATE__ ")\n"
7600 "\n"
7601 "Usage: tig [options] [revs] [--] [paths]\n"
7602 " or: tig show [options] [revs] [--] [paths]\n"
7603 " or: tig blame [options] [rev] [--] path\n"
7604 " or: tig status\n"
7605 " or: tig < [git command output]\n"
7606 "\n"
7607 "Options:\n"
7608 " +<number> Select line <number> in the first view\n"
7609 " -v, --version Show version and exit\n"
7610 " -h, --help Show help message and exit";
7612 static void __NORETURN
7613 quit(int sig)
7615 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7616 if (cursed)
7617 endwin();
7618 exit(0);
7621 static void __NORETURN
7622 die(const char *err, ...)
7624 va_list args;
7626 endwin();
7628 va_start(args, err);
7629 fputs("tig: ", stderr);
7630 vfprintf(stderr, err, args);
7631 fputs("\n", stderr);
7632 va_end(args);
7634 exit(1);
7637 static void
7638 warn(const char *msg, ...)
7640 va_list args;
7642 va_start(args, msg);
7643 fputs("tig warning: ", stderr);
7644 vfprintf(stderr, msg, args);
7645 fputs("\n", stderr);
7646 va_end(args);
7649 static int
7650 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7652 const char ***filter_args = data;
7654 return argv_append(filter_args, name) ? OK : ERR;
7657 static void
7658 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7660 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7661 const char **all_argv = NULL;
7663 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7664 !argv_append_array(&all_argv, argv) ||
7665 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7666 die("Failed to split arguments");
7667 argv_free(all_argv);
7668 free(all_argv);
7671 static void
7672 filter_options(const char *argv[], bool blame)
7674 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7676 if (blame)
7677 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7678 else
7679 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7681 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7684 static enum request
7685 parse_options(int argc, const char *argv[])
7687 enum request request = REQ_VIEW_MAIN;
7688 const char *subcommand;
7689 bool seen_dashdash = FALSE;
7690 const char **filter_argv = NULL;
7691 int i;
7693 if (!isatty(STDIN_FILENO))
7694 return REQ_VIEW_PAGER;
7696 if (argc <= 1)
7697 return REQ_VIEW_MAIN;
7699 subcommand = argv[1];
7700 if (!strcmp(subcommand, "status")) {
7701 if (argc > 2)
7702 warn("ignoring arguments after `%s'", subcommand);
7703 return REQ_VIEW_STATUS;
7705 } else if (!strcmp(subcommand, "blame")) {
7706 request = REQ_VIEW_BLAME;
7708 } else if (!strcmp(subcommand, "show")) {
7709 request = REQ_VIEW_DIFF;
7711 } else {
7712 subcommand = NULL;
7715 for (i = 1 + !!subcommand; i < argc; i++) {
7716 const char *opt = argv[i];
7718 // stop parsing our options after -- and let rev-parse handle the rest
7719 if (!seen_dashdash) {
7720 if (!strcmp(opt, "--")) {
7721 seen_dashdash = TRUE;
7722 continue;
7724 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7725 printf("tig version %s\n", TIG_VERSION);
7726 quit(0);
7728 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7729 printf("%s\n", usage);
7730 quit(0);
7732 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7733 opt_lineno = atoi(opt + 1);
7734 continue;
7739 if (!argv_append(&filter_argv, opt))
7740 die("command too long");
7743 if (filter_argv)
7744 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7746 /* Finish validating and setting up blame options */
7747 if (request == REQ_VIEW_BLAME) {
7748 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7749 die("invalid number of options to blame\n\n%s", usage);
7751 if (opt_rev_argv) {
7752 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7755 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7758 return request;
7762 main(int argc, const char *argv[])
7764 const char *codeset = ENCODING_UTF8;
7765 enum request request = parse_options(argc, argv);
7766 struct view *view;
7767 int i;
7769 signal(SIGINT, quit);
7770 signal(SIGPIPE, SIG_IGN);
7772 if (setlocale(LC_ALL, "")) {
7773 codeset = nl_langinfo(CODESET);
7776 foreach_view(view, i) {
7777 add_keymap(&view->ops->keymap);
7780 if (load_repo_info() == ERR)
7781 die("Failed to load repo info.");
7783 if (load_options() == ERR)
7784 die("Failed to load user config.");
7786 if (load_git_config() == ERR)
7787 die("Failed to load repo config.");
7789 /* Require a git repository unless when running in pager mode. */
7790 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7791 die("Not a git repository");
7793 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7794 char translit[SIZEOF_STR];
7796 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7797 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7798 else
7799 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7800 if (opt_iconv_out == ICONV_NONE)
7801 die("Failed to initialize character set conversion");
7804 if (load_refs() == ERR)
7805 die("Failed to load refs.");
7807 init_display();
7809 while (view_driver(display[current_view], request)) {
7810 int key = get_input(0);
7812 view = display[current_view];
7813 request = get_keybinding(&view->ops->keymap, key);
7815 /* Some low-level request handling. This keeps access to
7816 * status_win restricted. */
7817 switch (request) {
7818 case REQ_NONE:
7819 report("Unknown key, press %s for help",
7820 get_view_key(view, REQ_VIEW_HELP));
7821 break;
7822 case REQ_PROMPT:
7824 char *cmd = read_prompt(":");
7826 if (cmd && string_isnumber(cmd)) {
7827 int lineno = view->pos.lineno + 1;
7829 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7830 select_view_line(view, lineno - 1);
7831 report("");
7832 } else {
7833 report("Unable to parse '%s' as a line number", cmd);
7835 } else if (cmd && iscommit(cmd)) {
7836 string_ncopy(opt_search, cmd, strlen(cmd));
7838 request = view_request(view, REQ_JUMP_COMMIT);
7839 if (request == REQ_JUMP_COMMIT) {
7840 report("Jumping to commits is not supported by the '%s' view", view->name);
7843 } else if (cmd) {
7844 struct view *next = VIEW(REQ_VIEW_PAGER);
7845 const char *argv[SIZEOF_ARG] = { "git" };
7846 int argc = 1;
7848 /* When running random commands, initially show the
7849 * command in the title. However, it maybe later be
7850 * overwritten if a commit line is selected. */
7851 string_ncopy(next->ref, cmd, strlen(cmd));
7853 if (!argv_from_string(argv, &argc, cmd)) {
7854 report("Too many arguments");
7855 } else if (!format_argv(&next->argv, argv, FALSE)) {
7856 report("Argument formatting failed");
7857 } else {
7858 next->dir = NULL;
7859 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7863 request = REQ_NONE;
7864 break;
7866 case REQ_SEARCH:
7867 case REQ_SEARCH_BACK:
7869 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7870 char *search = read_prompt(prompt);
7872 if (search)
7873 string_ncopy(opt_search, search, strlen(search));
7874 else if (*opt_search)
7875 request = request == REQ_SEARCH ?
7876 REQ_FIND_NEXT :
7877 REQ_FIND_PREV;
7878 else
7879 request = REQ_NONE;
7880 break;
7882 default:
7883 break;
7887 quit(0);
7889 return 0;