[GH #62] Make the use of encoding arguments optional
[tig.git] / tig.c
blob01e471aa305dfe54caf9a0e72871689c5a34d9eb
1 /* Copyright (c) 2006-2012 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include "tig.h"
15 #include "io.h"
16 #include "refs.h"
17 #include "graph.h"
18 #include "git.h"
20 static void __NORETURN die(const char *err, ...) PRINTF_LIKE(1, 2);
21 static void warn(const char *msg, ...) PRINTF_LIKE(1, 2);
22 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
23 #define report_clear() report("%s", "")
26 enum input_status {
27 INPUT_OK,
28 INPUT_SKIP,
29 INPUT_STOP,
30 INPUT_CANCEL
33 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
35 static char *prompt_input(const char *prompt, input_handler handler, void *data);
36 static bool prompt_yesno(const char *prompt);
37 static char *read_prompt(const char *prompt);
39 struct menu_item {
40 int hotkey;
41 const char *text;
42 void *data;
45 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
47 #define GRAPHIC_ENUM(_) \
48 _(GRAPHIC, ASCII), \
49 _(GRAPHIC, DEFAULT), \
50 _(GRAPHIC, UTF_8)
52 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
54 #define DATE_ENUM(_) \
55 _(DATE, NO), \
56 _(DATE, DEFAULT), \
57 _(DATE, LOCAL), \
58 _(DATE, RELATIVE), \
59 _(DATE, SHORT)
61 DEFINE_ENUM(date, DATE_ENUM);
63 struct time {
64 time_t sec;
65 int tz;
68 static inline int timecmp(const struct time *t1, const struct time *t2)
70 return t1->sec - t2->sec;
73 static const char *
74 mkdate(const struct time *time, enum date date)
76 static char buf[DATE_WIDTH + 1];
77 static const struct enum_map reldate[] = {
78 { "second", 1, 60 * 2 },
79 { "minute", 60, 60 * 60 * 2 },
80 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
81 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
82 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
83 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
84 { "year", 60 * 60 * 24 * 365, 0 },
86 struct tm tm;
88 if (!date || !time || !time->sec)
89 return "";
91 if (date == DATE_RELATIVE) {
92 struct timeval now;
93 time_t date = time->sec + time->tz;
94 time_t seconds;
95 int i;
97 gettimeofday(&now, NULL);
98 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
99 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
100 if (seconds >= reldate[i].value && reldate[i].value)
101 continue;
103 seconds /= reldate[i].namelen;
104 if (!string_format(buf, "%ld %s%s %s",
105 seconds, reldate[i].name,
106 seconds > 1 ? "s" : "",
107 now.tv_sec >= date ? "ago" : "ahead"))
108 break;
109 return buf;
113 if (date == DATE_LOCAL) {
114 time_t date = time->sec + time->tz;
115 localtime_r(&date, &tm);
117 else {
118 gmtime_r(&time->sec, &tm);
120 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define AUTHOR_ENUM(_) \
125 _(AUTHOR, NO), \
126 _(AUTHOR, FULL), \
127 _(AUTHOR, ABBREVIATED)
129 DEFINE_ENUM(author, AUTHOR_ENUM);
131 static const char *
132 get_author_initials(const char *author)
134 static char initials[AUTHOR_WIDTH * 6 + 1];
135 size_t pos = 0;
136 const char *end = strchr(author, '\0');
138 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
140 memset(initials, 0, sizeof(initials));
141 while (author < end) {
142 unsigned char bytes;
143 size_t i;
145 while (author < end && is_initial_sep(*author))
146 author++;
148 bytes = utf8_char_length(author, end);
149 if (bytes >= sizeof(initials) - 1 - pos)
150 break;
151 while (bytes--) {
152 initials[pos++] = *author++;
155 i = pos;
156 while (author < end && !is_initial_sep(*author)) {
157 bytes = utf8_char_length(author, end);
158 if (bytes >= sizeof(initials) - 1 - i) {
159 while (author < end && !is_initial_sep(*author))
160 author++;
161 break;
163 while (bytes--) {
164 initials[i++] = *author++;
168 initials[i++] = 0;
171 return initials;
174 #define author_trim(cols) (cols == 0 || cols > 10)
176 static const char *
177 mkauthor(const char *text, int cols, enum author author)
179 bool trim = author_trim(cols);
180 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
182 if (author == AUTHOR_NO)
183 return "";
184 if (abbreviate && text)
185 return get_author_initials(text);
186 return text;
189 static const char *
190 mkmode(mode_t mode)
192 if (S_ISDIR(mode))
193 return "drwxr-xr-x";
194 else if (S_ISLNK(mode))
195 return "lrwxrwxrwx";
196 else if (S_ISGITLINK(mode))
197 return "m---------";
198 else if (S_ISREG(mode) && mode & S_IXUSR)
199 return "-rwxr-xr-x";
200 else if (S_ISREG(mode))
201 return "-rw-r--r--";
202 else
203 return "----------";
206 #define FILENAME_ENUM(_) \
207 _(FILENAME, NO), \
208 _(FILENAME, ALWAYS), \
209 _(FILENAME, AUTO)
211 DEFINE_ENUM(filename, FILENAME_ENUM);
213 #define IGNORE_SPACE_ENUM(_) \
214 _(IGNORE_SPACE, NO), \
215 _(IGNORE_SPACE, ALL), \
216 _(IGNORE_SPACE, SOME), \
217 _(IGNORE_SPACE, AT_EOL)
219 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
221 #define COMMIT_ORDER_ENUM(_) \
222 _(COMMIT_ORDER, DEFAULT), \
223 _(COMMIT_ORDER, TOPO), \
224 _(COMMIT_ORDER, DATE), \
225 _(COMMIT_ORDER, REVERSE)
227 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
229 #define VIEW_INFO(_) \
230 _(MAIN, main, ref_head), \
231 _(DIFF, diff, ref_commit), \
232 _(LOG, log, ref_head), \
233 _(TREE, tree, ref_commit), \
234 _(BLOB, blob, ref_blob), \
235 _(BLAME, blame, ref_commit), \
236 _(BRANCH, branch, ref_head), \
237 _(HELP, help, ""), \
238 _(PAGER, pager, ""), \
239 _(STATUS, status, "status"), \
240 _(STAGE, stage, "stage")
242 static struct encoding *
243 get_path_encoding(const char *path, struct encoding *default_encoding)
245 const char *check_attr_argv[] = {
246 "git", "check-attr", "encoding", "--", path, NULL
248 char buf[SIZEOF_STR];
249 char *encoding;
251 /* <path>: encoding: <encoding> */
253 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
254 || !(encoding = strstr(buf, ENCODING_SEP)))
255 return default_encoding;
257 encoding += STRING_SIZE(ENCODING_SEP);
258 if (!strcmp(encoding, ENCODING_UTF8)
259 || !strcmp(encoding, "unspecified")
260 || !strcmp(encoding, "set"))
261 return default_encoding;
263 return encoding_open(encoding);
267 * User requests
270 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
272 #define REQ_INFO \
273 REQ_GROUP("View switching") \
274 VIEW_INFO(VIEW_REQ), \
276 REQ_GROUP("View manipulation") \
277 REQ_(ENTER, "Enter current line and scroll"), \
278 REQ_(NEXT, "Move to next"), \
279 REQ_(PREVIOUS, "Move to previous"), \
280 REQ_(PARENT, "Move to parent"), \
281 REQ_(VIEW_NEXT, "Move focus to next view"), \
282 REQ_(REFRESH, "Reload and refresh"), \
283 REQ_(MAXIMIZE, "Maximize the current view"), \
284 REQ_(VIEW_CLOSE, "Close the current view"), \
285 REQ_(QUIT, "Close all views and quit"), \
287 REQ_GROUP("View specific requests") \
288 REQ_(STATUS_UPDATE, "Update file status"), \
289 REQ_(STATUS_REVERT, "Revert file changes"), \
290 REQ_(STATUS_MERGE, "Merge file using external tool"), \
291 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
292 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
293 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
294 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
296 REQ_GROUP("Cursor navigation") \
297 REQ_(MOVE_UP, "Move cursor one line up"), \
298 REQ_(MOVE_DOWN, "Move cursor one line down"), \
299 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
300 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
301 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
302 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
304 REQ_GROUP("Scrolling") \
305 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
306 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
307 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
308 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
309 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
310 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
311 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
313 REQ_GROUP("Searching") \
314 REQ_(SEARCH, "Search the view"), \
315 REQ_(SEARCH_BACK, "Search backwards in the view"), \
316 REQ_(FIND_NEXT, "Find next search match"), \
317 REQ_(FIND_PREV, "Find previous search match"), \
319 REQ_GROUP("Option manipulation") \
320 REQ_(OPTIONS, "Open option menu"), \
321 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
322 REQ_(TOGGLE_DATE, "Toggle date display"), \
323 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
324 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
325 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
326 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
327 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
328 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
329 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
330 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
331 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
332 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
333 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
335 REQ_GROUP("Misc") \
336 REQ_(PROMPT, "Bring up the prompt"), \
337 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
338 REQ_(SHOW_VERSION, "Show version information"), \
339 REQ_(STOP_LOADING, "Stop all loading views"), \
340 REQ_(EDIT, "Open in editor"), \
341 REQ_(NONE, "Do nothing")
344 /* User action requests. */
345 enum request {
346 #define REQ_GROUP(help)
347 #define REQ_(req, help) REQ_##req
349 /* Offset all requests to avoid conflicts with ncurses getch values. */
350 REQ_UNKNOWN = KEY_MAX + 1,
351 REQ_OFFSET,
352 REQ_INFO,
354 /* Internal requests. */
355 REQ_JUMP_COMMIT,
357 #undef REQ_GROUP
358 #undef REQ_
361 struct request_info {
362 enum request request;
363 const char *name;
364 int namelen;
365 const char *help;
368 static const struct request_info req_info[] = {
369 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
370 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
371 REQ_INFO
372 #undef REQ_GROUP
373 #undef REQ_
376 static enum request
377 get_request(const char *name)
379 int namelen = strlen(name);
380 int i;
382 for (i = 0; i < ARRAY_SIZE(req_info); i++)
383 if (enum_equals(req_info[i], name, namelen))
384 return req_info[i].request;
386 return REQ_UNKNOWN;
391 * Options
394 /* Option and state variables. */
395 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
396 static enum date opt_date = DATE_DEFAULT;
397 static enum author opt_author = AUTHOR_FULL;
398 static enum filename opt_filename = FILENAME_AUTO;
399 static bool opt_rev_graph = TRUE;
400 static bool opt_line_number = FALSE;
401 static bool opt_show_refs = TRUE;
402 static bool opt_show_changes = TRUE;
403 static bool opt_untracked_dirs_content = TRUE;
404 static bool opt_read_git_colors = TRUE;
405 static bool opt_wrap_lines = FALSE;
406 static bool opt_ignore_case = FALSE;
407 static int opt_diff_context = 3;
408 static char opt_diff_context_arg[9] = "";
409 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
410 static char opt_ignore_space_arg[22] = "";
411 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
412 static char opt_commit_order_arg[22] = "";
413 static bool opt_notes = TRUE;
414 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
415 static int opt_num_interval = 5;
416 static double opt_hscroll = 0.50;
417 static double opt_scale_split_view = 2.0 / 3.0;
418 static double opt_scale_vsplit_view = 0.5;
419 static bool opt_vsplit = FALSE;
420 static int opt_tab_size = 8;
421 static int opt_author_width = AUTHOR_WIDTH;
422 static int opt_filename_width = FILENAME_WIDTH;
423 static char opt_path[SIZEOF_STR] = "";
424 static char opt_file[SIZEOF_STR] = "";
425 static char opt_ref[SIZEOF_REF] = "";
426 static unsigned long opt_goto_line = 0;
427 static char opt_head[SIZEOF_REF] = "";
428 static char opt_remote[SIZEOF_REF] = "";
429 static struct encoding *opt_encoding = NULL;
430 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
431 static iconv_t opt_iconv_out = ICONV_NONE;
432 static char opt_search[SIZEOF_STR] = "";
433 static char opt_cdup[SIZEOF_STR] = "";
434 static char opt_prefix[SIZEOF_STR] = "";
435 static char opt_git_dir[SIZEOF_STR] = "";
436 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
437 static char opt_editor[SIZEOF_STR] = "";
438 static FILE *opt_tty = NULL;
439 static const char **opt_diff_argv = NULL;
440 static const char **opt_rev_argv = NULL;
441 static const char **opt_file_argv = NULL;
442 static const char **opt_blame_argv = NULL;
443 static int opt_lineno = 0;
444 static bool opt_show_id = FALSE;
445 static int opt_id_cols = ID_WIDTH;
447 #define is_initial_commit() (!get_ref_head())
448 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
449 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
451 static inline void
452 update_diff_context_arg(int diff_context)
454 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
455 string_ncopy(opt_diff_context_arg, "-U3", 3);
458 static inline void
459 update_ignore_space_arg()
461 if (opt_ignore_space == IGNORE_SPACE_ALL) {
462 string_copy(opt_ignore_space_arg, "--ignore-all-space");
463 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
464 string_copy(opt_ignore_space_arg, "--ignore-space-change");
465 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
466 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
467 } else {
468 string_copy(opt_ignore_space_arg, "");
472 static inline void
473 update_commit_order_arg()
475 if (opt_commit_order == COMMIT_ORDER_TOPO) {
476 string_copy(opt_commit_order_arg, "--topo-order");
477 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
478 string_copy(opt_commit_order_arg, "--date-order");
479 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
480 string_copy(opt_commit_order_arg, "--reverse");
481 } else {
482 string_copy(opt_commit_order_arg, "");
486 static inline void
487 update_notes_arg()
489 if (opt_notes) {
490 string_copy(opt_notes_arg, "--show-notes");
491 } else {
492 /* Notes are disabled by default when passing --pretty args. */
493 string_copy(opt_notes_arg, "");
498 * Line-oriented content detection.
501 #define LINE_INFO \
502 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
504 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
505 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
506 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
507 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
508 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
509 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
510 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
511 LINE(DIFF_DELETED_FILE_MODE, \
512 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
515 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
517 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
518 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
519 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
520 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
521 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
522 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
523 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
527 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
528 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
529 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
530 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
531 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
532 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
533 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
534 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
537 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
538 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
539 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
540 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
541 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
542 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
543 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
544 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
545 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
546 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
547 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
548 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
549 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
550 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
551 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
552 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
553 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
554 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
555 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
556 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
557 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
558 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
559 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
560 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
561 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
562 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
563 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
564 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
565 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
566 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
567 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
568 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
569 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
570 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
571 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
572 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
573 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
574 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
575 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
577 enum line_type {
578 #define LINE(type, line, fg, bg, attr) \
579 LINE_##type
580 LINE_INFO,
581 LINE_NONE
582 #undef LINE
585 struct line_info {
586 const char *name; /* Option name. */
587 int namelen; /* Size of option name. */
588 const char *line; /* The start of line to match. */
589 int linelen; /* Size of string to match. */
590 int fg, bg, attr; /* Color and text attributes for the lines. */
591 int color_pair;
594 static struct line_info line_info[] = {
595 #define LINE(type, line, fg, bg, attr) \
596 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
597 LINE_INFO
598 #undef LINE
601 static struct line_info **color_pair;
602 static size_t color_pairs;
604 static struct line_info *custom_color;
605 static size_t custom_colors;
607 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
608 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
610 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
611 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
613 /* Color IDs must be 1 or higher. [GH #15] */
614 #define COLOR_ID(line_type) ((line_type) + 1)
616 static enum line_type
617 get_line_type(const char *line)
619 int linelen = strlen(line);
620 enum line_type type;
622 for (type = 0; type < custom_colors; type++)
623 /* Case insensitive search matches Signed-off-by lines better. */
624 if (linelen >= custom_color[type].linelen &&
625 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
626 return TO_CUSTOM_COLOR_TYPE(type);
628 for (type = 0; type < ARRAY_SIZE(line_info); type++)
629 /* Case insensitive search matches Signed-off-by lines better. */
630 if (linelen >= line_info[type].linelen &&
631 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
632 return type;
634 return LINE_DEFAULT;
637 static enum line_type
638 get_line_type_from_ref(const struct ref *ref)
640 if (ref->head)
641 return LINE_MAIN_HEAD;
642 else if (ref->ltag)
643 return LINE_MAIN_LOCAL_TAG;
644 else if (ref->tag)
645 return LINE_MAIN_TAG;
646 else if (ref->tracked)
647 return LINE_MAIN_TRACKED;
648 else if (ref->remote)
649 return LINE_MAIN_REMOTE;
650 else if (ref->replace)
651 return LINE_MAIN_REPLACE;
653 return LINE_MAIN_REF;
656 static inline struct line_info *
657 get_line(enum line_type type)
659 if (type > LINE_NONE) {
660 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
661 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
662 } else {
663 assert(type < ARRAY_SIZE(line_info));
664 return &line_info[type];
668 static inline int
669 get_line_color(enum line_type type)
671 return COLOR_ID(get_line(type)->color_pair);
674 static inline int
675 get_line_attr(enum line_type type)
677 struct line_info *info = get_line(type);
679 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
682 static struct line_info *
683 get_line_info(const char *name)
685 size_t namelen = strlen(name);
686 enum line_type type;
688 for (type = 0; type < ARRAY_SIZE(line_info); type++)
689 if (enum_equals(line_info[type], name, namelen))
690 return &line_info[type];
692 return NULL;
695 static struct line_info *
696 add_custom_color(const char *quoted_line)
698 struct line_info *info;
699 char *line;
700 size_t linelen;
702 if (!realloc_custom_color(&custom_color, custom_colors, 1))
703 die("Failed to alloc custom line info");
705 linelen = strlen(quoted_line) - 1;
706 line = malloc(linelen);
707 if (!line)
708 return NULL;
710 strncpy(line, quoted_line + 1, linelen);
711 line[linelen - 1] = 0;
713 info = &custom_color[custom_colors++];
714 info->name = info->line = line;
715 info->namelen = info->linelen = strlen(line);
717 return info;
720 static void
721 init_line_info_color_pair(struct line_info *info, enum line_type type,
722 int default_bg, int default_fg)
724 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
725 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
726 int i;
728 for (i = 0; i < color_pairs; i++) {
729 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
730 info->color_pair = i;
731 return;
735 if (!realloc_color_pair(&color_pair, color_pairs, 1))
736 die("Failed to alloc color pair");
738 color_pair[color_pairs] = info;
739 info->color_pair = color_pairs++;
740 init_pair(COLOR_ID(info->color_pair), fg, bg);
743 static void
744 init_colors(void)
746 int default_bg = line_info[LINE_DEFAULT].bg;
747 int default_fg = line_info[LINE_DEFAULT].fg;
748 enum line_type type;
750 start_color();
752 if (assume_default_colors(default_fg, default_bg) == ERR) {
753 default_bg = COLOR_BLACK;
754 default_fg = COLOR_WHITE;
757 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
758 struct line_info *info = &line_info[type];
760 init_line_info_color_pair(info, type, default_bg, default_fg);
763 for (type = 0; type < custom_colors; type++) {
764 struct line_info *info = &custom_color[type];
766 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
767 default_bg, default_fg);
771 struct line {
772 enum line_type type;
773 unsigned int lineno:24;
775 /* State flags */
776 unsigned int selected:1;
777 unsigned int dirty:1;
778 unsigned int cleareol:1;
779 unsigned int dont_free:1;
780 unsigned int wrapped:1;
782 void *data; /* User data */
787 * Keys
790 struct keybinding {
791 int alias;
792 enum request request;
795 static struct keybinding default_keybindings[] = {
796 /* View switching */
797 { 'm', REQ_VIEW_MAIN },
798 { 'd', REQ_VIEW_DIFF },
799 { 'l', REQ_VIEW_LOG },
800 { 't', REQ_VIEW_TREE },
801 { 'f', REQ_VIEW_BLOB },
802 { 'B', REQ_VIEW_BLAME },
803 { 'H', REQ_VIEW_BRANCH },
804 { 'p', REQ_VIEW_PAGER },
805 { 'h', REQ_VIEW_HELP },
806 { 'S', REQ_VIEW_STATUS },
807 { 'c', REQ_VIEW_STAGE },
809 /* View manipulation */
810 { 'q', REQ_VIEW_CLOSE },
811 { KEY_TAB, REQ_VIEW_NEXT },
812 { KEY_RETURN, REQ_ENTER },
813 { KEY_UP, REQ_PREVIOUS },
814 { KEY_CTL('P'), REQ_PREVIOUS },
815 { KEY_DOWN, REQ_NEXT },
816 { KEY_CTL('N'), REQ_NEXT },
817 { 'R', REQ_REFRESH },
818 { KEY_F(5), REQ_REFRESH },
819 { 'O', REQ_MAXIMIZE },
820 { ',', REQ_PARENT },
822 /* View specific */
823 { 'u', REQ_STATUS_UPDATE },
824 { '!', REQ_STATUS_REVERT },
825 { 'M', REQ_STATUS_MERGE },
826 { '1', REQ_STAGE_UPDATE_LINE },
827 { '@', REQ_STAGE_NEXT },
828 { '[', REQ_DIFF_CONTEXT_DOWN },
829 { ']', REQ_DIFF_CONTEXT_UP },
831 /* Cursor navigation */
832 { 'k', REQ_MOVE_UP },
833 { 'j', REQ_MOVE_DOWN },
834 { KEY_HOME, REQ_MOVE_FIRST_LINE },
835 { KEY_END, REQ_MOVE_LAST_LINE },
836 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
837 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
838 { ' ', REQ_MOVE_PAGE_DOWN },
839 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
840 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
841 { 'b', REQ_MOVE_PAGE_UP },
842 { '-', REQ_MOVE_PAGE_UP },
844 /* Scrolling */
845 { '|', REQ_SCROLL_FIRST_COL },
846 { KEY_LEFT, REQ_SCROLL_LEFT },
847 { KEY_RIGHT, REQ_SCROLL_RIGHT },
848 { KEY_IC, REQ_SCROLL_LINE_UP },
849 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
850 { KEY_DC, REQ_SCROLL_LINE_DOWN },
851 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
852 { 'w', REQ_SCROLL_PAGE_UP },
853 { 's', REQ_SCROLL_PAGE_DOWN },
855 /* Searching */
856 { '/', REQ_SEARCH },
857 { '?', REQ_SEARCH_BACK },
858 { 'n', REQ_FIND_NEXT },
859 { 'N', REQ_FIND_PREV },
861 /* Misc */
862 { 'Q', REQ_QUIT },
863 { 'z', REQ_STOP_LOADING },
864 { 'v', REQ_SHOW_VERSION },
865 { 'r', REQ_SCREEN_REDRAW },
866 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
867 { 'o', REQ_OPTIONS },
868 { '.', REQ_TOGGLE_LINENO },
869 { 'D', REQ_TOGGLE_DATE },
870 { 'A', REQ_TOGGLE_AUTHOR },
871 { 'g', REQ_TOGGLE_REV_GRAPH },
872 { '~', REQ_TOGGLE_GRAPHIC },
873 { '#', REQ_TOGGLE_FILENAME },
874 { 'F', REQ_TOGGLE_REFS },
875 { 'I', REQ_TOGGLE_SORT_ORDER },
876 { 'i', REQ_TOGGLE_SORT_FIELD },
877 { 'W', REQ_TOGGLE_IGNORE_SPACE },
878 { 'X', REQ_TOGGLE_ID },
879 { ':', REQ_PROMPT },
880 { 'e', REQ_EDIT },
883 struct keymap {
884 const char *name;
885 struct keymap *next;
886 struct keybinding *data;
887 size_t size;
888 bool hidden;
891 static struct keymap generic_keymap = { "generic" };
892 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
894 static struct keymap *keymaps = &generic_keymap;
896 static void
897 add_keymap(struct keymap *keymap)
899 keymap->next = keymaps;
900 keymaps = keymap;
903 static struct keymap *
904 get_keymap(const char *name)
906 struct keymap *keymap = keymaps;
908 while (keymap) {
909 if (!strcasecmp(keymap->name, name))
910 return keymap;
911 keymap = keymap->next;
914 return NULL;
918 static void
919 add_keybinding(struct keymap *table, enum request request, int key)
921 size_t i;
923 for (i = 0; i < table->size; i++) {
924 if (table->data[i].alias == key) {
925 table->data[i].request = request;
926 return;
930 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
931 if (!table->data)
932 die("Failed to allocate keybinding");
933 table->data[table->size].alias = key;
934 table->data[table->size++].request = request;
936 if (request == REQ_NONE && is_generic_keymap(table)) {
937 int i;
939 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
940 if (default_keybindings[i].alias == key)
941 default_keybindings[i].request = REQ_NONE;
945 /* Looks for a key binding first in the given map, then in the generic map, and
946 * lastly in the default keybindings. */
947 static enum request
948 get_keybinding(struct keymap *keymap, int key)
950 size_t i;
952 for (i = 0; i < keymap->size; i++)
953 if (keymap->data[i].alias == key)
954 return keymap->data[i].request;
956 for (i = 0; i < generic_keymap.size; i++)
957 if (generic_keymap.data[i].alias == key)
958 return generic_keymap.data[i].request;
960 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
961 if (default_keybindings[i].alias == key)
962 return default_keybindings[i].request;
964 return (enum request) key;
968 struct key {
969 const char *name;
970 int value;
973 static const struct key key_table[] = {
974 { "Enter", KEY_RETURN },
975 { "Space", ' ' },
976 { "Backspace", KEY_BACKSPACE },
977 { "Tab", KEY_TAB },
978 { "Escape", KEY_ESC },
979 { "Left", KEY_LEFT },
980 { "Right", KEY_RIGHT },
981 { "Up", KEY_UP },
982 { "Down", KEY_DOWN },
983 { "Insert", KEY_IC },
984 { "Delete", KEY_DC },
985 { "Hash", '#' },
986 { "Home", KEY_HOME },
987 { "End", KEY_END },
988 { "PageUp", KEY_PPAGE },
989 { "PageDown", KEY_NPAGE },
990 { "F1", KEY_F(1) },
991 { "F2", KEY_F(2) },
992 { "F3", KEY_F(3) },
993 { "F4", KEY_F(4) },
994 { "F5", KEY_F(5) },
995 { "F6", KEY_F(6) },
996 { "F7", KEY_F(7) },
997 { "F8", KEY_F(8) },
998 { "F9", KEY_F(9) },
999 { "F10", KEY_F(10) },
1000 { "F11", KEY_F(11) },
1001 { "F12", KEY_F(12) },
1004 static int
1005 get_key_value(const char *name)
1007 int i;
1009 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1010 if (!strcasecmp(key_table[i].name, name))
1011 return key_table[i].value;
1013 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1014 return (int)name[1] & 0x1f;
1015 if (strlen(name) == 1 && isprint(*name))
1016 return (int) *name;
1017 return ERR;
1020 static const char *
1021 get_key_name(int key_value)
1023 static char key_char[] = "'X'\0";
1024 const char *seq = NULL;
1025 int key;
1027 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1028 if (key_table[key].value == key_value)
1029 seq = key_table[key].name;
1031 if (seq == NULL && key_value < 0x7f) {
1032 char *s = key_char + 1;
1034 if (key_value >= 0x20) {
1035 *s++ = key_value;
1036 } else {
1037 *s++ = '^';
1038 *s++ = 0x40 | (key_value & 0x1f);
1040 *s++ = '\'';
1041 *s++ = '\0';
1042 seq = key_char;
1045 return seq ? seq : "(no key)";
1048 static bool
1049 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1051 const char *sep = *pos > 0 ? ", " : "";
1052 const char *keyname = get_key_name(keybinding->alias);
1054 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1057 static bool
1058 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1059 struct keymap *keymap, bool all)
1061 int i;
1063 for (i = 0; i < keymap->size; i++) {
1064 if (keymap->data[i].request == request) {
1065 if (!append_key(buf, pos, &keymap->data[i]))
1066 return FALSE;
1067 if (!all)
1068 break;
1072 return TRUE;
1075 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1077 static const char *
1078 get_keys(struct keymap *keymap, enum request request, bool all)
1080 static char buf[BUFSIZ];
1081 size_t pos = 0;
1082 int i;
1084 buf[pos] = 0;
1086 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1087 return "Too many keybindings!";
1088 if (pos > 0 && !all)
1089 return buf;
1091 if (!is_generic_keymap(keymap)) {
1092 /* Only the generic keymap includes the default keybindings when
1093 * listing all keys. */
1094 if (all)
1095 return buf;
1097 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1098 return "Too many keybindings!";
1099 if (pos)
1100 return buf;
1103 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1104 if (default_keybindings[i].request == request) {
1105 if (!append_key(buf, &pos, &default_keybindings[i]))
1106 return "Too many keybindings!";
1107 if (!all)
1108 return buf;
1112 return buf;
1115 enum run_request_flag {
1116 RUN_REQUEST_DEFAULT = 0,
1117 RUN_REQUEST_FORCE = 1,
1118 RUN_REQUEST_SILENT = 2,
1119 RUN_REQUEST_CONFIRM = 4,
1120 RUN_REQUEST_EXIT = 8,
1123 struct run_request {
1124 struct keymap *keymap;
1125 int key;
1126 const char **argv;
1127 bool silent;
1128 bool confirm;
1129 bool exit;
1132 static struct run_request *run_request;
1133 static size_t run_requests;
1135 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1137 static bool
1138 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1140 bool force = flags & RUN_REQUEST_FORCE;
1141 struct run_request *req;
1143 if (!force && get_keybinding(keymap, key) != key)
1144 return TRUE;
1146 if (!realloc_run_requests(&run_request, run_requests, 1))
1147 return FALSE;
1149 if (!argv_copy(&run_request[run_requests].argv, argv))
1150 return FALSE;
1152 req = &run_request[run_requests++];
1153 req->silent = flags & RUN_REQUEST_SILENT;
1154 req->confirm = flags & RUN_REQUEST_CONFIRM;
1155 req->exit = flags & RUN_REQUEST_EXIT;
1156 req->keymap = keymap;
1157 req->key = key;
1159 add_keybinding(keymap, REQ_NONE + run_requests, key);
1160 return TRUE;
1163 static struct run_request *
1164 get_run_request(enum request request)
1166 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1167 return NULL;
1168 return &run_request[request - REQ_NONE - 1];
1171 static void
1172 add_builtin_run_requests(void)
1174 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1175 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1176 const char *commit[] = { "git", "commit", NULL };
1177 const char *gc[] = { "git", "gc", NULL };
1179 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1180 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1181 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1182 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1186 * User config file handling.
1189 #define OPT_ERR_INFO \
1190 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1191 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1192 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1193 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1194 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1195 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1196 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1197 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1198 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1199 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1200 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1201 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1202 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1203 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1204 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1205 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1206 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1207 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1209 enum option_code {
1210 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1211 OPT_ERR_INFO
1212 #undef OPT_ERR_
1213 OPT_OK
1216 static const char *option_errors[] = {
1217 #define OPT_ERR_(name, msg) msg
1218 OPT_ERR_INFO
1219 #undef OPT_ERR_
1222 static const struct enum_map color_map[] = {
1223 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1224 COLOR_MAP(DEFAULT),
1225 COLOR_MAP(BLACK),
1226 COLOR_MAP(BLUE),
1227 COLOR_MAP(CYAN),
1228 COLOR_MAP(GREEN),
1229 COLOR_MAP(MAGENTA),
1230 COLOR_MAP(RED),
1231 COLOR_MAP(WHITE),
1232 COLOR_MAP(YELLOW),
1235 static const struct enum_map attr_map[] = {
1236 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1237 ATTR_MAP(NORMAL),
1238 ATTR_MAP(BLINK),
1239 ATTR_MAP(BOLD),
1240 ATTR_MAP(DIM),
1241 ATTR_MAP(REVERSE),
1242 ATTR_MAP(STANDOUT),
1243 ATTR_MAP(UNDERLINE),
1246 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1248 static enum option_code
1249 parse_step(double *opt, const char *arg)
1251 *opt = atoi(arg);
1252 if (!strchr(arg, '%'))
1253 return OPT_OK;
1255 /* "Shift down" so 100% and 1 does not conflict. */
1256 *opt = (*opt - 1) / 100;
1257 if (*opt >= 1.0) {
1258 *opt = 0.99;
1259 return OPT_ERR_INVALID_STEP_VALUE;
1261 if (*opt < 0.0) {
1262 *opt = 1;
1263 return OPT_ERR_INVALID_STEP_VALUE;
1265 return OPT_OK;
1268 static enum option_code
1269 parse_int(int *opt, const char *arg, int min, int max)
1271 int value = atoi(arg);
1273 if (min <= value && value <= max) {
1274 *opt = value;
1275 return OPT_OK;
1278 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1281 #define parse_id(opt, arg) \
1282 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1284 static bool
1285 set_color(int *color, const char *name)
1287 if (map_enum(color, color_map, name))
1288 return TRUE;
1289 if (!prefixcmp(name, "color"))
1290 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1291 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1292 return parse_int(color, name, 0, 255) == OPT_OK;
1295 /* Wants: object fgcolor bgcolor [attribute] */
1296 static enum option_code
1297 option_color_command(int argc, const char *argv[])
1299 struct line_info *info;
1301 if (argc < 3)
1302 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1304 if (*argv[0] == '"' || *argv[0] == '\'') {
1305 info = add_custom_color(argv[0]);
1306 } else {
1307 info = get_line_info(argv[0]);
1309 if (!info) {
1310 static const struct enum_map obsolete[] = {
1311 ENUM_MAP("main-delim", LINE_DELIMITER),
1312 ENUM_MAP("main-date", LINE_DATE),
1313 ENUM_MAP("main-author", LINE_AUTHOR),
1314 ENUM_MAP("blame-id", LINE_ID),
1316 int index;
1318 if (!map_enum(&index, obsolete, argv[0]))
1319 return OPT_ERR_UNKNOWN_COLOR_NAME;
1320 info = &line_info[index];
1323 if (!set_color(&info->fg, argv[1]) ||
1324 !set_color(&info->bg, argv[2]))
1325 return OPT_ERR_UNKNOWN_COLOR;
1327 info->attr = 0;
1328 while (argc-- > 3) {
1329 int attr;
1331 if (!set_attribute(&attr, argv[argc]))
1332 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1333 info->attr |= attr;
1336 return OPT_OK;
1339 static enum option_code
1340 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1342 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1343 ? TRUE : FALSE;
1344 if (matched)
1345 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1346 return OPT_OK;
1349 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1351 static enum option_code
1352 parse_enum_do(unsigned int *opt, const char *arg,
1353 const struct enum_map *map, size_t map_size)
1355 bool is_true;
1357 assert(map_size > 1);
1359 if (map_enum_do(map, map_size, (int *) opt, arg))
1360 return OPT_OK;
1362 parse_bool(&is_true, arg);
1363 *opt = is_true ? map[1].value : map[0].value;
1364 return OPT_OK;
1367 #define parse_enum(opt, arg, map) \
1368 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1370 static enum option_code
1371 parse_string(char *opt, const char *arg, size_t optsize)
1373 int arglen = strlen(arg);
1375 switch (arg[0]) {
1376 case '\"':
1377 case '\'':
1378 if (arglen == 1 || arg[arglen - 1] != arg[0])
1379 return OPT_ERR_UNMATCHED_QUOTATION;
1380 arg += 1; arglen -= 2;
1381 default:
1382 string_ncopy_do(opt, optsize, arg, arglen);
1383 return OPT_OK;
1387 static enum option_code
1388 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1390 char buf[SIZEOF_STR];
1391 enum option_code code = parse_string(buf, arg, sizeof(buf));
1393 if (code == OPT_OK) {
1394 struct encoding *encoding = *encoding_ref;
1396 if (encoding && !priority)
1397 return code;
1398 encoding = encoding_open(buf);
1399 if (encoding)
1400 *encoding_ref = encoding;
1403 return code;
1406 static enum option_code
1407 parse_args(const char ***args, const char *argv[])
1409 if (*args == NULL && !argv_copy(args, argv))
1410 return OPT_ERR_OUT_OF_MEMORY;
1411 return OPT_OK;
1414 /* Wants: name = value */
1415 static enum option_code
1416 option_set_command(int argc, const char *argv[])
1418 if (argc < 3)
1419 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1421 if (strcmp(argv[1], "="))
1422 return OPT_ERR_NO_VALUE_ASSIGNED;
1424 if (!strcmp(argv[0], "blame-options"))
1425 return parse_args(&opt_blame_argv, argv + 2);
1427 if (argc != 3)
1428 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1430 if (!strcmp(argv[0], "show-author"))
1431 return parse_enum(&opt_author, argv[2], author_map);
1433 if (!strcmp(argv[0], "show-date"))
1434 return parse_enum(&opt_date, argv[2], date_map);
1436 if (!strcmp(argv[0], "show-rev-graph"))
1437 return parse_bool(&opt_rev_graph, argv[2]);
1439 if (!strcmp(argv[0], "show-refs"))
1440 return parse_bool(&opt_show_refs, argv[2]);
1442 if (!strcmp(argv[0], "show-changes"))
1443 return parse_bool(&opt_show_changes, argv[2]);
1445 if (!strcmp(argv[0], "show-notes")) {
1446 bool matched = FALSE;
1447 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1449 if (res == OPT_OK && matched) {
1450 update_notes_arg();
1451 return res;
1454 opt_notes = TRUE;
1455 strcpy(opt_notes_arg, "--show-notes=");
1456 res = parse_string(opt_notes_arg + 8, argv[2],
1457 sizeof(opt_notes_arg) - 8);
1458 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1459 opt_notes_arg[7] = '\0';
1460 return res;
1463 if (!strcmp(argv[0], "show-line-numbers"))
1464 return parse_bool(&opt_line_number, argv[2]);
1466 if (!strcmp(argv[0], "line-graphics"))
1467 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1469 if (!strcmp(argv[0], "line-number-interval"))
1470 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1472 if (!strcmp(argv[0], "author-width"))
1473 return parse_int(&opt_author_width, argv[2], 0, 1024);
1475 if (!strcmp(argv[0], "filename-width"))
1476 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1478 if (!strcmp(argv[0], "show-filename"))
1479 return parse_enum(&opt_filename, argv[2], filename_map);
1481 if (!strcmp(argv[0], "horizontal-scroll"))
1482 return parse_step(&opt_hscroll, argv[2]);
1484 if (!strcmp(argv[0], "split-view-height"))
1485 return parse_step(&opt_scale_split_view, argv[2]);
1487 if (!strcmp(argv[0], "vertical-split"))
1488 return parse_bool(&opt_vsplit, argv[2]);
1490 if (!strcmp(argv[0], "tab-size"))
1491 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1493 if (!strcmp(argv[0], "diff-context")) {
1494 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1496 if (code == OPT_OK)
1497 update_diff_context_arg(opt_diff_context);
1498 return code;
1501 if (!strcmp(argv[0], "ignore-space")) {
1502 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1504 if (code == OPT_OK)
1505 update_ignore_space_arg();
1506 return code;
1509 if (!strcmp(argv[0], "commit-order")) {
1510 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1512 if (code == OPT_OK)
1513 update_commit_order_arg();
1514 return code;
1517 if (!strcmp(argv[0], "status-untracked-dirs"))
1518 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1520 if (!strcmp(argv[0], "read-git-colors"))
1521 return parse_bool(&opt_read_git_colors, argv[2]);
1523 if (!strcmp(argv[0], "ignore-case"))
1524 return parse_bool(&opt_ignore_case, argv[2]);
1526 if (!strcmp(argv[0], "wrap-lines"))
1527 return parse_bool(&opt_wrap_lines, argv[2]);
1529 if (!strcmp(argv[0], "show-id"))
1530 return parse_bool(&opt_show_id, argv[2]);
1532 if (!strcmp(argv[0], "id-width"))
1533 return parse_id(&opt_id_cols, argv[2]);
1535 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1538 /* Wants: mode request key */
1539 static enum option_code
1540 option_bind_command(int argc, const char *argv[])
1542 enum request request;
1543 struct keymap *keymap;
1544 int key;
1546 if (argc < 3)
1547 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1549 if (!(keymap = get_keymap(argv[0])))
1550 return OPT_ERR_UNKNOWN_KEY_MAP;
1552 key = get_key_value(argv[1]);
1553 if (key == ERR)
1554 return OPT_ERR_UNKNOWN_KEY;
1556 request = get_request(argv[2]);
1557 if (request == REQ_UNKNOWN) {
1558 static const struct enum_map obsolete[] = {
1559 ENUM_MAP("cherry-pick", REQ_NONE),
1560 ENUM_MAP("screen-resize", REQ_NONE),
1561 ENUM_MAP("tree-parent", REQ_PARENT),
1563 int alias;
1565 if (map_enum(&alias, obsolete, argv[2])) {
1566 if (alias != REQ_NONE)
1567 add_keybinding(keymap, alias, key);
1568 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1571 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1572 enum run_request_flag flags = RUN_REQUEST_FORCE;
1574 while (*argv[2]) {
1575 if (*argv[2] == '@') {
1576 flags |= RUN_REQUEST_SILENT;
1577 } else if (*argv[2] == '?') {
1578 flags |= RUN_REQUEST_CONFIRM;
1579 } else if (*argv[2] == '<') {
1580 flags |= RUN_REQUEST_EXIT;
1581 } else {
1582 break;
1584 argv[2]++;
1587 return add_run_request(keymap, key, argv + 2, flags)
1588 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1590 if (request == REQ_UNKNOWN)
1591 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1593 add_keybinding(keymap, request, key);
1595 return OPT_OK;
1599 static enum option_code load_option_file(const char *path);
1601 static enum option_code
1602 option_source_command(int argc, const char *argv[])
1604 if (argc < 1)
1605 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1607 return load_option_file(argv[0]);
1610 static enum option_code
1611 set_option(const char *opt, char *value)
1613 const char *argv[SIZEOF_ARG];
1614 int argc = 0;
1616 if (!argv_from_string(argv, &argc, value))
1617 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1619 if (!strcmp(opt, "color"))
1620 return option_color_command(argc, argv);
1622 if (!strcmp(opt, "set"))
1623 return option_set_command(argc, argv);
1625 if (!strcmp(opt, "bind"))
1626 return option_bind_command(argc, argv);
1628 if (!strcmp(opt, "source"))
1629 return option_source_command(argc, argv);
1631 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1634 struct config_state {
1635 const char *path;
1636 int lineno;
1637 bool errors;
1640 static int
1641 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1643 struct config_state *config = data;
1644 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1646 config->lineno++;
1648 /* Check for comment markers, since read_properties() will
1649 * only ensure opt and value are split at first " \t". */
1650 optlen = strcspn(opt, "#");
1651 if (optlen == 0)
1652 return OK;
1654 if (opt[optlen] == 0) {
1655 /* Look for comment endings in the value. */
1656 size_t len = strcspn(value, "#");
1658 if (len < valuelen) {
1659 valuelen = len;
1660 value[valuelen] = 0;
1663 status = set_option(opt, value);
1666 if (status != OPT_OK) {
1667 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1668 option_errors[status], (int) optlen, opt);
1669 config->errors = TRUE;
1672 /* Always keep going if errors are encountered. */
1673 return OK;
1676 static enum option_code
1677 load_option_file(const char *path)
1679 struct config_state config = { path, 0, FALSE };
1680 struct io io;
1682 /* Do not read configuration from stdin if set to "" */
1683 if (!path || !strlen(path))
1684 return OPT_OK;
1686 /* It's OK that the file doesn't exist. */
1687 if (!io_open(&io, "%s", path))
1688 return OPT_ERR_FILE_DOES_NOT_EXIST;
1690 if (io_load(&io, " \t", read_option, &config) == ERR ||
1691 config.errors == TRUE)
1692 warn("Errors while loading %s.", path);
1693 return OPT_OK;
1696 static int
1697 load_options(void)
1699 const char *home = getenv("HOME");
1700 const char *tigrc_user = getenv("TIGRC_USER");
1701 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1702 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1703 char buf[SIZEOF_STR];
1705 if (!tigrc_system)
1706 tigrc_system = SYSCONFDIR "/tigrc";
1707 load_option_file(tigrc_system);
1709 if (!tigrc_user) {
1710 if (!home || !string_format(buf, "%s/.tigrc", home))
1711 return ERR;
1712 tigrc_user = buf;
1714 load_option_file(tigrc_user);
1716 /* Add _after_ loading config files to avoid adding run requests
1717 * that conflict with keybindings. */
1718 add_builtin_run_requests();
1720 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1721 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1722 int argc = 0;
1724 if (!string_format(buf, "%s", tig_diff_opts) ||
1725 !argv_from_string(diff_opts, &argc, buf))
1726 die("TIG_DIFF_OPTS contains too many arguments");
1727 else if (!argv_copy(&opt_diff_argv, diff_opts))
1728 die("Failed to format TIG_DIFF_OPTS arguments");
1731 return OK;
1736 * The viewer
1739 struct view;
1740 struct view_ops;
1742 /* The display array of active views and the index of the current view. */
1743 static struct view *display[2];
1744 static WINDOW *display_win[2];
1745 static WINDOW *display_title[2];
1746 static WINDOW *display_sep;
1748 static unsigned int current_view;
1750 #define foreach_displayed_view(view, i) \
1751 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1753 #define displayed_views() (display[1] != NULL ? 2 : 1)
1755 /* Current head and commit ID */
1756 static char ref_blob[SIZEOF_REF] = "";
1757 static char ref_commit[SIZEOF_REF] = "HEAD";
1758 static char ref_head[SIZEOF_REF] = "HEAD";
1759 static char ref_branch[SIZEOF_REF] = "";
1761 enum view_flag {
1762 VIEW_NO_FLAGS = 0,
1763 VIEW_ALWAYS_LINENO = 1 << 0,
1764 VIEW_CUSTOM_STATUS = 1 << 1,
1765 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1766 VIEW_ADD_PAGER_REFS = 1 << 3,
1767 VIEW_OPEN_DIFF = 1 << 4,
1768 VIEW_NO_REF = 1 << 5,
1769 VIEW_NO_GIT_DIR = 1 << 6,
1770 VIEW_DIFF_LIKE = 1 << 7,
1773 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1775 struct position {
1776 unsigned long offset; /* Offset of the window top */
1777 unsigned long col; /* Offset from the window side. */
1778 unsigned long lineno; /* Current line number */
1781 struct view {
1782 const char *name; /* View name */
1783 const char *id; /* Points to either of ref_{head,commit,blob} */
1785 struct view_ops *ops; /* View operations */
1787 char ref[SIZEOF_REF]; /* Hovered commit reference */
1788 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1790 int height, width; /* The width and height of the main window */
1791 WINDOW *win; /* The main window */
1793 /* Navigation */
1794 struct position pos; /* Current position. */
1795 struct position prev_pos; /* Previous position. */
1797 /* Searching */
1798 char grep[SIZEOF_STR]; /* Search string */
1799 regex_t *regex; /* Pre-compiled regexp */
1801 /* If non-NULL, points to the view that opened this view. If this view
1802 * is closed tig will switch back to the parent view. */
1803 struct view *parent;
1804 struct view *prev;
1806 /* Buffering */
1807 size_t lines; /* Total number of lines */
1808 struct line *line; /* Line index */
1809 unsigned int digits; /* Number of digits in the lines member. */
1811 /* Number of lines with custom status, not to be counted in the
1812 * view title. */
1813 unsigned int custom_lines;
1815 /* Drawing */
1816 struct line *curline; /* Line currently being drawn. */
1817 enum line_type curtype; /* Attribute currently used for drawing. */
1818 unsigned long col; /* Column when drawing. */
1819 bool has_scrolled; /* View was scrolled. */
1821 /* Loading */
1822 const char **argv; /* Shell command arguments. */
1823 const char *dir; /* Directory from which to execute. */
1824 struct io io;
1825 struct io *pipe;
1826 time_t start_time;
1827 time_t update_secs;
1828 struct encoding *encoding;
1830 /* Private data */
1831 void *private;
1834 enum open_flags {
1835 OPEN_DEFAULT = 0, /* Use default view switching. */
1836 OPEN_SPLIT = 1, /* Split current view. */
1837 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1838 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1839 OPEN_PREPARED = 32, /* Open already prepared command. */
1840 OPEN_EXTRA = 64, /* Open extra data from command. */
1843 struct view_ops {
1844 /* What type of content being displayed. Used in the title bar. */
1845 const char *type;
1846 /* What keymap does this view have */
1847 struct keymap keymap;
1848 /* Flags to control the view behavior. */
1849 enum view_flag flags;
1850 /* Size of private data. */
1851 size_t private_size;
1852 /* Open and reads in all view content. */
1853 bool (*open)(struct view *view, enum open_flags flags);
1854 /* Read one line; updates view->line. */
1855 bool (*read)(struct view *view, char *data);
1856 /* Draw one line; @lineno must be < view->height. */
1857 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1858 /* Depending on view handle a special requests. */
1859 enum request (*request)(struct view *view, enum request request, struct line *line);
1860 /* Search for regexp in a line. */
1861 bool (*grep)(struct view *view, struct line *line);
1862 /* Select line */
1863 void (*select)(struct view *view, struct line *line);
1866 #define VIEW_OPS(id, name, ref) name##_ops
1867 static struct view_ops VIEW_INFO(VIEW_OPS);
1869 static struct view views[] = {
1870 #define VIEW_DATA(id, name, ref) \
1871 { #name, ref, &name##_ops }
1872 VIEW_INFO(VIEW_DATA)
1875 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1877 #define foreach_view(view, i) \
1878 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1880 #define view_is_displayed(view) \
1881 (view == display[0] || view == display[1])
1883 #define view_has_line(view, line_) \
1884 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1886 static enum request
1887 view_request(struct view *view, enum request request)
1889 if (!view || !view->lines)
1890 return request;
1891 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1895 * View drawing.
1898 static inline void
1899 set_view_attr(struct view *view, enum line_type type)
1901 if (!view->curline->selected && view->curtype != type) {
1902 (void) wattrset(view->win, get_line_attr(type));
1903 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1904 view->curtype = type;
1908 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1910 static bool
1911 draw_chars(struct view *view, enum line_type type, const char *string,
1912 int max_len, bool use_tilde)
1914 static char out_buffer[BUFSIZ * 2];
1915 int len = 0;
1916 int col = 0;
1917 int trimmed = FALSE;
1918 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1920 if (max_len <= 0)
1921 return VIEW_MAX_LEN(view) <= 0;
1923 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1925 set_view_attr(view, type);
1926 if (len > 0) {
1927 if (opt_iconv_out != ICONV_NONE) {
1928 size_t inlen = len + 1;
1929 char *instr = calloc(1, inlen);
1930 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1931 if (!instr)
1932 return VIEW_MAX_LEN(view) <= 0;
1934 strncpy(instr, string, len);
1936 char *outbuf = out_buffer;
1937 size_t outlen = sizeof(out_buffer);
1939 size_t ret;
1941 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1942 if (ret != (size_t) -1) {
1943 string = out_buffer;
1944 len = sizeof(out_buffer) - outlen;
1946 free(instr);
1949 waddnstr(view->win, string, len);
1951 if (trimmed && use_tilde) {
1952 set_view_attr(view, LINE_DELIMITER);
1953 waddch(view->win, '~');
1954 col++;
1958 view->col += col;
1959 return VIEW_MAX_LEN(view) <= 0;
1962 static bool
1963 draw_space(struct view *view, enum line_type type, int max, int spaces)
1965 static char space[] = " ";
1967 spaces = MIN(max, spaces);
1969 while (spaces > 0) {
1970 int len = MIN(spaces, sizeof(space) - 1);
1972 if (draw_chars(view, type, space, len, FALSE))
1973 return TRUE;
1974 spaces -= len;
1977 return VIEW_MAX_LEN(view) <= 0;
1980 static bool
1981 draw_text(struct view *view, enum line_type type, const char *string)
1983 static char text[SIZEOF_STR];
1985 do {
1986 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1988 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1989 return TRUE;
1990 string += pos;
1991 } while (*string);
1993 return VIEW_MAX_LEN(view) <= 0;
1996 static bool PRINTF_LIKE(3, 4)
1997 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1999 char text[SIZEOF_STR];
2000 int retval;
2002 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2003 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2006 static bool
2007 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2009 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2010 int max = VIEW_MAX_LEN(view);
2011 int i;
2013 if (max < size)
2014 size = max;
2016 set_view_attr(view, type);
2017 /* Using waddch() instead of waddnstr() ensures that
2018 * they'll be rendered correctly for the cursor line. */
2019 for (i = skip; i < size; i++)
2020 waddch(view->win, graphic[i]);
2022 view->col += size;
2023 if (separator) {
2024 if (size < max && skip <= size)
2025 waddch(view->win, ' ');
2026 view->col++;
2029 return VIEW_MAX_LEN(view) <= 0;
2032 static bool
2033 draw_field(struct view *view, enum line_type type, const char *text, int width, bool trim)
2035 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2036 int col = view->col;
2038 if (!text)
2039 return draw_space(view, type, max, max);
2041 return draw_chars(view, type, text, max - 1, trim)
2042 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2045 static bool
2046 draw_date(struct view *view, struct time *time)
2048 const char *date = mkdate(time, opt_date);
2049 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2051 if (opt_date == DATE_NO)
2052 return FALSE;
2054 return draw_field(view, LINE_DATE, date, cols, FALSE);
2057 static bool
2058 draw_author(struct view *view, const char *author)
2060 bool trim = author_trim(opt_author_width);
2061 const char *text = mkauthor(author, opt_author_width, opt_author);
2063 if (opt_author == AUTHOR_NO)
2064 return FALSE;
2066 return draw_field(view, LINE_AUTHOR, text, opt_author_width, trim);
2069 static bool
2070 draw_id(struct view *view, enum line_type type, const char *id)
2072 return draw_field(view, type, id, opt_id_cols, FALSE);
2075 static bool
2076 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2078 bool trim = filename && strlen(filename) >= opt_filename_width;
2080 if (opt_filename == FILENAME_NO)
2081 return FALSE;
2083 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2084 return FALSE;
2086 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, trim);
2089 static bool
2090 draw_mode(struct view *view, mode_t mode)
2092 const char *str = mkmode(mode);
2094 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), FALSE);
2097 static bool
2098 draw_lineno(struct view *view, unsigned int lineno)
2100 char number[10];
2101 int digits3 = view->digits < 3 ? 3 : view->digits;
2102 int max = MIN(VIEW_MAX_LEN(view), digits3);
2103 char *text = NULL;
2104 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2106 if (!opt_line_number)
2107 return FALSE;
2109 lineno += view->pos.offset + 1;
2110 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2111 static char fmt[] = "%1ld";
2113 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2114 if (string_format(number, fmt, lineno))
2115 text = number;
2117 if (text)
2118 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2119 else
2120 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2121 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2124 static bool
2125 draw_refs(struct view *view, struct ref_list *refs)
2127 size_t i;
2129 if (!opt_show_refs || !refs)
2130 return FALSE;
2132 for (i = 0; i < refs->size; i++) {
2133 struct ref *ref = refs->refs[i];
2134 enum line_type type = get_line_type_from_ref(ref);
2136 if (draw_formatted(view, type, "[%s]", ref->name))
2137 return TRUE;
2139 if (draw_text(view, LINE_DEFAULT, " "))
2140 return TRUE;
2143 return FALSE;
2146 static bool
2147 draw_view_line(struct view *view, unsigned int lineno)
2149 struct line *line;
2150 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2152 assert(view_is_displayed(view));
2154 if (view->pos.offset + lineno >= view->lines)
2155 return FALSE;
2157 line = &view->line[view->pos.offset + lineno];
2159 wmove(view->win, lineno, 0);
2160 if (line->cleareol)
2161 wclrtoeol(view->win);
2162 view->col = 0;
2163 view->curline = line;
2164 view->curtype = LINE_NONE;
2165 line->selected = FALSE;
2166 line->dirty = line->cleareol = 0;
2168 if (selected) {
2169 set_view_attr(view, LINE_CURSOR);
2170 line->selected = TRUE;
2171 view->ops->select(view, line);
2174 return view->ops->draw(view, line, lineno);
2177 static void
2178 redraw_view_dirty(struct view *view)
2180 bool dirty = FALSE;
2181 int lineno;
2183 for (lineno = 0; lineno < view->height; lineno++) {
2184 if (view->pos.offset + lineno >= view->lines)
2185 break;
2186 if (!view->line[view->pos.offset + lineno].dirty)
2187 continue;
2188 dirty = TRUE;
2189 if (!draw_view_line(view, lineno))
2190 break;
2193 if (!dirty)
2194 return;
2195 wnoutrefresh(view->win);
2198 static void
2199 redraw_view_from(struct view *view, int lineno)
2201 assert(0 <= lineno && lineno < view->height);
2203 for (; lineno < view->height; lineno++) {
2204 if (!draw_view_line(view, lineno))
2205 break;
2208 wnoutrefresh(view->win);
2211 static void
2212 redraw_view(struct view *view)
2214 werase(view->win);
2215 redraw_view_from(view, 0);
2219 static void
2220 update_view_title(struct view *view)
2222 char buf[SIZEOF_STR];
2223 char state[SIZEOF_STR];
2224 size_t bufpos = 0, statelen = 0;
2225 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2226 struct line *line = &view->line[view->pos.lineno];
2228 assert(view_is_displayed(view));
2230 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2231 line->lineno) {
2232 unsigned int view_lines = view->pos.offset + view->height;
2233 unsigned int lines = view->lines
2234 ? MIN(view_lines, view->lines) * 100 / view->lines
2235 : 0;
2237 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2238 view->ops->type,
2239 line->lineno,
2240 view->lines - view->custom_lines,
2241 lines);
2245 if (view->pipe) {
2246 time_t secs = time(NULL) - view->start_time;
2248 /* Three git seconds are a long time ... */
2249 if (secs > 2)
2250 string_format_from(state, &statelen, " loading %lds", secs);
2253 string_format_from(buf, &bufpos, "[%s]", view->name);
2254 if (*view->ref && bufpos < view->width) {
2255 size_t refsize = strlen(view->ref);
2256 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2258 if (minsize < view->width)
2259 refsize = view->width - minsize + 7;
2260 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2263 if (statelen && bufpos < view->width) {
2264 string_format_from(buf, &bufpos, "%s", state);
2267 if (view == display[current_view])
2268 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2269 else
2270 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2272 mvwaddnstr(window, 0, 0, buf, bufpos);
2273 wclrtoeol(window);
2274 wnoutrefresh(window);
2277 static int
2278 apply_step(double step, int value)
2280 if (step >= 1)
2281 return (int) step;
2282 value *= step + 0.01;
2283 return value ? value : 1;
2286 static void
2287 apply_horizontal_split(struct view *base, struct view *view)
2289 view->width = base->width;
2290 view->height = apply_step(opt_scale_split_view, base->height);
2291 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2292 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2293 base->height -= view->height;
2296 static void
2297 apply_vertical_split(struct view *base, struct view *view)
2299 view->height = base->height;
2300 view->width = apply_step(opt_scale_vsplit_view, base->width);
2301 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2302 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2303 base->width -= view->width;
2306 static void
2307 redraw_display_separator(bool clear)
2309 if (displayed_views() > 1 && opt_vsplit) {
2310 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2312 if (clear)
2313 wclear(display_sep);
2314 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2315 wnoutrefresh(display_sep);
2319 static void
2320 resize_display(void)
2322 int x, y, i;
2323 struct view *base = display[0];
2324 struct view *view = display[1] ? display[1] : display[0];
2326 /* Setup window dimensions */
2328 getmaxyx(stdscr, base->height, base->width);
2330 /* Make room for the status window. */
2331 base->height -= 1;
2333 if (view != base) {
2334 if (opt_vsplit) {
2335 apply_vertical_split(base, view);
2337 /* Make room for the separator bar. */
2338 view->width -= 1;
2339 } else {
2340 apply_horizontal_split(base, view);
2343 /* Make room for the title bar. */
2344 view->height -= 1;
2347 /* Make room for the title bar. */
2348 base->height -= 1;
2350 x = y = 0;
2352 foreach_displayed_view (view, i) {
2353 if (!display_win[i]) {
2354 display_win[i] = newwin(view->height, view->width, y, x);
2355 if (!display_win[i])
2356 die("Failed to create %s view", view->name);
2358 scrollok(display_win[i], FALSE);
2360 display_title[i] = newwin(1, view->width, y + view->height, x);
2361 if (!display_title[i])
2362 die("Failed to create title window");
2364 } else {
2365 wresize(display_win[i], view->height, view->width);
2366 mvwin(display_win[i], y, x);
2367 wresize(display_title[i], 1, view->width);
2368 mvwin(display_title[i], y + view->height, x);
2371 if (i > 0 && opt_vsplit) {
2372 if (!display_sep) {
2373 display_sep = newwin(view->height, 1, 0, x - 1);
2374 if (!display_sep)
2375 die("Failed to create separator window");
2377 } else {
2378 wresize(display_sep, view->height, 1);
2379 mvwin(display_sep, 0, x - 1);
2383 view->win = display_win[i];
2385 if (opt_vsplit)
2386 x += view->width + 1;
2387 else
2388 y += view->height + 1;
2391 redraw_display_separator(FALSE);
2394 static void
2395 redraw_display(bool clear)
2397 struct view *view;
2398 int i;
2400 foreach_displayed_view (view, i) {
2401 if (clear)
2402 wclear(view->win);
2403 redraw_view(view);
2404 update_view_title(view);
2407 redraw_display_separator(clear);
2411 * Option management
2414 #define TOGGLE_MENU \
2415 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2416 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2417 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2418 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2419 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2420 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2421 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2422 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2423 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2424 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL) \
2425 TOGGLE_(ID, 'X', "commit ID display", &opt_show_id, NULL)
2427 static bool
2428 toggle_option(enum request request)
2430 const struct {
2431 enum request request;
2432 const struct enum_map *map;
2433 size_t map_size;
2434 } data[] = {
2435 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2436 TOGGLE_MENU
2437 #undef TOGGLE_
2439 const struct menu_item menu[] = {
2440 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2441 TOGGLE_MENU
2442 #undef TOGGLE_
2443 { 0 }
2445 int i = 0;
2447 if (request == REQ_OPTIONS) {
2448 if (!prompt_menu("Toggle option", menu, &i))
2449 return FALSE;
2450 } else {
2451 while (i < ARRAY_SIZE(data) && data[i].request != request)
2452 i++;
2453 if (i >= ARRAY_SIZE(data))
2454 die("Invalid request (%d)", request);
2457 if (data[i].map != NULL) {
2458 unsigned int *opt = menu[i].data;
2460 *opt = (*opt + 1) % data[i].map_size;
2461 if (data[i].map == ignore_space_map) {
2462 update_ignore_space_arg();
2463 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2464 return TRUE;
2466 } else if (data[i].map == commit_order_map) {
2467 update_commit_order_arg();
2468 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2469 return TRUE;
2472 redraw_display(FALSE);
2473 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2475 } else {
2476 bool *option = menu[i].data;
2478 *option = !*option;
2479 redraw_display(FALSE);
2480 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2483 return FALSE;
2488 * Navigation
2491 static bool
2492 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2494 if (lineno >= view->lines)
2495 lineno = view->lines > 0 ? view->lines - 1 : 0;
2497 if (offset > lineno || offset + view->height <= lineno) {
2498 unsigned long half = view->height / 2;
2500 if (lineno > half)
2501 offset = lineno - half;
2502 else
2503 offset = 0;
2506 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2507 view->pos.offset = offset;
2508 view->pos.lineno = lineno;
2509 return TRUE;
2512 return FALSE;
2515 /* Scrolling backend */
2516 static void
2517 do_scroll_view(struct view *view, int lines)
2519 bool redraw_current_line = FALSE;
2521 /* The rendering expects the new offset. */
2522 view->pos.offset += lines;
2524 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2525 assert(lines);
2527 /* Move current line into the view. */
2528 if (view->pos.lineno < view->pos.offset) {
2529 view->pos.lineno = view->pos.offset;
2530 redraw_current_line = TRUE;
2531 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2532 view->pos.lineno = view->pos.offset + view->height - 1;
2533 redraw_current_line = TRUE;
2536 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2538 /* Redraw the whole screen if scrolling is pointless. */
2539 if (view->height < ABS(lines)) {
2540 redraw_view(view);
2542 } else {
2543 int line = lines > 0 ? view->height - lines : 0;
2544 int end = line + ABS(lines);
2546 scrollok(view->win, TRUE);
2547 wscrl(view->win, lines);
2548 scrollok(view->win, FALSE);
2550 while (line < end && draw_view_line(view, line))
2551 line++;
2553 if (redraw_current_line)
2554 draw_view_line(view, view->pos.lineno - view->pos.offset);
2555 wnoutrefresh(view->win);
2558 view->has_scrolled = TRUE;
2559 report_clear();
2562 /* Scroll frontend */
2563 static void
2564 scroll_view(struct view *view, enum request request)
2566 int lines = 1;
2568 assert(view_is_displayed(view));
2570 switch (request) {
2571 case REQ_SCROLL_FIRST_COL:
2572 view->pos.col = 0;
2573 redraw_view_from(view, 0);
2574 report_clear();
2575 return;
2576 case REQ_SCROLL_LEFT:
2577 if (view->pos.col == 0) {
2578 report("Cannot scroll beyond the first column");
2579 return;
2581 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2582 view->pos.col = 0;
2583 else
2584 view->pos.col -= apply_step(opt_hscroll, view->width);
2585 redraw_view_from(view, 0);
2586 report_clear();
2587 return;
2588 case REQ_SCROLL_RIGHT:
2589 view->pos.col += apply_step(opt_hscroll, view->width);
2590 redraw_view(view);
2591 report_clear();
2592 return;
2593 case REQ_SCROLL_PAGE_DOWN:
2594 lines = view->height;
2595 case REQ_SCROLL_LINE_DOWN:
2596 if (view->pos.offset + lines > view->lines)
2597 lines = view->lines - view->pos.offset;
2599 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2600 report("Cannot scroll beyond the last line");
2601 return;
2603 break;
2605 case REQ_SCROLL_PAGE_UP:
2606 lines = view->height;
2607 case REQ_SCROLL_LINE_UP:
2608 if (lines > view->pos.offset)
2609 lines = view->pos.offset;
2611 if (lines == 0) {
2612 report("Cannot scroll beyond the first line");
2613 return;
2616 lines = -lines;
2617 break;
2619 default:
2620 die("request %d not handled in switch", request);
2623 do_scroll_view(view, lines);
2626 /* Cursor moving */
2627 static void
2628 move_view(struct view *view, enum request request)
2630 int scroll_steps = 0;
2631 int steps;
2633 switch (request) {
2634 case REQ_MOVE_FIRST_LINE:
2635 steps = -view->pos.lineno;
2636 break;
2638 case REQ_MOVE_LAST_LINE:
2639 steps = view->lines - view->pos.lineno - 1;
2640 break;
2642 case REQ_MOVE_PAGE_UP:
2643 steps = view->height > view->pos.lineno
2644 ? -view->pos.lineno : -view->height;
2645 break;
2647 case REQ_MOVE_PAGE_DOWN:
2648 steps = view->pos.lineno + view->height >= view->lines
2649 ? view->lines - view->pos.lineno - 1 : view->height;
2650 break;
2652 case REQ_MOVE_UP:
2653 case REQ_PREVIOUS:
2654 steps = -1;
2655 break;
2657 case REQ_MOVE_DOWN:
2658 case REQ_NEXT:
2659 steps = 1;
2660 break;
2662 default:
2663 die("request %d not handled in switch", request);
2666 if (steps <= 0 && view->pos.lineno == 0) {
2667 report("Cannot move beyond the first line");
2668 return;
2670 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2671 report("Cannot move beyond the last line");
2672 return;
2675 /* Move the current line */
2676 view->pos.lineno += steps;
2677 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2679 /* Check whether the view needs to be scrolled */
2680 if (view->pos.lineno < view->pos.offset ||
2681 view->pos.lineno >= view->pos.offset + view->height) {
2682 scroll_steps = steps;
2683 if (steps < 0 && -steps > view->pos.offset) {
2684 scroll_steps = -view->pos.offset;
2686 } else if (steps > 0) {
2687 if (view->pos.lineno == view->lines - 1 &&
2688 view->lines > view->height) {
2689 scroll_steps = view->lines - view->pos.offset - 1;
2690 if (scroll_steps >= view->height)
2691 scroll_steps -= view->height - 1;
2696 if (!view_is_displayed(view)) {
2697 view->pos.offset += scroll_steps;
2698 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2699 view->ops->select(view, &view->line[view->pos.lineno]);
2700 return;
2703 /* Repaint the old "current" line if we be scrolling */
2704 if (ABS(steps) < view->height)
2705 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2707 if (scroll_steps) {
2708 do_scroll_view(view, scroll_steps);
2709 return;
2712 /* Draw the current line */
2713 draw_view_line(view, view->pos.lineno - view->pos.offset);
2715 wnoutrefresh(view->win);
2716 report_clear();
2721 * Searching
2724 static void search_view(struct view *view, enum request request);
2726 static bool
2727 grep_text(struct view *view, const char *text[])
2729 regmatch_t pmatch;
2730 size_t i;
2732 for (i = 0; text[i]; i++)
2733 if (*text[i] &&
2734 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2735 return TRUE;
2736 return FALSE;
2739 static void
2740 select_view_line(struct view *view, unsigned long lineno)
2742 struct position old = view->pos;
2744 if (goto_view_line(view, view->pos.offset, lineno)) {
2745 if (view_is_displayed(view)) {
2746 if (old.offset != view->pos.offset) {
2747 redraw_view(view);
2748 } else {
2749 draw_view_line(view, old.lineno - view->pos.offset);
2750 draw_view_line(view, view->pos.lineno - view->pos.offset);
2751 wnoutrefresh(view->win);
2753 } else {
2754 view->ops->select(view, &view->line[view->pos.lineno]);
2759 static void
2760 find_next(struct view *view, enum request request)
2762 unsigned long lineno = view->pos.lineno;
2763 int direction;
2765 if (!*view->grep) {
2766 if (!*opt_search)
2767 report("No previous search");
2768 else
2769 search_view(view, request);
2770 return;
2773 switch (request) {
2774 case REQ_SEARCH:
2775 case REQ_FIND_NEXT:
2776 direction = 1;
2777 break;
2779 case REQ_SEARCH_BACK:
2780 case REQ_FIND_PREV:
2781 direction = -1;
2782 break;
2784 default:
2785 return;
2788 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2789 lineno += direction;
2791 /* Note, lineno is unsigned long so will wrap around in which case it
2792 * will become bigger than view->lines. */
2793 for (; lineno < view->lines; lineno += direction) {
2794 if (view->ops->grep(view, &view->line[lineno])) {
2795 select_view_line(view, lineno);
2796 report("Line %ld matches '%s'", lineno + 1, view->grep);
2797 return;
2801 report("No match found for '%s'", view->grep);
2804 static void
2805 search_view(struct view *view, enum request request)
2807 int regex_err;
2808 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
2810 if (view->regex) {
2811 regfree(view->regex);
2812 *view->grep = 0;
2813 } else {
2814 view->regex = calloc(1, sizeof(*view->regex));
2815 if (!view->regex)
2816 return;
2819 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
2820 if (regex_err != 0) {
2821 char buf[SIZEOF_STR] = "unknown error";
2823 regerror(regex_err, view->regex, buf, sizeof(buf));
2824 report("Search failed: %s", buf);
2825 return;
2828 string_copy(view->grep, opt_search);
2830 find_next(view, request);
2834 * Incremental updating
2837 static inline bool
2838 check_position(struct position *pos)
2840 return pos->lineno || pos->col || pos->offset;
2843 static inline void
2844 clear_position(struct position *pos)
2846 memset(pos, 0, sizeof(*pos));
2849 static void
2850 reset_view(struct view *view)
2852 int i;
2854 for (i = 0; i < view->lines; i++)
2855 if (!view->line[i].dont_free)
2856 free(view->line[i].data);
2857 free(view->line);
2859 view->prev_pos = view->pos;
2860 clear_position(&view->pos);
2862 view->line = NULL;
2863 view->lines = 0;
2864 view->vid[0] = 0;
2865 view->custom_lines = 0;
2866 view->update_secs = 0;
2869 static const char *
2870 format_arg(const char *name)
2872 static struct {
2873 const char *name;
2874 size_t namelen;
2875 const char *value;
2876 const char *value_if_empty;
2877 } vars[] = {
2878 #define FORMAT_VAR(name, value, value_if_empty) \
2879 { name, STRING_SIZE(name), value, value_if_empty }
2880 FORMAT_VAR("%(directory)", opt_path, "."),
2881 FORMAT_VAR("%(file)", opt_file, ""),
2882 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2883 FORMAT_VAR("%(head)", ref_head, ""),
2884 FORMAT_VAR("%(commit)", ref_commit, ""),
2885 FORMAT_VAR("%(blob)", ref_blob, ""),
2886 FORMAT_VAR("%(branch)", ref_branch, ""),
2888 int i;
2890 if (!prefixcmp(name, "%(prompt"))
2891 return read_prompt("Command argument: ");
2893 for (i = 0; i < ARRAY_SIZE(vars); i++)
2894 if (!strncmp(name, vars[i].name, vars[i].namelen))
2895 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2897 report("Unknown replacement: `%s`", name);
2898 return NULL;
2901 static bool
2902 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2904 char buf[SIZEOF_STR];
2905 int argc;
2907 argv_free(*dst_argv);
2909 for (argc = 0; src_argv[argc]; argc++) {
2910 const char *arg = src_argv[argc];
2911 size_t bufpos = 0;
2913 if (!strcmp(arg, "%(fileargs)")) {
2914 if (!argv_append_array(dst_argv, opt_file_argv))
2915 break;
2916 continue;
2918 } else if (!strcmp(arg, "%(diffargs)")) {
2919 if (!argv_append_array(dst_argv, opt_diff_argv))
2920 break;
2921 continue;
2923 } else if (!strcmp(arg, "%(blameargs)")) {
2924 if (!argv_append_array(dst_argv, opt_blame_argv))
2925 break;
2926 continue;
2928 } else if (!strcmp(arg, "%(revargs)") ||
2929 (first && !strcmp(arg, "%(commit)"))) {
2930 if (!argv_append_array(dst_argv, opt_rev_argv))
2931 break;
2932 continue;
2935 while (arg) {
2936 char *next = strstr(arg, "%(");
2937 int len = next - arg;
2938 const char *value;
2940 if (!next) {
2941 len = strlen(arg);
2942 value = "";
2944 } else {
2945 value = format_arg(next);
2947 if (!value) {
2948 return FALSE;
2952 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2953 return FALSE;
2955 arg = next ? strchr(next, ')') + 1 : NULL;
2958 if (!argv_append(dst_argv, buf))
2959 break;
2962 return src_argv[argc] == NULL;
2965 static bool
2966 restore_view_position(struct view *view)
2968 /* A view without a previous view is the first view */
2969 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2970 select_view_line(view, opt_lineno - 1);
2971 opt_lineno = 0;
2974 /* Ensure that the view position is in a valid state. */
2975 if (!check_position(&view->prev_pos) ||
2976 (view->pipe && view->lines <= view->prev_pos.lineno))
2977 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2979 /* Changing the view position cancels the restoring. */
2980 /* FIXME: Changing back to the first line is not detected. */
2981 if (check_position(&view->pos)) {
2982 clear_position(&view->prev_pos);
2983 return FALSE;
2986 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2987 view_is_displayed(view))
2988 werase(view->win);
2990 view->pos.col = view->prev_pos.col;
2991 clear_position(&view->prev_pos);
2993 return TRUE;
2996 static void
2997 end_update(struct view *view, bool force)
2999 if (!view->pipe)
3000 return;
3001 while (!view->ops->read(view, NULL))
3002 if (!force)
3003 return;
3004 if (force)
3005 io_kill(view->pipe);
3006 io_done(view->pipe);
3007 view->pipe = NULL;
3010 static void
3011 setup_update(struct view *view, const char *vid)
3013 reset_view(view);
3014 string_copy_rev(view->vid, vid);
3015 view->pipe = &view->io;
3016 view->start_time = time(NULL);
3019 static bool
3020 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3022 bool extra = !!(flags & (OPEN_EXTRA));
3023 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3024 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3026 if (!reload && !strcmp(view->vid, view->id))
3027 return TRUE;
3029 if (view->pipe) {
3030 if (extra)
3031 io_done(view->pipe);
3032 else
3033 end_update(view, TRUE);
3036 if (!refresh && argv) {
3037 view->dir = dir;
3038 if (!format_argv(&view->argv, argv, !view->prev)) {
3039 report("Failed to format %s arguments", view->name);
3040 return FALSE;
3043 /* Put the current ref_* value to the view title ref
3044 * member. This is needed by the blob view. Most other
3045 * views sets it automatically after loading because the
3046 * first line is a commit line. */
3047 string_copy_rev(view->ref, view->id);
3050 if (view->argv && view->argv[0] &&
3051 !io_run(&view->io, IO_RD, view->dir, view->argv)) {
3052 report("Failed to open %s view", view->name);
3053 return FALSE;
3056 if (!extra)
3057 setup_update(view, view->id);
3059 return TRUE;
3062 static bool
3063 update_view(struct view *view)
3065 char *line;
3066 /* Clear the view and redraw everything since the tree sorting
3067 * might have rearranged things. */
3068 bool redraw = view->lines == 0;
3069 bool can_read = TRUE;
3070 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3072 if (!view->pipe)
3073 return TRUE;
3075 if (!io_can_read(view->pipe, FALSE)) {
3076 if (view->lines == 0 && view_is_displayed(view)) {
3077 time_t secs = time(NULL) - view->start_time;
3079 if (secs > 1 && secs > view->update_secs) {
3080 if (view->update_secs == 0)
3081 redraw_view(view);
3082 update_view_title(view);
3083 view->update_secs = secs;
3086 return TRUE;
3089 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3090 if (encoding) {
3091 line = encoding_convert(encoding, line);
3094 if (!view->ops->read(view, line)) {
3095 report("Allocation failure");
3096 end_update(view, TRUE);
3097 return FALSE;
3102 unsigned long lines = view->lines;
3103 int digits;
3105 for (digits = 0; lines; digits++)
3106 lines /= 10;
3108 /* Keep the displayed view in sync with line number scaling. */
3109 if (digits != view->digits) {
3110 view->digits = digits;
3111 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3112 redraw = TRUE;
3116 if (io_error(view->pipe)) {
3117 report("Failed to read: %s", io_strerror(view->pipe));
3118 end_update(view, TRUE);
3120 } else if (io_eof(view->pipe)) {
3121 if (view_is_displayed(view))
3122 report_clear();
3123 end_update(view, FALSE);
3126 if (restore_view_position(view))
3127 redraw = TRUE;
3129 if (!view_is_displayed(view))
3130 return TRUE;
3132 if (redraw)
3133 redraw_view_from(view, 0);
3134 else
3135 redraw_view_dirty(view);
3137 /* Update the title _after_ the redraw so that if the redraw picks up a
3138 * commit reference in view->ref it'll be available here. */
3139 update_view_title(view);
3140 return TRUE;
3143 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3145 static struct line *
3146 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3148 struct line *line;
3150 if (!realloc_lines(&view->line, view->lines, 1))
3151 return NULL;
3153 if (data_size) {
3154 void *alloc_data = calloc(1, data_size);
3156 if (!alloc_data)
3157 return NULL;
3159 if (data)
3160 memcpy(alloc_data, data, data_size);
3161 data = alloc_data;
3164 line = &view->line[view->lines++];
3165 memset(line, 0, sizeof(*line));
3166 line->type = type;
3167 line->data = (void *) data;
3168 line->dirty = 1;
3170 if (custom)
3171 view->custom_lines++;
3172 else
3173 line->lineno = view->lines - view->custom_lines;
3175 return line;
3178 static struct line *
3179 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3181 struct line *line = add_line(view, NULL, type, data_size, custom);
3183 if (line)
3184 *ptr = line->data;
3185 return line;
3188 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3189 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3191 static struct line *
3192 add_line_nodata(struct view *view, enum line_type type)
3194 return add_line(view, NULL, type, 0, FALSE);
3197 static struct line *
3198 add_line_static_data(struct view *view, const void *data, enum line_type type)
3200 struct line *line = add_line(view, data, type, 0, FALSE);
3202 if (line)
3203 line->dont_free = TRUE;
3204 return line;
3207 static struct line *
3208 add_line_text(struct view *view, const char *text, enum line_type type)
3210 return add_line(view, text, type, strlen(text) + 1, FALSE);
3213 static struct line * PRINTF_LIKE(3, 4)
3214 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3216 char buf[SIZEOF_STR];
3217 int retval;
3219 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3220 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3224 * View opening
3227 static void
3228 split_view(struct view *prev, struct view *view)
3230 display[1] = view;
3231 current_view = 1;
3232 view->parent = prev;
3233 resize_display();
3235 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3236 /* Take the title line into account. */
3237 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3239 /* Scroll the view that was split if the current line is
3240 * outside the new limited view. */
3241 do_scroll_view(prev, lines);
3244 if (view != prev && view_is_displayed(prev)) {
3245 /* "Blur" the previous view. */
3246 update_view_title(prev);
3250 static void
3251 maximize_view(struct view *view, bool redraw)
3253 memset(display, 0, sizeof(display));
3254 current_view = 0;
3255 display[current_view] = view;
3256 resize_display();
3257 if (redraw) {
3258 redraw_display(FALSE);
3259 report_clear();
3263 static void
3264 load_view(struct view *view, struct view *prev, enum open_flags flags)
3266 if (view->pipe)
3267 end_update(view, TRUE);
3268 if (view->ops->private_size) {
3269 if (!view->private)
3270 view->private = calloc(1, view->ops->private_size);
3271 else
3272 memset(view->private, 0, view->ops->private_size);
3275 /* When prev == view it means this is the first loaded view. */
3276 if (prev && view != prev) {
3277 view->prev = prev;
3280 if (!view->ops->open(view, flags))
3281 return;
3283 if (prev) {
3284 bool split = !!(flags & OPEN_SPLIT);
3286 if (split) {
3287 split_view(prev, view);
3288 } else {
3289 maximize_view(view, FALSE);
3293 restore_view_position(view);
3295 if (view->pipe && view->lines == 0) {
3296 /* Clear the old view and let the incremental updating refill
3297 * the screen. */
3298 werase(view->win);
3299 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3300 clear_position(&view->prev_pos);
3301 report_clear();
3302 } else if (view_is_displayed(view)) {
3303 redraw_view(view);
3304 report_clear();
3308 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3309 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3311 static void
3312 open_view(struct view *prev, enum request request, enum open_flags flags)
3314 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3315 struct view *view = VIEW(request);
3316 int nviews = displayed_views();
3318 assert(flags ^ OPEN_REFRESH);
3320 if (view == prev && nviews == 1 && !reload) {
3321 report("Already in %s view", view->name);
3322 return;
3325 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3326 report("The %s view is disabled in pager view", view->name);
3327 return;
3330 load_view(view, prev ? prev : view, flags);
3333 static void
3334 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3336 enum request request = view - views + REQ_OFFSET + 1;
3338 if (view->pipe)
3339 end_update(view, TRUE);
3340 view->dir = dir;
3342 if (!argv_copy(&view->argv, argv)) {
3343 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3344 } else {
3345 open_view(prev, request, flags | OPEN_PREPARED);
3349 static void
3350 open_external_viewer(const char *argv[], const char *dir, bool confirm)
3352 def_prog_mode(); /* save current tty modes */
3353 endwin(); /* restore original tty modes */
3354 io_run_fg(argv, dir);
3355 if (confirm) {
3356 fprintf(stderr, "Press Enter to continue");
3357 getc(opt_tty);
3359 reset_prog_mode();
3360 redraw_display(TRUE);
3363 static void
3364 open_mergetool(const char *file)
3366 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3368 open_external_viewer(mergetool_argv, opt_cdup, TRUE);
3371 static void
3372 open_editor(const char *file)
3374 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3375 char editor_cmd[SIZEOF_STR];
3376 const char *editor;
3377 int argc = 0;
3379 editor = getenv("GIT_EDITOR");
3380 if (!editor && *opt_editor)
3381 editor = opt_editor;
3382 if (!editor)
3383 editor = getenv("VISUAL");
3384 if (!editor)
3385 editor = getenv("EDITOR");
3386 if (!editor)
3387 editor = "vi";
3389 string_ncopy(editor_cmd, editor, strlen(editor));
3390 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3391 report("Failed to read editor command");
3392 return;
3395 editor_argv[argc] = file;
3396 open_external_viewer(editor_argv, opt_cdup, TRUE);
3399 static bool
3400 open_run_request(enum request request)
3402 struct run_request *req = get_run_request(request);
3403 const char **argv = NULL;
3405 if (!req) {
3406 report("Unknown run request");
3407 return FALSE;
3410 if (format_argv(&argv, req->argv, FALSE)) {
3411 bool confirmed = !req->confirm;
3413 if (req->confirm) {
3414 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3416 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3417 string_format(prompt, "Run `%s`?", cmd) &&
3418 prompt_yesno(prompt)) {
3419 confirmed = TRUE;
3423 if (confirmed && argv_remove_quotes(argv)) {
3424 if (req->silent)
3425 io_run_bg(argv);
3426 else
3427 open_external_viewer(argv, NULL, !req->exit);
3431 if (argv)
3432 argv_free(argv);
3433 free(argv);
3435 return req->exit;
3439 * User request switch noodle
3442 static int
3443 view_driver(struct view *view, enum request request)
3445 int i;
3447 if (request == REQ_NONE)
3448 return TRUE;
3450 if (request > REQ_NONE) {
3451 if (open_run_request(request))
3452 return FALSE;
3453 view_request(view, REQ_REFRESH);
3454 return TRUE;
3457 request = view_request(view, request);
3458 if (request == REQ_NONE)
3459 return TRUE;
3461 switch (request) {
3462 case REQ_MOVE_UP:
3463 case REQ_MOVE_DOWN:
3464 case REQ_MOVE_PAGE_UP:
3465 case REQ_MOVE_PAGE_DOWN:
3466 case REQ_MOVE_FIRST_LINE:
3467 case REQ_MOVE_LAST_LINE:
3468 move_view(view, request);
3469 break;
3471 case REQ_SCROLL_FIRST_COL:
3472 case REQ_SCROLL_LEFT:
3473 case REQ_SCROLL_RIGHT:
3474 case REQ_SCROLL_LINE_DOWN:
3475 case REQ_SCROLL_LINE_UP:
3476 case REQ_SCROLL_PAGE_DOWN:
3477 case REQ_SCROLL_PAGE_UP:
3478 scroll_view(view, request);
3479 break;
3481 case REQ_VIEW_MAIN:
3482 case REQ_VIEW_DIFF:
3483 case REQ_VIEW_LOG:
3484 case REQ_VIEW_TREE:
3485 case REQ_VIEW_HELP:
3486 case REQ_VIEW_BRANCH:
3487 case REQ_VIEW_BLAME:
3488 case REQ_VIEW_BLOB:
3489 case REQ_VIEW_STATUS:
3490 case REQ_VIEW_STAGE:
3491 case REQ_VIEW_PAGER:
3492 open_view(view, request, OPEN_DEFAULT);
3493 break;
3495 case REQ_NEXT:
3496 case REQ_PREVIOUS:
3497 if (view->parent) {
3498 int line;
3500 view = view->parent;
3501 line = view->pos.lineno;
3502 move_view(view, request);
3503 if (view_is_displayed(view))
3504 update_view_title(view);
3505 if (line != view->pos.lineno)
3506 view_request(view, REQ_ENTER);
3507 } else {
3508 move_view(view, request);
3510 break;
3512 case REQ_VIEW_NEXT:
3514 int nviews = displayed_views();
3515 int next_view = (current_view + 1) % nviews;
3517 if (next_view == current_view) {
3518 report("Only one view is displayed");
3519 break;
3522 current_view = next_view;
3523 /* Blur out the title of the previous view. */
3524 update_view_title(view);
3525 report_clear();
3526 break;
3528 case REQ_REFRESH:
3529 report("Refreshing is not yet supported for the %s view", view->name);
3530 break;
3532 case REQ_MAXIMIZE:
3533 if (displayed_views() == 2)
3534 maximize_view(view, TRUE);
3535 break;
3537 case REQ_OPTIONS:
3538 case REQ_TOGGLE_LINENO:
3539 case REQ_TOGGLE_DATE:
3540 case REQ_TOGGLE_AUTHOR:
3541 case REQ_TOGGLE_FILENAME:
3542 case REQ_TOGGLE_GRAPHIC:
3543 case REQ_TOGGLE_REV_GRAPH:
3544 case REQ_TOGGLE_REFS:
3545 case REQ_TOGGLE_CHANGES:
3546 case REQ_TOGGLE_IGNORE_SPACE:
3547 case REQ_TOGGLE_ID:
3548 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3549 reload_view(view);
3550 break;
3552 case REQ_TOGGLE_SORT_FIELD:
3553 case REQ_TOGGLE_SORT_ORDER:
3554 report("Sorting is not yet supported for the %s view", view->name);
3555 break;
3557 case REQ_DIFF_CONTEXT_UP:
3558 case REQ_DIFF_CONTEXT_DOWN:
3559 report("Changing the diff context is not yet supported for the %s view", view->name);
3560 break;
3562 case REQ_SEARCH:
3563 case REQ_SEARCH_BACK:
3564 search_view(view, request);
3565 break;
3567 case REQ_FIND_NEXT:
3568 case REQ_FIND_PREV:
3569 find_next(view, request);
3570 break;
3572 case REQ_STOP_LOADING:
3573 foreach_view(view, i) {
3574 if (view->pipe)
3575 report("Stopped loading the %s view", view->name),
3576 end_update(view, TRUE);
3578 break;
3580 case REQ_SHOW_VERSION:
3581 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3582 return TRUE;
3584 case REQ_SCREEN_REDRAW:
3585 redraw_display(TRUE);
3586 break;
3588 case REQ_EDIT:
3589 report("Nothing to edit");
3590 break;
3592 case REQ_ENTER:
3593 report("Nothing to enter");
3594 break;
3596 case REQ_VIEW_CLOSE:
3597 /* XXX: Mark closed views by letting view->prev point to the
3598 * view itself. Parents to closed view should never be
3599 * followed. */
3600 if (view->prev && view->prev != view) {
3601 maximize_view(view->prev, TRUE);
3602 view->prev = view;
3603 break;
3605 /* Fall-through */
3606 case REQ_QUIT:
3607 return FALSE;
3609 default:
3610 report("Unknown key, press %s for help",
3611 get_view_key(view, REQ_VIEW_HELP));
3612 return TRUE;
3615 return TRUE;
3620 * View backend utilities
3623 enum sort_field {
3624 ORDERBY_NAME,
3625 ORDERBY_DATE,
3626 ORDERBY_AUTHOR,
3629 struct sort_state {
3630 const enum sort_field *fields;
3631 size_t size, current;
3632 bool reverse;
3635 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3636 #define get_sort_field(state) ((state).fields[(state).current])
3637 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3639 static void
3640 sort_view(struct view *view, enum request request, struct sort_state *state,
3641 int (*compare)(const void *, const void *))
3643 switch (request) {
3644 case REQ_TOGGLE_SORT_FIELD:
3645 state->current = (state->current + 1) % state->size;
3646 break;
3648 case REQ_TOGGLE_SORT_ORDER:
3649 state->reverse = !state->reverse;
3650 break;
3651 default:
3652 die("Not a sort request");
3655 qsort(view->line, view->lines, sizeof(*view->line), compare);
3656 redraw_view(view);
3659 static bool
3660 update_diff_context(enum request request)
3662 int diff_context = opt_diff_context;
3664 switch (request) {
3665 case REQ_DIFF_CONTEXT_UP:
3666 opt_diff_context += 1;
3667 update_diff_context_arg(opt_diff_context);
3668 break;
3670 case REQ_DIFF_CONTEXT_DOWN:
3671 if (opt_diff_context == 0) {
3672 report("Diff context cannot be less than zero");
3673 break;
3675 opt_diff_context -= 1;
3676 update_diff_context_arg(opt_diff_context);
3677 break;
3679 default:
3680 die("Not a diff context request");
3683 return diff_context != opt_diff_context;
3686 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3688 /* Small author cache to reduce memory consumption. It uses binary
3689 * search to lookup or find place to position new entries. No entries
3690 * are ever freed. */
3691 static const char *
3692 get_author(const char *name)
3694 static const char **authors;
3695 static size_t authors_size;
3696 int from = 0, to = authors_size - 1;
3698 while (from <= to) {
3699 size_t pos = (to + from) / 2;
3700 int cmp = strcmp(name, authors[pos]);
3702 if (!cmp)
3703 return authors[pos];
3705 if (cmp < 0)
3706 to = pos - 1;
3707 else
3708 from = pos + 1;
3711 if (!realloc_authors(&authors, authors_size, 1))
3712 return NULL;
3713 name = strdup(name);
3714 if (!name)
3715 return NULL;
3717 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3718 authors[from] = name;
3719 authors_size++;
3721 return name;
3724 static void
3725 parse_timesec(struct time *time, const char *sec)
3727 time->sec = (time_t) atol(sec);
3730 static void
3731 parse_timezone(struct time *time, const char *zone)
3733 long tz;
3735 tz = ('0' - zone[1]) * 60 * 60 * 10;
3736 tz += ('0' - zone[2]) * 60 * 60;
3737 tz += ('0' - zone[3]) * 60 * 10;
3738 tz += ('0' - zone[4]) * 60;
3740 if (zone[0] == '-')
3741 tz = -tz;
3743 time->tz = tz;
3744 time->sec -= tz;
3747 /* Parse author lines where the name may be empty:
3748 * author <email@address.tld> 1138474660 +0100
3750 static void
3751 parse_author_line(char *ident, const char **author, struct time *time)
3753 char *nameend = strchr(ident, '<');
3754 char *emailend = strchr(ident, '>');
3756 if (nameend && emailend)
3757 *nameend = *emailend = 0;
3758 ident = chomp_string(ident);
3759 if (!*ident) {
3760 if (nameend)
3761 ident = chomp_string(nameend + 1);
3762 if (!*ident)
3763 ident = "Unknown";
3766 *author = get_author(ident);
3768 /* Parse epoch and timezone */
3769 if (emailend && emailend[1] == ' ') {
3770 char *secs = emailend + 2;
3771 char *zone = strchr(secs, ' ');
3773 parse_timesec(time, secs);
3775 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3776 parse_timezone(time, zone + 1);
3780 static struct line *
3781 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3783 for (; view_has_line(view, line); line += direction)
3784 if (line->type == type)
3785 return line;
3787 return NULL;
3790 #define find_prev_line_by_type(view, line, type) \
3791 find_line_by_type(view, line, type, -1)
3793 #define find_next_line_by_type(view, line, type) \
3794 find_line_by_type(view, line, type, 1)
3797 * Blame
3800 struct blame_commit {
3801 char id[SIZEOF_REV]; /* SHA1 ID. */
3802 char title[128]; /* First line of the commit message. */
3803 const char *author; /* Author of the commit. */
3804 struct time time; /* Date from the author ident. */
3805 char filename[128]; /* Name of file. */
3806 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3807 char parent_filename[128]; /* Parent/previous name of file. */
3810 struct blame_header {
3811 char id[SIZEOF_REV]; /* SHA1 ID. */
3812 size_t orig_lineno;
3813 size_t lineno;
3814 size_t group;
3817 static bool
3818 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3820 const char *pos = *posref;
3822 *posref = NULL;
3823 pos = strchr(pos + 1, ' ');
3824 if (!pos || !isdigit(pos[1]))
3825 return FALSE;
3826 *number = atoi(pos + 1);
3827 if (*number < min || *number > max)
3828 return FALSE;
3830 *posref = pos;
3831 return TRUE;
3834 static bool
3835 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3837 const char *pos = text + SIZEOF_REV - 2;
3839 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3840 return FALSE;
3842 string_ncopy(header->id, text, SIZEOF_REV);
3844 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3845 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3846 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3847 return FALSE;
3849 return TRUE;
3852 static bool
3853 match_blame_header(const char *name, char **line)
3855 size_t namelen = strlen(name);
3856 bool matched = !strncmp(name, *line, namelen);
3858 if (matched)
3859 *line += namelen;
3861 return matched;
3864 static bool
3865 parse_blame_info(struct blame_commit *commit, char *line)
3867 if (match_blame_header("author ", &line)) {
3868 commit->author = get_author(line);
3870 } else if (match_blame_header("author-time ", &line)) {
3871 parse_timesec(&commit->time, line);
3873 } else if (match_blame_header("author-tz ", &line)) {
3874 parse_timezone(&commit->time, line);
3876 } else if (match_blame_header("summary ", &line)) {
3877 string_ncopy(commit->title, line, strlen(line));
3879 } else if (match_blame_header("previous ", &line)) {
3880 if (strlen(line) <= SIZEOF_REV)
3881 return FALSE;
3882 string_copy_rev(commit->parent_id, line);
3883 line += SIZEOF_REV;
3884 string_ncopy(commit->parent_filename, line, strlen(line));
3886 } else if (match_blame_header("filename ", &line)) {
3887 string_ncopy(commit->filename, line, strlen(line));
3888 return TRUE;
3891 return FALSE;
3895 * Pager backend
3898 static bool
3899 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3901 if (draw_lineno(view, lineno))
3902 return TRUE;
3904 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
3905 return TRUE;
3907 draw_text(view, line->type, line->data);
3908 return TRUE;
3911 static bool
3912 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3914 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3915 char ref[SIZEOF_STR];
3917 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3918 return TRUE;
3920 /* This is the only fatal call, since it can "corrupt" the buffer. */
3921 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3922 return FALSE;
3924 return TRUE;
3927 static void
3928 add_pager_refs(struct view *view, const char *commit_id)
3930 char buf[SIZEOF_STR];
3931 struct ref_list *list;
3932 size_t bufpos = 0, i;
3933 const char *sep = "Refs: ";
3934 bool is_tag = FALSE;
3936 list = get_ref_list(commit_id);
3937 if (!list) {
3938 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3939 goto try_add_describe_ref;
3940 return;
3943 for (i = 0; i < list->size; i++) {
3944 struct ref *ref = list->refs[i];
3945 const char *fmt = ref->tag ? "%s[%s]" :
3946 ref->remote ? "%s<%s>" : "%s%s";
3948 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3949 return;
3950 sep = ", ";
3951 if (ref->tag)
3952 is_tag = TRUE;
3955 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3956 try_add_describe_ref:
3957 /* Add <tag>-g<commit_id> "fake" reference. */
3958 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3959 return;
3962 if (bufpos == 0)
3963 return;
3965 add_line_text(view, buf, LINE_PP_REFS);
3968 static struct line *
3969 pager_wrap_line(struct view *view, const char *data, enum line_type type)
3971 struct line *first_line = NULL;
3972 size_t datalen = strlen(data);
3973 size_t lineno = 0;
3975 while (datalen > 0 || !first_line) {
3976 bool wrapped = first_line != NULL;
3977 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
3978 struct line *line;
3979 char *text;
3981 line = add_line(view, NULL, type, linelen + 1, wrapped);
3982 if (!line)
3983 break;
3984 if (!first_line)
3985 first_line = line;
3986 if (!wrapped)
3987 lineno = line->lineno;
3989 line->wrapped = wrapped;
3990 line->lineno = lineno;
3991 text = line->data;
3992 if (linelen)
3993 strncpy(text, data, linelen);
3994 text[linelen] = 0;
3996 datalen -= linelen;
3997 data += linelen;
4000 return first_line;
4003 static bool
4004 pager_common_read(struct view *view, const char *data, enum line_type type)
4006 struct line *line;
4008 if (!data)
4009 return TRUE;
4011 if (opt_wrap_lines) {
4012 line = pager_wrap_line(view, data, type);
4013 } else {
4014 line = add_line_text(view, data, type);
4017 if (!line)
4018 return FALSE;
4020 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4021 add_pager_refs(view, data + STRING_SIZE("commit "));
4023 return TRUE;
4026 static bool
4027 pager_read(struct view *view, char *data)
4029 if (!data)
4030 return TRUE;
4032 return pager_common_read(view, data, get_line_type(data));
4035 static enum request
4036 pager_request(struct view *view, enum request request, struct line *line)
4038 int split = 0;
4040 if (request != REQ_ENTER)
4041 return request;
4043 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4044 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4045 split = 1;
4048 /* Always scroll the view even if it was split. That way
4049 * you can use Enter to scroll through the log view and
4050 * split open each commit diff. */
4051 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4053 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4054 * but if we are scrolling a non-current view this won't properly
4055 * update the view title. */
4056 if (split)
4057 update_view_title(view);
4059 return REQ_NONE;
4062 static bool
4063 pager_grep(struct view *view, struct line *line)
4065 const char *text[] = { line->data, NULL };
4067 return grep_text(view, text);
4070 static void
4071 pager_select(struct view *view, struct line *line)
4073 if (line->type == LINE_COMMIT) {
4074 char *text = (char *)line->data + STRING_SIZE("commit ");
4076 if (!view_has_flags(view, VIEW_NO_REF))
4077 string_copy_rev(view->ref, text);
4078 string_copy_rev(ref_commit, text);
4082 static bool
4083 pager_open(struct view *view, enum open_flags flags)
4085 if (display[0] == NULL) {
4086 if (!io_open(&view->io, "%s", ""))
4087 die("Failed to open stdin");
4088 flags = OPEN_PREPARED;
4090 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4091 report("No pager content, press %s to run command from prompt",
4092 get_view_key(view, REQ_PROMPT));
4093 return FALSE;
4096 return begin_update(view, NULL, NULL, flags);
4099 static struct view_ops pager_ops = {
4100 "line",
4101 { "pager" },
4102 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4104 pager_open,
4105 pager_read,
4106 pager_draw,
4107 pager_request,
4108 pager_grep,
4109 pager_select,
4112 static bool
4113 log_open(struct view *view, enum open_flags flags)
4115 static const char *log_argv[] = {
4116 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4119 return begin_update(view, NULL, log_argv, flags);
4122 static enum request
4123 log_request(struct view *view, enum request request, struct line *line)
4125 switch (request) {
4126 case REQ_REFRESH:
4127 load_refs();
4128 refresh_view(view);
4129 return REQ_NONE;
4130 default:
4131 return pager_request(view, request, line);
4135 static struct view_ops log_ops = {
4136 "line",
4137 { "log" },
4138 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
4140 log_open,
4141 pager_read,
4142 pager_draw,
4143 log_request,
4144 pager_grep,
4145 pager_select,
4148 struct diff_state {
4149 bool reading_diff_stat;
4150 bool combined_diff;
4153 static bool
4154 diff_open(struct view *view, enum open_flags flags)
4156 static const char *diff_argv[] = {
4157 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4158 "--patch-with-stat",
4159 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4160 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4163 return begin_update(view, NULL, diff_argv, flags);
4166 static bool
4167 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4169 enum line_type type = get_line_type(data);
4171 if (!view->lines && type != LINE_COMMIT)
4172 state->reading_diff_stat = TRUE;
4174 if (state->reading_diff_stat) {
4175 size_t len = strlen(data);
4176 char *pipe = strchr(data, '|');
4177 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4178 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4179 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4181 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4182 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4183 } else {
4184 state->reading_diff_stat = FALSE;
4187 } else if (!strcmp(data, "---")) {
4188 state->reading_diff_stat = TRUE;
4191 if (type == LINE_DIFF_HEADER) {
4192 const int len = line_info[LINE_DIFF_HEADER].linelen;
4194 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4195 !strncmp(data + len, "cc ", strlen("cc ")))
4196 state->combined_diff = TRUE;
4199 /* ADD2 and DEL2 are only valid in combined diff hunks */
4200 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4201 type = LINE_DEFAULT;
4203 return pager_common_read(view, data, type);
4206 static bool
4207 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4209 struct line *marker = find_next_line_by_type(view, line, type);
4211 return marker &&
4212 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4215 static enum request
4216 diff_common_enter(struct view *view, enum request request, struct line *line)
4218 if (line->type == LINE_DIFF_STAT) {
4219 int file_number = 0;
4221 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4222 file_number++;
4223 line--;
4226 for (line = view->line; view_has_line(view, line); line++) {
4227 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4228 if (!line)
4229 break;
4231 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4232 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4233 if (file_number == 1) {
4234 break;
4236 file_number--;
4240 if (!line) {
4241 report("Failed to find file diff");
4242 return REQ_NONE;
4245 select_view_line(view, line - view->line);
4246 report_clear();
4247 return REQ_NONE;
4249 } else {
4250 return pager_request(view, request, line);
4254 static bool
4255 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4257 char *sep = strchr(*text, c);
4259 if (sep != NULL) {
4260 *sep = 0;
4261 draw_text(view, *type, *text);
4262 *sep = c;
4263 *text = sep;
4264 *type = next_type;
4267 return sep != NULL;
4270 static bool
4271 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4273 char *text = line->data;
4274 enum line_type type = line->type;
4276 if (draw_lineno(view, lineno))
4277 return TRUE;
4279 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4280 return TRUE;
4282 if (type == LINE_DIFF_STAT) {
4283 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4284 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4285 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4286 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4287 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4288 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4289 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4291 } else {
4292 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4293 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4297 draw_text(view, type, text);
4298 return TRUE;
4301 static bool
4302 diff_read(struct view *view, char *data)
4304 struct diff_state *state = view->private;
4306 if (!data) {
4307 /* Fall back to retry if no diff will be shown. */
4308 if (view->lines == 0 && opt_file_argv) {
4309 int pos = argv_size(view->argv)
4310 - argv_size(opt_file_argv) - 1;
4312 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4313 for (; view->argv[pos]; pos++) {
4314 free((void *) view->argv[pos]);
4315 view->argv[pos] = NULL;
4318 if (view->pipe)
4319 io_done(view->pipe);
4320 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4321 return FALSE;
4324 return TRUE;
4327 return diff_common_read(view, data, state);
4330 static bool
4331 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4332 struct blame_header *header, struct blame_commit *commit)
4334 char line_arg[SIZEOF_STR];
4335 const char *blame_argv[] = {
4336 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4338 struct io io;
4339 bool ok = FALSE;
4340 char *buf;
4342 if (!string_format(line_arg, "-L%ld,+1", lineno))
4343 return FALSE;
4345 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4346 return FALSE;
4348 while ((buf = io_get(&io, '\n', TRUE))) {
4349 if (header) {
4350 if (!parse_blame_header(header, buf, 9999999))
4351 break;
4352 header = NULL;
4354 } else if (parse_blame_info(commit, buf)) {
4355 ok = TRUE;
4356 break;
4360 if (io_error(&io))
4361 ok = FALSE;
4363 io_done(&io);
4364 return ok;
4367 static bool
4368 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4370 return prefixcmp(chunk, "@@ -") ||
4371 !(chunk = strchr(chunk, marker)) ||
4372 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4375 static enum request
4376 diff_trace_origin(struct view *view, struct line *line)
4378 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4379 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4380 const char *chunk_data;
4381 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4382 int lineno = 0;
4383 const char *file = NULL;
4384 char ref[SIZEOF_REF];
4385 struct blame_header header;
4386 struct blame_commit commit;
4388 if (!diff || !chunk || chunk == line) {
4389 report("The line to trace must be inside a diff chunk");
4390 return REQ_NONE;
4393 for (; diff < line && !file; diff++) {
4394 const char *data = diff->data;
4396 if (!prefixcmp(data, "--- a/")) {
4397 file = data + STRING_SIZE("--- a/");
4398 break;
4402 if (diff == line || !file) {
4403 report("Failed to read the file name");
4404 return REQ_NONE;
4407 chunk_data = chunk->data;
4409 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4410 report("Failed to read the line number");
4411 return REQ_NONE;
4414 if (lineno == 0) {
4415 report("This is the origin of the line");
4416 return REQ_NONE;
4419 for (chunk += 1; chunk < line; chunk++) {
4420 if (chunk->type == LINE_DIFF_ADD) {
4421 lineno += chunk_marker == '+';
4422 } else if (chunk->type == LINE_DIFF_DEL) {
4423 lineno += chunk_marker == '-';
4424 } else {
4425 lineno++;
4429 if (chunk_marker == '+')
4430 string_copy(ref, view->vid);
4431 else
4432 string_format(ref, "%s^", view->vid);
4434 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4435 report("Failed to read blame data");
4436 return REQ_NONE;
4439 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4440 string_copy(opt_ref, header.id);
4441 opt_goto_line = header.orig_lineno - 1;
4443 return REQ_VIEW_BLAME;
4446 static const char *
4447 diff_get_pathname(struct view *view, struct line *line)
4449 const struct line *header;
4450 const char *dst, *prefixes[] = { " b/", "cc ", "combined " };
4451 int i;
4453 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4454 if (!header)
4455 return NULL;
4457 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4458 dst = strstr(header->data, prefixes[i]);
4460 return dst ? dst + strlen(prefixes[--i]) : NULL;
4463 static enum request
4464 diff_request(struct view *view, enum request request, struct line *line)
4466 const char *file;
4468 switch (request) {
4469 case REQ_VIEW_BLAME:
4470 return diff_trace_origin(view, line);
4472 case REQ_DIFF_CONTEXT_UP:
4473 case REQ_DIFF_CONTEXT_DOWN:
4474 if (!update_diff_context(request))
4475 return REQ_NONE;
4476 reload_view(view);
4477 return REQ_NONE;
4479 case REQ_EDIT:
4480 file = diff_get_pathname(view, line);
4481 if (!file || access(file, R_OK))
4482 return pager_request(view, request, line);
4483 open_editor(file);
4484 return REQ_NONE;
4486 case REQ_ENTER:
4487 return diff_common_enter(view, request, line);
4489 default:
4490 return pager_request(view, request, line);
4494 static void
4495 diff_select(struct view *view, struct line *line)
4497 const char *s;
4499 if (line->type == LINE_DIFF_STAT) {
4500 s = get_view_key(view, REQ_ENTER);
4501 string_format(view->ref, "Press '%s' to jump to file diff", s);
4502 } else {
4503 s = diff_get_pathname(view, line);
4504 if (s) {
4505 string_format(view->ref, "Changes to '%s'", s);
4506 } else {
4507 string_ncopy(view->ref, view->id, strlen(view->id));
4508 pager_select(view, line);
4513 static struct view_ops diff_ops = {
4514 "line",
4515 { "diff" },
4516 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4517 sizeof(struct diff_state),
4518 diff_open,
4519 diff_read,
4520 diff_common_draw,
4521 diff_request,
4522 pager_grep,
4523 diff_select,
4527 * Help backend
4530 static bool
4531 help_draw(struct view *view, struct line *line, unsigned int lineno)
4533 if (line->type == LINE_HELP_KEYMAP) {
4534 struct keymap *keymap = line->data;
4536 draw_formatted(view, line->type, "[%c] %s bindings",
4537 keymap->hidden ? '+' : '-', keymap->name);
4538 return TRUE;
4539 } else {
4540 return pager_draw(view, line, lineno);
4544 static bool
4545 help_open_keymap_title(struct view *view, struct keymap *keymap)
4547 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4548 return keymap->hidden;
4551 static void
4552 help_open_keymap(struct view *view, struct keymap *keymap)
4554 const char *group = NULL;
4555 char buf[SIZEOF_STR];
4556 bool add_title = TRUE;
4557 int i;
4559 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4560 const char *key = NULL;
4562 if (req_info[i].request == REQ_NONE)
4563 continue;
4565 if (!req_info[i].request) {
4566 group = req_info[i].help;
4567 continue;
4570 key = get_keys(keymap, req_info[i].request, TRUE);
4571 if (!key || !*key)
4572 continue;
4574 if (add_title && help_open_keymap_title(view, keymap))
4575 return;
4576 add_title = FALSE;
4578 if (group) {
4579 add_line_text(view, group, LINE_HELP_GROUP);
4580 group = NULL;
4583 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4584 enum_name(req_info[i]), req_info[i].help);
4587 group = "External commands:";
4589 for (i = 0; i < run_requests; i++) {
4590 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4591 const char *key;
4593 if (!req || req->keymap != keymap)
4594 continue;
4596 key = get_key_name(req->key);
4597 if (!*key)
4598 key = "(no key defined)";
4600 if (add_title && help_open_keymap_title(view, keymap))
4601 return;
4602 add_title = FALSE;
4604 if (group) {
4605 add_line_text(view, group, LINE_HELP_GROUP);
4606 group = NULL;
4609 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4610 return;
4612 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4616 static bool
4617 help_open(struct view *view, enum open_flags flags)
4619 struct keymap *keymap;
4621 reset_view(view);
4622 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4623 add_line_text(view, "", LINE_DEFAULT);
4625 for (keymap = keymaps; keymap; keymap = keymap->next)
4626 help_open_keymap(view, keymap);
4628 return TRUE;
4631 static enum request
4632 help_request(struct view *view, enum request request, struct line *line)
4634 switch (request) {
4635 case REQ_ENTER:
4636 if (line->type == LINE_HELP_KEYMAP) {
4637 struct keymap *keymap = line->data;
4639 keymap->hidden = !keymap->hidden;
4640 refresh_view(view);
4643 return REQ_NONE;
4644 default:
4645 return pager_request(view, request, line);
4649 static struct view_ops help_ops = {
4650 "line",
4651 { "help" },
4652 VIEW_NO_GIT_DIR,
4654 help_open,
4655 NULL,
4656 help_draw,
4657 help_request,
4658 pager_grep,
4659 pager_select,
4664 * Tree backend
4667 struct tree_stack_entry {
4668 struct tree_stack_entry *prev; /* Entry below this in the stack */
4669 unsigned long lineno; /* Line number to restore */
4670 char *name; /* Position of name in opt_path */
4673 /* The top of the path stack. */
4674 static struct tree_stack_entry *tree_stack = NULL;
4675 unsigned long tree_lineno = 0;
4677 static void
4678 pop_tree_stack_entry(void)
4680 struct tree_stack_entry *entry = tree_stack;
4682 tree_lineno = entry->lineno;
4683 entry->name[0] = 0;
4684 tree_stack = entry->prev;
4685 free(entry);
4688 static void
4689 push_tree_stack_entry(const char *name, unsigned long lineno)
4691 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4692 size_t pathlen = strlen(opt_path);
4694 if (!entry)
4695 return;
4697 entry->prev = tree_stack;
4698 entry->name = opt_path + pathlen;
4699 tree_stack = entry;
4701 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4702 pop_tree_stack_entry();
4703 return;
4706 /* Move the current line to the first tree entry. */
4707 tree_lineno = 1;
4708 entry->lineno = lineno;
4711 /* Parse output from git-ls-tree(1):
4713 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4716 #define SIZEOF_TREE_ATTR \
4717 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4719 #define SIZEOF_TREE_MODE \
4720 STRING_SIZE("100644 ")
4722 #define TREE_ID_OFFSET \
4723 STRING_SIZE("100644 blob ")
4725 #define tree_path_is_parent(path) (!strcmp("..", (path)))
4727 struct tree_entry {
4728 char id[SIZEOF_REV];
4729 char commit[SIZEOF_REV];
4730 mode_t mode;
4731 struct time time; /* Date from the author ident. */
4732 const char *author; /* Author of the commit. */
4733 char name[1];
4736 struct tree_state {
4737 char commit[SIZEOF_REV];
4738 const char *author_name;
4739 struct time author_time;
4740 bool read_date;
4743 static const char *
4744 tree_path(const struct line *line)
4746 return ((struct tree_entry *) line->data)->name;
4749 static int
4750 tree_compare_entry(const struct line *line1, const struct line *line2)
4752 if (line1->type != line2->type)
4753 return line1->type == LINE_TREE_DIR ? -1 : 1;
4754 return strcmp(tree_path(line1), tree_path(line2));
4757 static const enum sort_field tree_sort_fields[] = {
4758 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4760 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4762 static int
4763 tree_compare(const void *l1, const void *l2)
4765 const struct line *line1 = (const struct line *) l1;
4766 const struct line *line2 = (const struct line *) l2;
4767 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4768 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4770 if (line1->type == LINE_TREE_HEAD)
4771 return -1;
4772 if (line2->type == LINE_TREE_HEAD)
4773 return 1;
4775 switch (get_sort_field(tree_sort_state)) {
4776 case ORDERBY_DATE:
4777 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4779 case ORDERBY_AUTHOR:
4780 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4782 case ORDERBY_NAME:
4783 default:
4784 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4789 static struct line *
4790 tree_entry(struct view *view, enum line_type type, const char *path,
4791 const char *mode, const char *id)
4793 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
4794 struct tree_entry *entry;
4795 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
4797 if (!line)
4798 return NULL;
4800 strncpy(entry->name, path, strlen(path));
4801 if (mode)
4802 entry->mode = strtoul(mode, NULL, 8);
4803 if (id)
4804 string_copy_rev(entry->id, id);
4806 return line;
4809 static bool
4810 tree_read_date(struct view *view, char *text, struct tree_state *state)
4812 if (!text && state->read_date) {
4813 state->read_date = FALSE;
4814 return TRUE;
4816 } else if (!text) {
4817 /* Find next entry to process */
4818 const char *log_file[] = {
4819 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
4820 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4823 if (!view->lines) {
4824 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4825 report("Tree is empty");
4826 return TRUE;
4829 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4830 report("Failed to load tree data");
4831 return TRUE;
4834 state->read_date = TRUE;
4835 return FALSE;
4837 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
4838 string_copy_rev(state->commit, text + STRING_SIZE("commit "));
4840 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4841 parse_author_line(text + STRING_SIZE("author "),
4842 &state->author_name, &state->author_time);
4844 } else if (*text == ':') {
4845 char *pos;
4846 size_t annotated = 1;
4847 size_t i;
4849 pos = strchr(text, '\t');
4850 if (!pos)
4851 return TRUE;
4852 text = pos + 1;
4853 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4854 text += strlen(opt_path);
4855 pos = strchr(text, '/');
4856 if (pos)
4857 *pos = 0;
4859 for (i = 1; i < view->lines; i++) {
4860 struct line *line = &view->line[i];
4861 struct tree_entry *entry = line->data;
4863 annotated += !!entry->author;
4864 if (entry->author || strcmp(entry->name, text))
4865 continue;
4867 string_copy_rev(entry->commit, state->commit);
4868 entry->author = state->author_name;
4869 entry->time = state->author_time;
4870 line->dirty = 1;
4871 break;
4874 if (annotated == view->lines)
4875 io_kill(view->pipe);
4877 return TRUE;
4880 static bool
4881 tree_read(struct view *view, char *text)
4883 struct tree_state *state = view->private;
4884 struct tree_entry *data;
4885 struct line *entry, *line;
4886 enum line_type type;
4887 size_t textlen = text ? strlen(text) : 0;
4888 char *path = text + SIZEOF_TREE_ATTR;
4890 if (state->read_date || !text)
4891 return tree_read_date(view, text, state);
4893 if (textlen <= SIZEOF_TREE_ATTR)
4894 return FALSE;
4895 if (view->lines == 0 &&
4896 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4897 return FALSE;
4899 /* Strip the path part ... */
4900 if (*opt_path) {
4901 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4902 size_t striplen = strlen(opt_path);
4904 if (pathlen > striplen)
4905 memmove(path, path + striplen,
4906 pathlen - striplen + 1);
4908 /* Insert "link" to parent directory. */
4909 if (view->lines == 1 &&
4910 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4911 return FALSE;
4914 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4915 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4916 if (!entry)
4917 return FALSE;
4918 data = entry->data;
4920 /* Skip "Directory ..." and ".." line. */
4921 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4922 if (tree_compare_entry(line, entry) <= 0)
4923 continue;
4925 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4927 line->data = data;
4928 line->type = type;
4929 for (; line <= entry; line++)
4930 line->dirty = line->cleareol = 1;
4931 return TRUE;
4934 if (tree_lineno <= view->pos.lineno)
4935 tree_lineno = view->custom_lines;
4937 if (tree_lineno > view->pos.lineno) {
4938 view->pos.lineno = tree_lineno;
4939 tree_lineno = 0;
4942 return TRUE;
4945 static bool
4946 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4948 struct tree_entry *entry = line->data;
4950 if (line->type == LINE_TREE_HEAD) {
4951 if (draw_text(view, line->type, "Directory path /"))
4952 return TRUE;
4953 } else {
4954 if (draw_mode(view, entry->mode))
4955 return TRUE;
4957 if (draw_author(view, entry->author))
4958 return TRUE;
4960 if (draw_date(view, &entry->time))
4961 return TRUE;
4963 if (opt_show_id && draw_id(view, LINE_ID, entry->commit))
4964 return TRUE;
4967 draw_text(view, line->type, entry->name);
4968 return TRUE;
4971 static void
4972 open_blob_editor(const char *id)
4974 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4975 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4976 int fd = mkstemp(file);
4978 if (fd == -1)
4979 report("Failed to create temporary file");
4980 else if (!io_run_append(blob_argv, fd))
4981 report("Failed to save blob data to file");
4982 else
4983 open_editor(file);
4984 if (fd != -1)
4985 unlink(file);
4988 static enum request
4989 tree_request(struct view *view, enum request request, struct line *line)
4991 enum open_flags flags;
4992 struct tree_entry *entry = line->data;
4994 switch (request) {
4995 case REQ_VIEW_BLAME:
4996 if (line->type != LINE_TREE_FILE) {
4997 report("Blame only supported for files");
4998 return REQ_NONE;
5001 string_copy(opt_ref, view->vid);
5002 return request;
5004 case REQ_EDIT:
5005 if (line->type != LINE_TREE_FILE) {
5006 report("Edit only supported for files");
5007 } else if (!is_head_commit(view->vid)) {
5008 open_blob_editor(entry->id);
5009 } else {
5010 open_editor(opt_file);
5012 return REQ_NONE;
5014 case REQ_TOGGLE_SORT_FIELD:
5015 case REQ_TOGGLE_SORT_ORDER:
5016 sort_view(view, request, &tree_sort_state, tree_compare);
5017 return REQ_NONE;
5019 case REQ_PARENT:
5020 if (!*opt_path) {
5021 /* quit view if at top of tree */
5022 return REQ_VIEW_CLOSE;
5024 /* fake 'cd ..' */
5025 line = &view->line[1];
5026 break;
5028 case REQ_ENTER:
5029 break;
5031 default:
5032 return request;
5035 /* Cleanup the stack if the tree view is at a different tree. */
5036 while (!*opt_path && tree_stack)
5037 pop_tree_stack_entry();
5039 switch (line->type) {
5040 case LINE_TREE_DIR:
5041 /* Depending on whether it is a subdirectory or parent link
5042 * mangle the path buffer. */
5043 if (line == &view->line[1] && *opt_path) {
5044 pop_tree_stack_entry();
5046 } else {
5047 const char *basename = tree_path(line);
5049 push_tree_stack_entry(basename, view->pos.lineno);
5052 /* Trees and subtrees share the same ID, so they are not not
5053 * unique like blobs. */
5054 flags = OPEN_RELOAD;
5055 request = REQ_VIEW_TREE;
5056 break;
5058 case LINE_TREE_FILE:
5059 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5060 request = REQ_VIEW_BLOB;
5061 break;
5063 default:
5064 return REQ_NONE;
5067 open_view(view, request, flags);
5068 if (request == REQ_VIEW_TREE)
5069 view->pos.lineno = tree_lineno;
5071 return REQ_NONE;
5074 static bool
5075 tree_grep(struct view *view, struct line *line)
5077 struct tree_entry *entry = line->data;
5078 const char *text[] = {
5079 entry->name,
5080 mkauthor(entry->author, opt_author_width, opt_author),
5081 mkdate(&entry->time, opt_date),
5082 NULL
5085 return grep_text(view, text);
5088 static void
5089 tree_select(struct view *view, struct line *line)
5091 struct tree_entry *entry = line->data;
5093 if (line->type == LINE_TREE_HEAD) {
5094 string_format(view->ref, "Files in /%s", opt_path);
5095 return;
5098 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5099 string_copy(view->ref, "Open parent directory");
5100 return;
5103 if (line->type == LINE_TREE_FILE) {
5104 string_copy_rev(ref_blob, entry->id);
5105 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5108 string_copy_rev(view->ref, entry->id);
5111 static bool
5112 tree_open(struct view *view, enum open_flags flags)
5114 static const char *tree_argv[] = {
5115 "git", "ls-tree", "%(commit)", "%(directory)", NULL
5118 if (string_rev_is_null(ref_commit)) {
5119 report("No tree exists for this commit");
5120 return FALSE;
5123 if (view->lines == 0 && opt_prefix[0]) {
5124 char *pos = opt_prefix;
5126 while (pos && *pos) {
5127 char *end = strchr(pos, '/');
5129 if (end)
5130 *end = 0;
5131 push_tree_stack_entry(pos, 0);
5132 pos = end;
5133 if (end) {
5134 *end = '/';
5135 pos++;
5139 } else if (strcmp(view->vid, view->id)) {
5140 opt_path[0] = 0;
5143 return begin_update(view, opt_cdup, tree_argv, flags);
5146 static struct view_ops tree_ops = {
5147 "file",
5148 { "tree" },
5149 VIEW_NO_FLAGS,
5150 sizeof(struct tree_state),
5151 tree_open,
5152 tree_read,
5153 tree_draw,
5154 tree_request,
5155 tree_grep,
5156 tree_select,
5159 static bool
5160 blob_open(struct view *view, enum open_flags flags)
5162 static const char *blob_argv[] = {
5163 "git", "cat-file", "blob", "%(blob)", NULL
5166 if (!ref_blob[0]) {
5167 report("No file chosen, press %s to open tree view",
5168 get_view_key(view, REQ_VIEW_TREE));
5169 return FALSE;
5172 view->encoding = get_path_encoding(opt_file, opt_encoding);
5174 return begin_update(view, NULL, blob_argv, flags);
5177 static bool
5178 blob_read(struct view *view, char *line)
5180 if (!line)
5181 return TRUE;
5182 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5185 static enum request
5186 blob_request(struct view *view, enum request request, struct line *line)
5188 switch (request) {
5189 case REQ_EDIT:
5190 open_blob_editor(view->vid);
5191 return REQ_NONE;
5192 default:
5193 return pager_request(view, request, line);
5197 static struct view_ops blob_ops = {
5198 "line",
5199 { "blob" },
5200 VIEW_NO_FLAGS,
5202 blob_open,
5203 blob_read,
5204 pager_draw,
5205 blob_request,
5206 pager_grep,
5207 pager_select,
5211 * Blame backend
5213 * Loading the blame view is a two phase job:
5215 * 1. File content is read either using opt_file from the
5216 * filesystem or using git-cat-file.
5217 * 2. Then blame information is incrementally added by
5218 * reading output from git-blame.
5221 struct blame {
5222 struct blame_commit *commit;
5223 unsigned long lineno;
5224 char text[1];
5227 struct blame_state {
5228 struct blame_commit *commit;
5229 int blamed;
5230 bool done_reading;
5231 bool auto_filename_display;
5234 static bool
5235 blame_detect_filename_display(struct view *view)
5237 bool show_filenames = FALSE;
5238 const char *filename = NULL;
5239 int i;
5241 if (opt_blame_argv) {
5242 for (i = 0; opt_blame_argv[i]; i++) {
5243 if (prefixcmp(opt_blame_argv[i], "-C"))
5244 continue;
5246 show_filenames = TRUE;
5250 for (i = 0; i < view->lines; i++) {
5251 struct blame *blame = view->line[i].data;
5253 if (blame->commit && blame->commit->id[0]) {
5254 if (!filename)
5255 filename = blame->commit->filename;
5256 else if (strcmp(filename, blame->commit->filename))
5257 show_filenames = TRUE;
5261 return show_filenames;
5264 static bool
5265 blame_open(struct view *view, enum open_flags flags)
5267 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5268 char path[SIZEOF_STR];
5269 size_t i;
5271 if (!opt_file[0]) {
5272 report("No file chosen, press %s to open tree view",
5273 get_view_key(view, REQ_VIEW_TREE));
5274 return FALSE;
5277 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5278 string_copy(path, opt_file);
5279 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5280 report("Failed to setup the blame view");
5281 return FALSE;
5285 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5286 const char *blame_cat_file_argv[] = {
5287 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5290 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5291 return FALSE;
5294 /* First pass: remove multiple references to the same commit. */
5295 for (i = 0; i < view->lines; i++) {
5296 struct blame *blame = view->line[i].data;
5298 if (blame->commit && blame->commit->id[0])
5299 blame->commit->id[0] = 0;
5300 else
5301 blame->commit = NULL;
5304 /* Second pass: free existing references. */
5305 for (i = 0; i < view->lines; i++) {
5306 struct blame *blame = view->line[i].data;
5308 if (blame->commit)
5309 free(blame->commit);
5312 string_format(view->vid, "%s", opt_file);
5313 string_format(view->ref, "%s ...", opt_file);
5315 return TRUE;
5318 static struct blame_commit *
5319 get_blame_commit(struct view *view, const char *id)
5321 size_t i;
5323 for (i = 0; i < view->lines; i++) {
5324 struct blame *blame = view->line[i].data;
5326 if (!blame->commit)
5327 continue;
5329 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5330 return blame->commit;
5334 struct blame_commit *commit = calloc(1, sizeof(*commit));
5336 if (commit)
5337 string_ncopy(commit->id, id, SIZEOF_REV);
5338 return commit;
5342 static struct blame_commit *
5343 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5345 struct blame_header header;
5346 struct blame_commit *commit;
5347 struct blame *blame;
5349 if (!parse_blame_header(&header, text, view->lines))
5350 return NULL;
5352 commit = get_blame_commit(view, text);
5353 if (!commit)
5354 return NULL;
5356 state->blamed += header.group;
5357 while (header.group--) {
5358 struct line *line = &view->line[header.lineno + header.group - 1];
5360 blame = line->data;
5361 blame->commit = commit;
5362 blame->lineno = header.orig_lineno + header.group - 1;
5363 line->dirty = 1;
5366 return commit;
5369 static bool
5370 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5372 if (!text) {
5373 const char *blame_argv[] = {
5374 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5375 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5378 if (view->lines == 0 && !view->prev)
5379 die("No blame exist for %s", view->vid);
5381 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5382 report("Failed to load blame data");
5383 return TRUE;
5386 if (opt_goto_line > 0) {
5387 select_view_line(view, opt_goto_line);
5388 opt_goto_line = 0;
5391 state->done_reading = TRUE;
5392 return FALSE;
5394 } else {
5395 size_t textlen = strlen(text);
5396 struct blame *blame;
5398 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5399 return FALSE;
5401 blame->commit = NULL;
5402 strncpy(blame->text, text, textlen);
5403 blame->text[textlen] = 0;
5404 return TRUE;
5408 static bool
5409 blame_read(struct view *view, char *line)
5411 struct blame_state *state = view->private;
5413 if (!state->done_reading)
5414 return blame_read_file(view, line, state);
5416 if (!line) {
5417 state->auto_filename_display = blame_detect_filename_display(view);
5418 string_format(view->ref, "%s", view->vid);
5419 if (view_is_displayed(view)) {
5420 update_view_title(view);
5421 redraw_view_from(view, 0);
5423 return TRUE;
5426 if (!state->commit) {
5427 state->commit = read_blame_commit(view, line, state);
5428 string_format(view->ref, "%s %2zd%%", view->vid,
5429 view->lines ? state->blamed * 100 / view->lines : 0);
5431 } else if (parse_blame_info(state->commit, line)) {
5432 state->commit = NULL;
5435 return TRUE;
5438 static bool
5439 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5441 struct blame_state *state = view->private;
5442 struct blame *blame = line->data;
5443 struct time *time = NULL;
5444 const char *id = NULL, *author = NULL, *filename = NULL;
5445 enum line_type id_type = LINE_ID;
5446 static const enum line_type blame_colors[] = {
5447 LINE_PALETTE_0,
5448 LINE_PALETTE_1,
5449 LINE_PALETTE_2,
5450 LINE_PALETTE_3,
5451 LINE_PALETTE_4,
5452 LINE_PALETTE_5,
5453 LINE_PALETTE_6,
5456 #define BLAME_COLOR(i) \
5457 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5459 if (blame->commit && *blame->commit->filename) {
5460 id = blame->commit->id;
5461 author = blame->commit->author;
5462 filename = blame->commit->filename;
5463 time = &blame->commit->time;
5464 id_type = BLAME_COLOR((long) blame->commit);
5467 if (draw_date(view, time))
5468 return TRUE;
5470 if (draw_author(view, author))
5471 return TRUE;
5473 if (draw_filename(view, filename, state->auto_filename_display))
5474 return TRUE;
5476 if (draw_id(view, id_type, id))
5477 return TRUE;
5479 if (draw_lineno(view, lineno))
5480 return TRUE;
5482 draw_text(view, LINE_DEFAULT, blame->text);
5483 return TRUE;
5486 static bool
5487 check_blame_commit(struct blame *blame, bool check_null_id)
5489 if (!blame->commit)
5490 report("Commit data not loaded yet");
5491 else if (check_null_id && string_rev_is_null(blame->commit->id))
5492 report("No commit exist for the selected line");
5493 else
5494 return TRUE;
5495 return FALSE;
5498 static void
5499 setup_blame_parent_line(struct view *view, struct blame *blame)
5501 char from[SIZEOF_REF + SIZEOF_STR];
5502 char to[SIZEOF_REF + SIZEOF_STR];
5503 const char *diff_tree_argv[] = {
5504 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
5505 "--no-color", "-U0", from, to, "--", NULL
5507 struct io io;
5508 int parent_lineno = -1;
5509 int blamed_lineno = -1;
5510 char *line;
5512 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5513 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5514 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5515 return;
5517 while ((line = io_get(&io, '\n', TRUE))) {
5518 if (*line == '@') {
5519 char *pos = strchr(line, '+');
5521 parent_lineno = atoi(line + 4);
5522 if (pos)
5523 blamed_lineno = atoi(pos + 1);
5525 } else if (*line == '+' && parent_lineno != -1) {
5526 if (blame->lineno == blamed_lineno - 1 &&
5527 !strcmp(blame->text, line + 1)) {
5528 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5529 break;
5531 blamed_lineno++;
5535 io_done(&io);
5538 static enum request
5539 blame_request(struct view *view, enum request request, struct line *line)
5541 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5542 struct blame *blame = line->data;
5544 switch (request) {
5545 case REQ_VIEW_BLAME:
5546 if (check_blame_commit(blame, TRUE)) {
5547 string_copy(opt_ref, blame->commit->id);
5548 string_copy(opt_file, blame->commit->filename);
5549 if (blame->lineno)
5550 view->pos.lineno = blame->lineno;
5551 reload_view(view);
5553 break;
5555 case REQ_PARENT:
5556 if (!check_blame_commit(blame, TRUE))
5557 break;
5558 if (!*blame->commit->parent_id) {
5559 report("The selected commit has no parents");
5560 } else {
5561 string_copy_rev(opt_ref, blame->commit->parent_id);
5562 string_copy(opt_file, blame->commit->parent_filename);
5563 setup_blame_parent_line(view, blame);
5564 opt_goto_line = blame->lineno;
5565 reload_view(view);
5567 break;
5569 case REQ_ENTER:
5570 if (!check_blame_commit(blame, FALSE))
5571 break;
5573 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5574 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5575 break;
5577 if (string_rev_is_null(blame->commit->id)) {
5578 struct view *diff = VIEW(REQ_VIEW_DIFF);
5579 const char *diff_parent_argv[] = {
5580 GIT_DIFF_BLAME(opt_encoding_arg,
5581 opt_diff_context_arg,
5582 opt_ignore_space_arg, view->vid)
5584 const char *diff_no_parent_argv[] = {
5585 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
5586 opt_diff_context_arg,
5587 opt_ignore_space_arg, view->vid)
5589 const char **diff_index_argv = *blame->commit->parent_id
5590 ? diff_parent_argv : diff_no_parent_argv;
5592 open_argv(view, diff, diff_index_argv, NULL, flags);
5593 if (diff->pipe)
5594 string_copy_rev(diff->ref, NULL_ID);
5595 } else {
5596 open_view(view, REQ_VIEW_DIFF, flags);
5598 break;
5600 default:
5601 return request;
5604 return REQ_NONE;
5607 static bool
5608 blame_grep(struct view *view, struct line *line)
5610 struct blame *blame = line->data;
5611 struct blame_commit *commit = blame->commit;
5612 const char *text[] = {
5613 blame->text,
5614 commit ? commit->title : "",
5615 commit ? commit->id : "",
5616 commit && opt_author ? commit->author : "",
5617 commit ? mkdate(&commit->time, opt_date) : "",
5618 NULL
5621 return grep_text(view, text);
5624 static void
5625 blame_select(struct view *view, struct line *line)
5627 struct blame *blame = line->data;
5628 struct blame_commit *commit = blame->commit;
5630 if (!commit)
5631 return;
5633 if (string_rev_is_null(commit->id))
5634 string_ncopy(ref_commit, "HEAD", 4);
5635 else
5636 string_copy_rev(ref_commit, commit->id);
5639 static struct view_ops blame_ops = {
5640 "line",
5641 { "blame" },
5642 VIEW_ALWAYS_LINENO,
5643 sizeof(struct blame_state),
5644 blame_open,
5645 blame_read,
5646 blame_draw,
5647 blame_request,
5648 blame_grep,
5649 blame_select,
5653 * Branch backend
5656 struct branch {
5657 const char *author; /* Author of the last commit. */
5658 struct time time; /* Date of the last activity. */
5659 char title[128]; /* First line of the commit message. */
5660 const struct ref *ref; /* Name and commit ID information. */
5663 static const struct ref branch_all;
5664 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5666 static const enum sort_field branch_sort_fields[] = {
5667 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5669 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5671 struct branch_state {
5672 char id[SIZEOF_REV];
5673 size_t max_ref_length;
5676 static int
5677 branch_compare(const void *l1, const void *l2)
5679 const struct branch *branch1 = ((const struct line *) l1)->data;
5680 const struct branch *branch2 = ((const struct line *) l2)->data;
5682 if (branch_is_all(branch1))
5683 return -1;
5684 else if (branch_is_all(branch2))
5685 return 1;
5687 switch (get_sort_field(branch_sort_state)) {
5688 case ORDERBY_DATE:
5689 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5691 case ORDERBY_AUTHOR:
5692 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5694 case ORDERBY_NAME:
5695 default:
5696 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5700 static bool
5701 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5703 struct branch_state *state = view->private;
5704 struct branch *branch = line->data;
5705 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5706 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5708 if (draw_date(view, &branch->time))
5709 return TRUE;
5711 if (draw_author(view, branch->author))
5712 return TRUE;
5714 if (draw_field(view, type, branch_name, state->max_ref_length, FALSE))
5715 return TRUE;
5717 if (opt_show_id && draw_id(view, LINE_ID, branch->ref->id))
5718 return TRUE;
5720 draw_text(view, LINE_DEFAULT, branch->title);
5721 return TRUE;
5724 static enum request
5725 branch_request(struct view *view, enum request request, struct line *line)
5727 struct branch *branch = line->data;
5729 switch (request) {
5730 case REQ_REFRESH:
5731 load_refs();
5732 refresh_view(view);
5733 return REQ_NONE;
5735 case REQ_TOGGLE_SORT_FIELD:
5736 case REQ_TOGGLE_SORT_ORDER:
5737 sort_view(view, request, &branch_sort_state, branch_compare);
5738 return REQ_NONE;
5740 case REQ_ENTER:
5742 const struct ref *ref = branch->ref;
5743 const char *all_branches_argv[] = {
5744 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
5746 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5748 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5749 return REQ_NONE;
5751 case REQ_JUMP_COMMIT:
5753 int lineno;
5755 for (lineno = 0; lineno < view->lines; lineno++) {
5756 struct branch *branch = view->line[lineno].data;
5758 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5759 select_view_line(view, lineno);
5760 report_clear();
5761 return REQ_NONE;
5765 default:
5766 return request;
5770 static bool
5771 branch_read(struct view *view, char *line)
5773 struct branch_state *state = view->private;
5774 const char *title = NULL;
5775 const char *author = NULL;
5776 struct time time = {};
5777 size_t i;
5779 if (!line)
5780 return TRUE;
5782 switch (get_line_type(line)) {
5783 case LINE_COMMIT:
5784 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5785 return TRUE;
5787 case LINE_AUTHOR:
5788 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5790 default:
5791 title = line + STRING_SIZE("title ");
5794 for (i = 0; i < view->lines; i++) {
5795 struct branch *branch = view->line[i].data;
5797 if (strcmp(branch->ref->id, state->id))
5798 continue;
5800 if (author) {
5801 branch->author = author;
5802 branch->time = time;
5805 if (title)
5806 string_expand(branch->title, sizeof(branch->title), title, 1);
5808 view->line[i].dirty = TRUE;
5811 return TRUE;
5814 static bool
5815 branch_open_visitor(void *data, const struct ref *ref)
5817 struct view *view = data;
5818 struct branch_state *state = view->private;
5819 struct branch *branch;
5820 size_t ref_length;
5822 if (ref->tag || ref->ltag)
5823 return TRUE;
5825 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, ref == &branch_all))
5826 return FALSE;
5828 ref_length = strlen(ref->name);
5829 if (ref_length > state->max_ref_length)
5830 state->max_ref_length = ref_length;
5832 branch->ref = ref;
5833 return TRUE;
5836 static bool
5837 branch_open(struct view *view, enum open_flags flags)
5839 const char *branch_log[] = {
5840 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
5841 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5842 "--all", "--simplify-by-decoration", NULL
5845 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5846 report("Failed to load branch data");
5847 return FALSE;
5850 branch_open_visitor(view, &branch_all);
5851 foreach_ref(branch_open_visitor, view);
5853 return TRUE;
5856 static bool
5857 branch_grep(struct view *view, struct line *line)
5859 struct branch *branch = line->data;
5860 const char *text[] = {
5861 branch->ref->name,
5862 mkauthor(branch->author, opt_author_width, opt_author),
5863 NULL
5866 return grep_text(view, text);
5869 static void
5870 branch_select(struct view *view, struct line *line)
5872 struct branch *branch = line->data;
5874 if (branch_is_all(branch)) {
5875 string_copy(view->ref, "All branches");
5876 return;
5878 string_copy_rev(view->ref, branch->ref->id);
5879 string_copy_rev(ref_commit, branch->ref->id);
5880 string_copy_rev(ref_head, branch->ref->id);
5881 string_copy_rev(ref_branch, branch->ref->name);
5884 static struct view_ops branch_ops = {
5885 "branch",
5886 { "branch" },
5887 VIEW_NO_FLAGS,
5888 sizeof(struct branch_state),
5889 branch_open,
5890 branch_read,
5891 branch_draw,
5892 branch_request,
5893 branch_grep,
5894 branch_select,
5898 * Status backend
5901 struct status {
5902 char status;
5903 struct {
5904 mode_t mode;
5905 char rev[SIZEOF_REV];
5906 char name[SIZEOF_STR];
5907 } old;
5908 struct {
5909 mode_t mode;
5910 char rev[SIZEOF_REV];
5911 char name[SIZEOF_STR];
5912 } new;
5915 static char status_onbranch[SIZEOF_STR];
5916 static struct status stage_status;
5917 static enum line_type stage_line_type;
5919 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5921 /* This should work even for the "On branch" line. */
5922 static inline bool
5923 status_has_none(struct view *view, struct line *line)
5925 return view_has_line(view, line) && !line[1].data;
5928 /* Get fields from the diff line:
5929 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5931 static inline bool
5932 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5934 const char *old_mode = buf + 1;
5935 const char *new_mode = buf + 8;
5936 const char *old_rev = buf + 15;
5937 const char *new_rev = buf + 56;
5938 const char *status = buf + 97;
5940 if (bufsize < 98 ||
5941 old_mode[-1] != ':' ||
5942 new_mode[-1] != ' ' ||
5943 old_rev[-1] != ' ' ||
5944 new_rev[-1] != ' ' ||
5945 status[-1] != ' ')
5946 return FALSE;
5948 file->status = *status;
5950 string_copy_rev(file->old.rev, old_rev);
5951 string_copy_rev(file->new.rev, new_rev);
5953 file->old.mode = strtoul(old_mode, NULL, 8);
5954 file->new.mode = strtoul(new_mode, NULL, 8);
5956 file->old.name[0] = file->new.name[0] = 0;
5958 return TRUE;
5961 static bool
5962 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5964 struct status *unmerged = NULL;
5965 char *buf;
5966 struct io io;
5968 if (!io_run(&io, IO_RD, opt_cdup, argv))
5969 return FALSE;
5971 add_line_nodata(view, type);
5973 while ((buf = io_get(&io, 0, TRUE))) {
5974 struct status *file = unmerged;
5976 if (!file) {
5977 if (!add_line_alloc(view, &file, type, 0, FALSE))
5978 goto error_out;
5981 /* Parse diff info part. */
5982 if (status) {
5983 file->status = status;
5984 if (status == 'A')
5985 string_copy(file->old.rev, NULL_ID);
5987 } else if (!file->status || file == unmerged) {
5988 if (!status_get_diff(file, buf, strlen(buf)))
5989 goto error_out;
5991 buf = io_get(&io, 0, TRUE);
5992 if (!buf)
5993 break;
5995 /* Collapse all modified entries that follow an
5996 * associated unmerged entry. */
5997 if (unmerged == file) {
5998 unmerged->status = 'U';
5999 unmerged = NULL;
6000 } else if (file->status == 'U') {
6001 unmerged = file;
6005 /* Grab the old name for rename/copy. */
6006 if (!*file->old.name &&
6007 (file->status == 'R' || file->status == 'C')) {
6008 string_ncopy(file->old.name, buf, strlen(buf));
6010 buf = io_get(&io, 0, TRUE);
6011 if (!buf)
6012 break;
6015 /* git-ls-files just delivers a NUL separated list of
6016 * file names similar to the second half of the
6017 * git-diff-* output. */
6018 string_ncopy(file->new.name, buf, strlen(buf));
6019 if (!*file->old.name)
6020 string_copy(file->old.name, file->new.name);
6021 file = NULL;
6024 if (io_error(&io)) {
6025 error_out:
6026 io_done(&io);
6027 return FALSE;
6030 if (!view->line[view->lines - 1].data)
6031 add_line_nodata(view, LINE_STAT_NONE);
6033 io_done(&io);
6034 return TRUE;
6037 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6038 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6040 static const char *status_list_other_argv[] = {
6041 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6044 static const char *status_list_no_head_argv[] = {
6045 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6048 static const char *update_index_argv[] = {
6049 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6052 /* Restore the previous line number to stay in the context or select a
6053 * line with something that can be updated. */
6054 static void
6055 status_restore(struct view *view)
6057 if (!check_position(&view->prev_pos))
6058 return;
6060 if (view->prev_pos.lineno >= view->lines)
6061 view->prev_pos.lineno = view->lines - 1;
6062 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6063 view->prev_pos.lineno++;
6064 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6065 view->prev_pos.lineno--;
6067 /* If the above fails, always skip the "On branch" line. */
6068 if (view->prev_pos.lineno < view->lines)
6069 view->pos.lineno = view->prev_pos.lineno;
6070 else
6071 view->pos.lineno = 1;
6073 if (view->prev_pos.offset > view->pos.lineno)
6074 view->pos.offset = view->pos.lineno;
6075 else if (view->prev_pos.offset < view->lines)
6076 view->pos.offset = view->prev_pos.offset;
6078 clear_position(&view->prev_pos);
6081 static void
6082 status_update_onbranch(void)
6084 static const char *paths[][2] = {
6085 { "rebase-apply/rebasing", "Rebasing" },
6086 { "rebase-apply/applying", "Applying mailbox" },
6087 { "rebase-apply/", "Rebasing mailbox" },
6088 { "rebase-merge/interactive", "Interactive rebase" },
6089 { "rebase-merge/", "Rebase merge" },
6090 { "MERGE_HEAD", "Merging" },
6091 { "BISECT_LOG", "Bisecting" },
6092 { "HEAD", "On branch" },
6094 char buf[SIZEOF_STR];
6095 struct stat stat;
6096 int i;
6098 if (is_initial_commit()) {
6099 string_copy(status_onbranch, "Initial commit");
6100 return;
6103 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6104 char *head = opt_head;
6106 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6107 lstat(buf, &stat) < 0)
6108 continue;
6110 if (!*opt_head) {
6111 struct io io;
6113 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6114 io_read_buf(&io, buf, sizeof(buf))) {
6115 head = buf;
6116 if (!prefixcmp(head, "refs/heads/"))
6117 head += STRING_SIZE("refs/heads/");
6121 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6122 string_copy(status_onbranch, opt_head);
6123 return;
6126 string_copy(status_onbranch, "Not currently on any branch");
6129 /* First parse staged info using git-diff-index(1), then parse unstaged
6130 * info using git-diff-files(1), and finally untracked files using
6131 * git-ls-files(1). */
6132 static bool
6133 status_open(struct view *view, enum open_flags flags)
6135 const char **staged_argv = is_initial_commit() ?
6136 status_list_no_head_argv : status_diff_index_argv;
6137 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6139 if (opt_is_inside_work_tree == FALSE) {
6140 report("The status view requires a working tree");
6141 return FALSE;
6144 reset_view(view);
6146 add_line_nodata(view, LINE_STAT_HEAD);
6147 status_update_onbranch();
6149 io_run_bg(update_index_argv);
6151 if (!opt_untracked_dirs_content)
6152 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6154 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6155 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6156 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6157 report("Failed to load status data");
6158 return FALSE;
6161 /* Restore the exact position or use the specialized restore
6162 * mode? */
6163 status_restore(view);
6164 return TRUE;
6167 static bool
6168 status_draw(struct view *view, struct line *line, unsigned int lineno)
6170 struct status *status = line->data;
6171 enum line_type type;
6172 const char *text;
6174 if (!status) {
6175 switch (line->type) {
6176 case LINE_STAT_STAGED:
6177 type = LINE_STAT_SECTION;
6178 text = "Changes to be committed:";
6179 break;
6181 case LINE_STAT_UNSTAGED:
6182 type = LINE_STAT_SECTION;
6183 text = "Changed but not updated:";
6184 break;
6186 case LINE_STAT_UNTRACKED:
6187 type = LINE_STAT_SECTION;
6188 text = "Untracked files:";
6189 break;
6191 case LINE_STAT_NONE:
6192 type = LINE_DEFAULT;
6193 text = " (no files)";
6194 break;
6196 case LINE_STAT_HEAD:
6197 type = LINE_STAT_HEAD;
6198 text = status_onbranch;
6199 break;
6201 default:
6202 return FALSE;
6204 } else {
6205 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6207 buf[0] = status->status;
6208 if (draw_text(view, line->type, buf))
6209 return TRUE;
6210 type = LINE_DEFAULT;
6211 text = status->new.name;
6214 draw_text(view, type, text);
6215 return TRUE;
6218 static enum request
6219 status_enter(struct view *view, struct line *line)
6221 struct status *status = line->data;
6222 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6224 if (line->type == LINE_STAT_NONE ||
6225 (!status && line[1].type == LINE_STAT_NONE)) {
6226 report("No file to diff");
6227 return REQ_NONE;
6230 switch (line->type) {
6231 case LINE_STAT_STAGED:
6232 case LINE_STAT_UNSTAGED:
6233 break;
6235 case LINE_STAT_UNTRACKED:
6236 if (!status) {
6237 report("No file to show");
6238 return REQ_NONE;
6241 if (!suffixcmp(status->new.name, -1, "/")) {
6242 report("Cannot display a directory");
6243 return REQ_NONE;
6245 break;
6247 case LINE_STAT_HEAD:
6248 return REQ_NONE;
6250 default:
6251 die("line type %d not handled in switch", line->type);
6254 if (status) {
6255 stage_status = *status;
6256 } else {
6257 memset(&stage_status, 0, sizeof(stage_status));
6260 stage_line_type = line->type;
6262 open_view(view, REQ_VIEW_STAGE, flags);
6263 return REQ_NONE;
6266 static bool
6267 status_exists(struct view *view, struct status *status, enum line_type type)
6269 unsigned long lineno;
6271 for (lineno = 0; lineno < view->lines; lineno++) {
6272 struct line *line = &view->line[lineno];
6273 struct status *pos = line->data;
6275 if (line->type != type)
6276 continue;
6277 if (!pos && (!status || !status->status) && line[1].data) {
6278 select_view_line(view, lineno);
6279 return TRUE;
6281 if (pos && !strcmp(status->new.name, pos->new.name)) {
6282 select_view_line(view, lineno);
6283 return TRUE;
6287 return FALSE;
6291 static bool
6292 status_update_prepare(struct io *io, enum line_type type)
6294 const char *staged_argv[] = {
6295 "git", "update-index", "-z", "--index-info", NULL
6297 const char *others_argv[] = {
6298 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6301 switch (type) {
6302 case LINE_STAT_STAGED:
6303 return io_run(io, IO_WR, opt_cdup, staged_argv);
6305 case LINE_STAT_UNSTAGED:
6306 case LINE_STAT_UNTRACKED:
6307 return io_run(io, IO_WR, opt_cdup, others_argv);
6309 default:
6310 die("line type %d not handled in switch", type);
6311 return FALSE;
6315 static bool
6316 status_update_write(struct io *io, struct status *status, enum line_type type)
6318 switch (type) {
6319 case LINE_STAT_STAGED:
6320 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6321 status->old.rev, status->old.name, 0);
6323 case LINE_STAT_UNSTAGED:
6324 case LINE_STAT_UNTRACKED:
6325 return io_printf(io, "%s%c", status->new.name, 0);
6327 default:
6328 die("line type %d not handled in switch", type);
6329 return FALSE;
6333 static bool
6334 status_update_file(struct status *status, enum line_type type)
6336 struct io io;
6337 bool result;
6339 if (!status_update_prepare(&io, type))
6340 return FALSE;
6342 result = status_update_write(&io, status, type);
6343 return io_done(&io) && result;
6346 static bool
6347 status_update_files(struct view *view, struct line *line)
6349 char buf[sizeof(view->ref)];
6350 struct io io;
6351 bool result = TRUE;
6352 struct line *pos;
6353 int files = 0;
6354 int file, done;
6355 int cursor_y = -1, cursor_x = -1;
6357 if (!status_update_prepare(&io, line->type))
6358 return FALSE;
6360 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6361 files++;
6363 string_copy(buf, view->ref);
6364 getsyx(cursor_y, cursor_x);
6365 for (file = 0, done = 5; result && file < files; line++, file++) {
6366 int almost_done = file * 100 / files;
6368 if (almost_done > done) {
6369 done = almost_done;
6370 string_format(view->ref, "updating file %u of %u (%d%% done)",
6371 file, files, done);
6372 update_view_title(view);
6373 setsyx(cursor_y, cursor_x);
6374 doupdate();
6376 result = status_update_write(&io, line->data, line->type);
6378 string_copy(view->ref, buf);
6380 return io_done(&io) && result;
6383 static bool
6384 status_update(struct view *view)
6386 struct line *line = &view->line[view->pos.lineno];
6388 assert(view->lines);
6390 if (!line->data) {
6391 if (status_has_none(view, line)) {
6392 report("Nothing to update");
6393 return FALSE;
6396 if (!status_update_files(view, line + 1)) {
6397 report("Failed to update file status");
6398 return FALSE;
6401 } else if (!status_update_file(line->data, line->type)) {
6402 report("Failed to update file status");
6403 return FALSE;
6406 return TRUE;
6409 static bool
6410 status_revert(struct status *status, enum line_type type, bool has_none)
6412 if (!status || type != LINE_STAT_UNSTAGED) {
6413 if (type == LINE_STAT_STAGED) {
6414 report("Cannot revert changes to staged files");
6415 } else if (type == LINE_STAT_UNTRACKED) {
6416 report("Cannot revert changes to untracked files");
6417 } else if (has_none) {
6418 report("Nothing to revert");
6419 } else {
6420 report("Cannot revert changes to multiple files");
6423 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6424 char mode[10] = "100644";
6425 const char *reset_argv[] = {
6426 "git", "update-index", "--cacheinfo", mode,
6427 status->old.rev, status->old.name, NULL
6429 const char *checkout_argv[] = {
6430 "git", "checkout", "--", status->old.name, NULL
6433 if (status->status == 'U') {
6434 string_format(mode, "%5o", status->old.mode);
6436 if (status->old.mode == 0 && status->new.mode == 0) {
6437 reset_argv[2] = "--force-remove";
6438 reset_argv[3] = status->old.name;
6439 reset_argv[4] = NULL;
6442 if (!io_run_fg(reset_argv, opt_cdup))
6443 return FALSE;
6444 if (status->old.mode == 0 && status->new.mode == 0)
6445 return TRUE;
6448 return io_run_fg(checkout_argv, opt_cdup);
6451 return FALSE;
6454 static enum request
6455 status_request(struct view *view, enum request request, struct line *line)
6457 struct status *status = line->data;
6459 switch (request) {
6460 case REQ_STATUS_UPDATE:
6461 if (!status_update(view))
6462 return REQ_NONE;
6463 break;
6465 case REQ_STATUS_REVERT:
6466 if (!status_revert(status, line->type, status_has_none(view, line)))
6467 return REQ_NONE;
6468 break;
6470 case REQ_STATUS_MERGE:
6471 if (!status || status->status != 'U') {
6472 report("Merging only possible for files with unmerged status ('U').");
6473 return REQ_NONE;
6475 open_mergetool(status->new.name);
6476 break;
6478 case REQ_EDIT:
6479 if (!status)
6480 return request;
6481 if (status->status == 'D') {
6482 report("File has been deleted.");
6483 return REQ_NONE;
6486 open_editor(status->new.name);
6487 break;
6489 case REQ_VIEW_BLAME:
6490 if (status)
6491 opt_ref[0] = 0;
6492 return request;
6494 case REQ_ENTER:
6495 /* After returning the status view has been split to
6496 * show the stage view. No further reloading is
6497 * necessary. */
6498 return status_enter(view, line);
6500 case REQ_REFRESH:
6501 /* Simply reload the view. */
6502 break;
6504 default:
6505 return request;
6508 refresh_view(view);
6510 return REQ_NONE;
6513 static void
6514 status_select(struct view *view, struct line *line)
6516 struct status *status = line->data;
6517 char file[SIZEOF_STR] = "all files";
6518 const char *text;
6519 const char *key;
6521 if (status && !string_format(file, "'%s'", status->new.name))
6522 return;
6524 if (!status && line[1].type == LINE_STAT_NONE)
6525 line++;
6527 switch (line->type) {
6528 case LINE_STAT_STAGED:
6529 text = "Press %s to unstage %s for commit";
6530 break;
6532 case LINE_STAT_UNSTAGED:
6533 text = "Press %s to stage %s for commit";
6534 break;
6536 case LINE_STAT_UNTRACKED:
6537 text = "Press %s to stage %s for addition";
6538 break;
6540 case LINE_STAT_HEAD:
6541 case LINE_STAT_NONE:
6542 text = "Nothing to update";
6543 break;
6545 default:
6546 die("line type %d not handled in switch", line->type);
6549 if (status && status->status == 'U') {
6550 text = "Press %s to resolve conflict in %s";
6551 key = get_view_key(view, REQ_STATUS_MERGE);
6553 } else {
6554 key = get_view_key(view, REQ_STATUS_UPDATE);
6557 string_format(view->ref, text, key, file);
6558 if (status)
6559 string_copy(opt_file, status->new.name);
6562 static bool
6563 status_grep(struct view *view, struct line *line)
6565 struct status *status = line->data;
6567 if (status) {
6568 const char buf[2] = { status->status, 0 };
6569 const char *text[] = { status->new.name, buf, NULL };
6571 return grep_text(view, text);
6574 return FALSE;
6577 static struct view_ops status_ops = {
6578 "file",
6579 { "status" },
6580 VIEW_CUSTOM_STATUS,
6582 status_open,
6583 NULL,
6584 status_draw,
6585 status_request,
6586 status_grep,
6587 status_select,
6591 struct stage_state {
6592 struct diff_state diff;
6593 size_t chunks;
6594 int *chunk;
6597 static bool
6598 stage_diff_write(struct io *io, struct line *line, struct line *end)
6600 while (line < end) {
6601 if (!io_write(io, line->data, strlen(line->data)) ||
6602 !io_write(io, "\n", 1))
6603 return FALSE;
6604 line++;
6605 if (line->type == LINE_DIFF_CHUNK ||
6606 line->type == LINE_DIFF_HEADER)
6607 break;
6610 return TRUE;
6613 static bool
6614 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6616 const char *apply_argv[SIZEOF_ARG] = {
6617 "git", "apply", "--whitespace=nowarn", NULL
6619 struct line *diff_hdr;
6620 struct io io;
6621 int argc = 3;
6623 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6624 if (!diff_hdr)
6625 return FALSE;
6627 if (!revert)
6628 apply_argv[argc++] = "--cached";
6629 if (line != NULL)
6630 apply_argv[argc++] = "--unidiff-zero";
6631 if (revert || stage_line_type == LINE_STAT_STAGED)
6632 apply_argv[argc++] = "-R";
6633 apply_argv[argc++] = "-";
6634 apply_argv[argc++] = NULL;
6635 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6636 return FALSE;
6638 if (line != NULL) {
6639 int lineno = 0;
6640 struct line *context = chunk + 1;
6641 const char *markers[] = {
6642 line->type == LINE_DIFF_DEL ? "" : ",0",
6643 line->type == LINE_DIFF_DEL ? ",0" : "",
6646 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6648 while (context < line) {
6649 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6650 break;
6651 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6652 lineno++;
6654 context++;
6657 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6658 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6659 lineno, markers[0], lineno, markers[1]) ||
6660 !stage_diff_write(&io, line, line + 1)) {
6661 chunk = NULL;
6663 } else {
6664 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6665 !stage_diff_write(&io, chunk, view->line + view->lines))
6666 chunk = NULL;
6669 io_done(&io);
6670 io_run_bg(update_index_argv);
6672 return chunk ? TRUE : FALSE;
6675 static bool
6676 stage_update(struct view *view, struct line *line, bool single)
6678 struct line *chunk = NULL;
6680 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6681 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6683 if (chunk) {
6684 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6685 report("Failed to apply chunk");
6686 return FALSE;
6689 } else if (!stage_status.status) {
6690 view = view->parent;
6692 for (line = view->line; view_has_line(view, line); line++)
6693 if (line->type == stage_line_type)
6694 break;
6696 if (!status_update_files(view, line + 1)) {
6697 report("Failed to update files");
6698 return FALSE;
6701 } else if (!status_update_file(&stage_status, stage_line_type)) {
6702 report("Failed to update file");
6703 return FALSE;
6706 return TRUE;
6709 static bool
6710 stage_revert(struct view *view, struct line *line)
6712 struct line *chunk = NULL;
6714 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6715 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6717 if (chunk) {
6718 if (!prompt_yesno("Are you sure you want to revert changes?"))
6719 return FALSE;
6721 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6722 report("Failed to revert chunk");
6723 return FALSE;
6725 return TRUE;
6727 } else {
6728 return status_revert(stage_status.status ? &stage_status : NULL,
6729 stage_line_type, FALSE);
6734 static void
6735 stage_next(struct view *view, struct line *line)
6737 struct stage_state *state = view->private;
6738 int i;
6740 if (!state->chunks) {
6741 for (line = view->line; view_has_line(view, line); line++) {
6742 if (line->type != LINE_DIFF_CHUNK)
6743 continue;
6745 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6746 report("Allocation failure");
6747 return;
6750 state->chunk[state->chunks++] = line - view->line;
6754 for (i = 0; i < state->chunks; i++) {
6755 if (state->chunk[i] > view->pos.lineno) {
6756 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6757 report("Chunk %d of %zd", i + 1, state->chunks);
6758 return;
6762 report("No next chunk found");
6765 static enum request
6766 stage_request(struct view *view, enum request request, struct line *line)
6768 switch (request) {
6769 case REQ_STATUS_UPDATE:
6770 if (!stage_update(view, line, FALSE))
6771 return REQ_NONE;
6772 break;
6774 case REQ_STATUS_REVERT:
6775 if (!stage_revert(view, line))
6776 return REQ_NONE;
6777 break;
6779 case REQ_STAGE_UPDATE_LINE:
6780 if (stage_line_type == LINE_STAT_UNTRACKED ||
6781 stage_status.status == 'A') {
6782 report("Staging single lines is not supported for new files");
6783 return REQ_NONE;
6785 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6786 report("Please select a change to stage");
6787 return REQ_NONE;
6789 if (!stage_update(view, line, TRUE))
6790 return REQ_NONE;
6791 break;
6793 case REQ_STAGE_NEXT:
6794 if (stage_line_type == LINE_STAT_UNTRACKED) {
6795 report("File is untracked; press %s to add",
6796 get_view_key(view, REQ_STATUS_UPDATE));
6797 return REQ_NONE;
6799 stage_next(view, line);
6800 return REQ_NONE;
6802 case REQ_EDIT:
6803 if (!stage_status.new.name[0])
6804 return request;
6805 if (stage_status.status == 'D') {
6806 report("File has been deleted.");
6807 return REQ_NONE;
6810 open_editor(stage_status.new.name);
6811 break;
6813 case REQ_REFRESH:
6814 /* Reload everything ... */
6815 break;
6817 case REQ_VIEW_BLAME:
6818 if (stage_status.new.name[0]) {
6819 string_copy(opt_file, stage_status.new.name);
6820 opt_ref[0] = 0;
6822 return request;
6824 case REQ_ENTER:
6825 return diff_common_enter(view, request, line);
6827 case REQ_DIFF_CONTEXT_UP:
6828 case REQ_DIFF_CONTEXT_DOWN:
6829 if (!update_diff_context(request))
6830 return REQ_NONE;
6831 break;
6833 default:
6834 return request;
6837 refresh_view(view->parent);
6839 /* Check whether the staged entry still exists, and close the
6840 * stage view if it doesn't. */
6841 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6842 status_restore(view->parent);
6843 return REQ_VIEW_CLOSE;
6846 refresh_view(view);
6848 return REQ_NONE;
6851 static bool
6852 stage_open(struct view *view, enum open_flags flags)
6854 static const char *no_head_diff_argv[] = {
6855 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6856 stage_status.new.name)
6858 static const char *index_show_argv[] = {
6859 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6860 stage_status.old.name, stage_status.new.name)
6862 static const char *files_show_argv[] = {
6863 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6864 stage_status.old.name, stage_status.new.name)
6866 /* Diffs for unmerged entries are empty when passing the new
6867 * path, so leave out the new path. */
6868 static const char *files_unmerged_argv[] = {
6869 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
6870 opt_diff_context_arg, opt_ignore_space_arg, "--",
6871 stage_status.old.name, NULL
6873 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6874 const char **argv = NULL;
6875 const char *info;
6877 if (!stage_line_type) {
6878 report("No stage content, press %s to open the status view and choose file",
6879 get_view_key(view, REQ_VIEW_STATUS));
6880 return FALSE;
6883 view->encoding = NULL;
6885 switch (stage_line_type) {
6886 case LINE_STAT_STAGED:
6887 if (is_initial_commit()) {
6888 argv = no_head_diff_argv;
6889 } else {
6890 argv = index_show_argv;
6892 if (stage_status.status)
6893 info = "Staged changes to %s";
6894 else
6895 info = "Staged changes";
6896 break;
6898 case LINE_STAT_UNSTAGED:
6899 if (stage_status.status != 'U')
6900 argv = files_show_argv;
6901 else
6902 argv = files_unmerged_argv;
6903 if (stage_status.status)
6904 info = "Unstaged changes to %s";
6905 else
6906 info = "Unstaged changes";
6907 break;
6909 case LINE_STAT_UNTRACKED:
6910 info = "Untracked file %s";
6911 argv = file_argv;
6912 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6913 break;
6915 case LINE_STAT_HEAD:
6916 default:
6917 die("line type %d not handled in switch", stage_line_type);
6920 if (!string_format(view->ref, info, stage_status.new.name)
6921 || !argv_copy(&view->argv, argv)) {
6922 report("Failed to open staged view");
6923 return FALSE;
6926 view->vid[0] = 0;
6927 view->dir = opt_cdup;
6928 return begin_update(view, NULL, NULL, flags);
6931 static bool
6932 stage_read(struct view *view, char *data)
6934 struct stage_state *state = view->private;
6936 if (data && diff_common_read(view, data, &state->diff))
6937 return TRUE;
6939 return pager_read(view, data);
6942 static struct view_ops stage_ops = {
6943 "line",
6944 { "stage" },
6945 VIEW_DIFF_LIKE,
6946 sizeof(struct stage_state),
6947 stage_open,
6948 stage_read,
6949 diff_common_draw,
6950 stage_request,
6951 pager_grep,
6952 pager_select,
6957 * Revision graph
6960 static const enum line_type graph_colors[] = {
6961 LINE_PALETTE_0,
6962 LINE_PALETTE_1,
6963 LINE_PALETTE_2,
6964 LINE_PALETTE_3,
6965 LINE_PALETTE_4,
6966 LINE_PALETTE_5,
6967 LINE_PALETTE_6,
6970 static enum line_type get_graph_color(struct graph_symbol *symbol)
6972 if (symbol->commit)
6973 return LINE_GRAPH_COMMIT;
6974 assert(symbol->color < ARRAY_SIZE(graph_colors));
6975 return graph_colors[symbol->color];
6978 static bool
6979 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6981 const char *chars = graph_symbol_to_utf8(symbol);
6983 return draw_text(view, color, chars + !!first);
6986 static bool
6987 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6989 const char *chars = graph_symbol_to_ascii(symbol);
6991 return draw_text(view, color, chars + !!first);
6994 static bool
6995 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6997 const chtype *chars = graph_symbol_to_chtype(symbol);
6999 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7002 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7004 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7006 static const draw_graph_fn fns[] = {
7007 draw_graph_ascii,
7008 draw_graph_chtype,
7009 draw_graph_utf8
7011 draw_graph_fn fn = fns[opt_line_graphics];
7012 int i;
7014 for (i = 0; i < canvas->size; i++) {
7015 struct graph_symbol *symbol = &canvas->symbols[i];
7016 enum line_type color = get_graph_color(symbol);
7018 if (fn(view, symbol, color, i == 0))
7019 return TRUE;
7022 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7026 * Main view backend
7029 struct commit {
7030 char id[SIZEOF_REV]; /* SHA1 ID. */
7031 char title[128]; /* First line of the commit message. */
7032 const char *author; /* Author of the commit. */
7033 struct time time; /* Date from the author ident. */
7034 struct ref_list *refs; /* Repository references. */
7035 struct graph_canvas graph; /* Ancestry chain graphics. */
7038 struct main_state {
7039 struct graph graph;
7040 struct commit *current;
7041 bool in_header;
7042 bool added_changes_commits;
7045 static struct commit *
7046 main_add_commit(struct view *view, enum line_type type, const char *ids,
7047 bool is_boundary, bool custom)
7049 struct main_state *state = view->private;
7050 struct commit *commit;
7052 if (!add_line_alloc(view, &commit, type, 0, custom))
7053 return NULL;
7055 string_copy_rev(commit->id, ids);
7056 commit->refs = get_ref_list(commit->id);
7057 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7058 return commit;
7061 bool
7062 main_has_changes(const char *argv[])
7064 struct io io;
7066 if (!io_run(&io, IO_BG, NULL, argv, -1))
7067 return FALSE;
7068 io_done(&io);
7069 return io.status == 1;
7072 static void
7073 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7075 char ids[SIZEOF_STR] = NULL_ID " ";
7076 struct main_state *state = view->private;
7077 struct commit *commit;
7078 struct timeval now;
7079 struct timezone tz;
7081 if (!parent)
7082 return;
7084 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7086 commit = main_add_commit(view, type, ids, FALSE, TRUE);
7087 if (!commit)
7088 return;
7090 if (!gettimeofday(&now, &tz)) {
7091 commit->time.tz = tz.tz_minuteswest * 60;
7092 commit->time.sec = now.tv_sec - commit->time.tz;
7095 commit->author = "";
7096 string_ncopy(commit->title, title, strlen(title));
7097 graph_render_parents(&state->graph);
7100 static void
7101 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7103 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7104 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7105 const char *staged_parent = NULL_ID;
7106 const char *unstaged_parent = parent;
7108 if (!is_head_commit(parent))
7109 return;
7111 state->added_changes_commits = TRUE;
7113 io_run_bg(update_index_argv);
7115 if (!main_has_changes(unstaged_argv)) {
7116 unstaged_parent = NULL;
7117 staged_parent = parent;
7120 if (!main_has_changes(staged_argv)) {
7121 staged_parent = NULL;
7124 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7125 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7128 static bool
7129 main_open(struct view *view, enum open_flags flags)
7131 static const char *main_argv[] = {
7132 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7135 return begin_update(view, NULL, main_argv, flags);
7138 static bool
7139 main_draw(struct view *view, struct line *line, unsigned int lineno)
7141 struct commit *commit = line->data;
7143 if (!commit->author)
7144 return FALSE;
7146 if (draw_lineno(view, lineno))
7147 return TRUE;
7149 if (opt_show_id && draw_id(view, LINE_ID, commit->id))
7150 return TRUE;
7152 if (draw_date(view, &commit->time))
7153 return TRUE;
7155 if (draw_author(view, commit->author))
7156 return TRUE;
7158 if (opt_rev_graph && draw_graph(view, &commit->graph))
7159 return TRUE;
7161 if (draw_refs(view, commit->refs))
7162 return TRUE;
7164 draw_text(view, LINE_DEFAULT, commit->title);
7165 return TRUE;
7168 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7169 static bool
7170 main_read(struct view *view, char *line)
7172 struct main_state *state = view->private;
7173 struct graph *graph = &state->graph;
7174 enum line_type type;
7175 struct commit *commit = state->current;
7177 if (!line) {
7178 if (!view->lines && !view->prev)
7179 die("No revisions match the given arguments.");
7180 if (view->lines > 0) {
7181 commit = view->line[view->lines - 1].data;
7182 view->line[view->lines - 1].dirty = 1;
7183 if (!commit->author) {
7184 view->lines--;
7185 free(commit);
7189 done_graph(graph);
7190 return TRUE;
7193 type = get_line_type(line);
7194 if (type == LINE_COMMIT) {
7195 bool is_boundary;
7197 state->in_header = TRUE;
7198 line += STRING_SIZE("commit ");
7199 is_boundary = *line == '-';
7200 if (is_boundary || !isalnum(*line))
7201 line++;
7203 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7204 main_add_changes_commits(view, state, line);
7206 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7207 return state->current != NULL;
7210 if (!view->lines || !commit)
7211 return TRUE;
7213 /* Empty line separates the commit header from the log itself. */
7214 if (*line == '\0')
7215 state->in_header = FALSE;
7217 switch (type) {
7218 case LINE_PARENT:
7219 if (!graph->has_parents)
7220 graph_add_parent(graph, line + STRING_SIZE("parent "));
7221 break;
7223 case LINE_AUTHOR:
7224 parse_author_line(line + STRING_SIZE("author "),
7225 &commit->author, &commit->time);
7226 graph_render_parents(graph);
7227 break;
7229 default:
7230 /* Fill in the commit title if it has not already been set. */
7231 if (commit->title[0])
7232 break;
7234 /* Skip lines in the commit header. */
7235 if (state->in_header)
7236 break;
7238 /* Require titles to start with a non-space character at the
7239 * offset used by git log. */
7240 if (strncmp(line, " ", 4))
7241 break;
7242 line += 4;
7243 /* Well, if the title starts with a whitespace character,
7244 * try to be forgiving. Otherwise we end up with no title. */
7245 while (isspace(*line))
7246 line++;
7247 if (*line == '\0')
7248 break;
7249 /* FIXME: More graceful handling of titles; append "..." to
7250 * shortened titles, etc. */
7252 string_expand(commit->title, sizeof(commit->title), line, 1);
7253 view->line[view->lines - 1].dirty = 1;
7256 return TRUE;
7259 static enum request
7260 main_request(struct view *view, enum request request, struct line *line)
7262 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7264 switch (request) {
7265 case REQ_NEXT:
7266 case REQ_PREVIOUS:
7267 if (view_is_displayed(view) && display[0] != view)
7268 return request;
7269 /* Do not pass navigation requests to the branch view
7270 * when the main view is maximized. (GH #38) */
7271 move_view(view, request);
7272 break;
7274 case REQ_ENTER:
7275 if (view_is_displayed(view) && display[0] != view)
7276 maximize_view(view, TRUE);
7278 if (line->type == LINE_STAT_UNSTAGED
7279 || line->type == LINE_STAT_STAGED) {
7280 struct view *diff = VIEW(REQ_VIEW_DIFF);
7281 const char *diff_staged_argv[] = {
7282 GIT_DIFF_STAGED(opt_encoding_arg,
7283 opt_diff_context_arg,
7284 opt_ignore_space_arg, NULL, NULL)
7286 const char *diff_unstaged_argv[] = {
7287 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7288 opt_diff_context_arg,
7289 opt_ignore_space_arg, NULL, NULL)
7291 const char **diff_argv = line->type == LINE_STAT_STAGED
7292 ? diff_staged_argv : diff_unstaged_argv;
7294 open_argv(view, diff, diff_argv, NULL, flags);
7295 break;
7298 open_view(view, REQ_VIEW_DIFF, flags);
7299 break;
7300 case REQ_REFRESH:
7301 load_refs();
7302 refresh_view(view);
7303 break;
7305 case REQ_JUMP_COMMIT:
7307 int lineno;
7309 for (lineno = 0; lineno < view->lines; lineno++) {
7310 struct commit *commit = view->line[lineno].data;
7312 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7313 select_view_line(view, lineno);
7314 report_clear();
7315 return REQ_NONE;
7319 report("Unable to find commit '%s'", opt_search);
7320 break;
7322 default:
7323 return request;
7326 return REQ_NONE;
7329 static bool
7330 grep_refs(struct ref_list *list, regex_t *regex)
7332 regmatch_t pmatch;
7333 size_t i;
7335 if (!opt_show_refs || !list)
7336 return FALSE;
7338 for (i = 0; i < list->size; i++) {
7339 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7340 return TRUE;
7343 return FALSE;
7346 static bool
7347 main_grep(struct view *view, struct line *line)
7349 struct commit *commit = line->data;
7350 const char *text[] = {
7351 commit->id,
7352 commit->title,
7353 mkauthor(commit->author, opt_author_width, opt_author),
7354 mkdate(&commit->time, opt_date),
7355 NULL
7358 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7361 static void
7362 main_select(struct view *view, struct line *line)
7364 struct commit *commit = line->data;
7366 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7367 string_copy(view->ref, commit->title);
7368 else
7369 string_copy_rev(view->ref, commit->id);
7370 string_copy_rev(ref_commit, commit->id);
7373 static struct view_ops main_ops = {
7374 "commit",
7375 { "main" },
7376 VIEW_NO_FLAGS,
7377 sizeof(struct main_state),
7378 main_open,
7379 main_read,
7380 main_draw,
7381 main_request,
7382 main_grep,
7383 main_select,
7388 * Status management
7391 /* Whether or not the curses interface has been initialized. */
7392 static bool cursed = FALSE;
7394 /* Terminal hacks and workarounds. */
7395 static bool use_scroll_redrawwin;
7396 static bool use_scroll_status_wclear;
7398 /* The status window is used for polling keystrokes. */
7399 static WINDOW *status_win;
7401 /* Reading from the prompt? */
7402 static bool input_mode = FALSE;
7404 static bool status_empty = FALSE;
7406 /* Update status and title window. */
7407 static void
7408 report(const char *msg, ...)
7410 struct view *view = display[current_view];
7412 if (input_mode)
7413 return;
7415 if (!view) {
7416 char buf[SIZEOF_STR];
7417 int retval;
7419 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7420 die("%s", buf);
7423 if (!status_empty || *msg) {
7424 va_list args;
7426 va_start(args, msg);
7428 wmove(status_win, 0, 0);
7429 if (view->has_scrolled && use_scroll_status_wclear)
7430 wclear(status_win);
7431 if (*msg) {
7432 vwprintw(status_win, msg, args);
7433 status_empty = FALSE;
7434 } else {
7435 status_empty = TRUE;
7437 wclrtoeol(status_win);
7438 wnoutrefresh(status_win);
7440 va_end(args);
7443 update_view_title(view);
7446 static void
7447 init_display(void)
7449 const char *term;
7450 int x, y;
7452 /* Initialize the curses library */
7453 if (isatty(STDIN_FILENO)) {
7454 cursed = !!initscr();
7455 opt_tty = stdin;
7456 } else {
7457 /* Leave stdin and stdout alone when acting as a pager. */
7458 opt_tty = fopen("/dev/tty", "r+");
7459 if (!opt_tty)
7460 die("Failed to open /dev/tty");
7461 cursed = !!newterm(NULL, opt_tty, opt_tty);
7464 if (!cursed)
7465 die("Failed to initialize curses");
7467 nonl(); /* Disable conversion and detect newlines from input. */
7468 cbreak(); /* Take input chars one at a time, no wait for \n */
7469 noecho(); /* Don't echo input */
7470 leaveok(stdscr, FALSE);
7472 if (has_colors())
7473 init_colors();
7475 getmaxyx(stdscr, y, x);
7476 status_win = newwin(1, x, y - 1, 0);
7477 if (!status_win)
7478 die("Failed to create status window");
7480 /* Enable keyboard mapping */
7481 keypad(status_win, TRUE);
7482 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7484 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7485 set_tabsize(opt_tab_size);
7486 #else
7487 TABSIZE = opt_tab_size;
7488 #endif
7490 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7491 if (term && !strcmp(term, "gnome-terminal")) {
7492 /* In the gnome-terminal-emulator, the message from
7493 * scrolling up one line when impossible followed by
7494 * scrolling down one line causes corruption of the
7495 * status line. This is fixed by calling wclear. */
7496 use_scroll_status_wclear = TRUE;
7497 use_scroll_redrawwin = FALSE;
7499 } else if (term && !strcmp(term, "xrvt-xpm")) {
7500 /* No problems with full optimizations in xrvt-(unicode)
7501 * and aterm. */
7502 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7504 } else {
7505 /* When scrolling in (u)xterm the last line in the
7506 * scrolling direction will update slowly. */
7507 use_scroll_redrawwin = TRUE;
7508 use_scroll_status_wclear = FALSE;
7512 static int
7513 get_input(int prompt_position)
7515 struct view *view;
7516 int i, key, cursor_y, cursor_x;
7518 if (prompt_position)
7519 input_mode = TRUE;
7521 while (TRUE) {
7522 bool loading = FALSE;
7524 foreach_view (view, i) {
7525 update_view(view);
7526 if (view_is_displayed(view) && view->has_scrolled &&
7527 use_scroll_redrawwin)
7528 redrawwin(view->win);
7529 view->has_scrolled = FALSE;
7530 if (view->pipe)
7531 loading = TRUE;
7534 /* Update the cursor position. */
7535 if (prompt_position) {
7536 getbegyx(status_win, cursor_y, cursor_x);
7537 cursor_x = prompt_position;
7538 } else {
7539 view = display[current_view];
7540 getbegyx(view->win, cursor_y, cursor_x);
7541 cursor_x = view->width - 1;
7542 cursor_y += view->pos.lineno - view->pos.offset;
7544 setsyx(cursor_y, cursor_x);
7546 /* Refresh, accept single keystroke of input */
7547 doupdate();
7548 nodelay(status_win, loading);
7549 key = wgetch(status_win);
7551 /* wgetch() with nodelay() enabled returns ERR when
7552 * there's no input. */
7553 if (key == ERR) {
7555 } else if (key == KEY_RESIZE) {
7556 int height, width;
7558 getmaxyx(stdscr, height, width);
7560 wresize(status_win, 1, width);
7561 mvwin(status_win, height - 1, 0);
7562 wnoutrefresh(status_win);
7563 resize_display();
7564 redraw_display(TRUE);
7566 } else {
7567 input_mode = FALSE;
7568 if (key == erasechar())
7569 key = KEY_BACKSPACE;
7570 return key;
7575 static char *
7576 prompt_input(const char *prompt, input_handler handler, void *data)
7578 enum input_status status = INPUT_OK;
7579 static char buf[SIZEOF_STR];
7580 size_t pos = 0;
7582 buf[pos] = 0;
7584 while (status == INPUT_OK || status == INPUT_SKIP) {
7585 int key;
7587 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7588 wclrtoeol(status_win);
7590 key = get_input(pos + 1);
7591 switch (key) {
7592 case KEY_RETURN:
7593 case KEY_ENTER:
7594 case '\n':
7595 status = pos ? INPUT_STOP : INPUT_CANCEL;
7596 break;
7598 case KEY_BACKSPACE:
7599 if (pos > 0)
7600 buf[--pos] = 0;
7601 else
7602 status = INPUT_CANCEL;
7603 break;
7605 case KEY_ESC:
7606 status = INPUT_CANCEL;
7607 break;
7609 default:
7610 if (pos >= sizeof(buf)) {
7611 report("Input string too long");
7612 return NULL;
7615 status = handler(data, buf, key);
7616 if (status == INPUT_OK)
7617 buf[pos++] = (char) key;
7621 /* Clear the status window */
7622 status_empty = FALSE;
7623 report_clear();
7625 if (status == INPUT_CANCEL)
7626 return NULL;
7628 buf[pos++] = 0;
7630 return buf;
7633 static enum input_status
7634 prompt_yesno_handler(void *data, char *buf, int c)
7636 if (c == 'y' || c == 'Y')
7637 return INPUT_STOP;
7638 if (c == 'n' || c == 'N')
7639 return INPUT_CANCEL;
7640 return INPUT_SKIP;
7643 static bool
7644 prompt_yesno(const char *prompt)
7646 char prompt2[SIZEOF_STR];
7648 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7649 return FALSE;
7651 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7654 static enum input_status
7655 read_prompt_handler(void *data, char *buf, int c)
7657 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7660 static char *
7661 read_prompt(const char *prompt)
7663 return prompt_input(prompt, read_prompt_handler, NULL);
7666 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7668 enum input_status status = INPUT_OK;
7669 int size = 0;
7671 while (items[size].text)
7672 size++;
7674 assert(size > 0);
7676 while (status == INPUT_OK) {
7677 const struct menu_item *item = &items[*selected];
7678 int key;
7679 int i;
7681 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7682 prompt, *selected + 1, size);
7683 if (item->hotkey)
7684 wprintw(status_win, "[%c] ", (char) item->hotkey);
7685 wprintw(status_win, "%s", item->text);
7686 wclrtoeol(status_win);
7688 key = get_input(COLS - 1);
7689 switch (key) {
7690 case KEY_RETURN:
7691 case KEY_ENTER:
7692 case '\n':
7693 status = INPUT_STOP;
7694 break;
7696 case KEY_LEFT:
7697 case KEY_UP:
7698 *selected = *selected - 1;
7699 if (*selected < 0)
7700 *selected = size - 1;
7701 break;
7703 case KEY_RIGHT:
7704 case KEY_DOWN:
7705 *selected = (*selected + 1) % size;
7706 break;
7708 case KEY_ESC:
7709 status = INPUT_CANCEL;
7710 break;
7712 default:
7713 for (i = 0; items[i].text; i++)
7714 if (items[i].hotkey == key) {
7715 *selected = i;
7716 status = INPUT_STOP;
7717 break;
7722 /* Clear the status window */
7723 status_empty = FALSE;
7724 report_clear();
7726 return status != INPUT_CANCEL;
7730 * Repository properties
7734 static void
7735 set_remote_branch(const char *name, const char *value, size_t valuelen)
7737 if (!strcmp(name, ".remote")) {
7738 string_ncopy(opt_remote, value, valuelen);
7740 } else if (*opt_remote && !strcmp(name, ".merge")) {
7741 size_t from = strlen(opt_remote);
7743 if (!prefixcmp(value, "refs/heads/"))
7744 value += STRING_SIZE("refs/heads/");
7746 if (!string_format_from(opt_remote, &from, "/%s", value))
7747 opt_remote[0] = 0;
7751 static void
7752 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7754 const char *argv[SIZEOF_ARG] = { name, "=" };
7755 int argc = 1 + (cmd == option_set_command);
7756 enum option_code error;
7758 if (!argv_from_string(argv, &argc, value))
7759 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7760 else
7761 error = cmd(argc, argv);
7763 if (error != OPT_OK)
7764 warn("Option 'tig.%s': %s", name, option_errors[error]);
7767 static bool
7768 set_environment_variable(const char *name, const char *value)
7770 size_t len = strlen(name) + 1 + strlen(value) + 1;
7771 char *env = malloc(len);
7773 if (env &&
7774 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7775 putenv(env) == 0)
7776 return TRUE;
7777 free(env);
7778 return FALSE;
7781 static void
7782 set_work_tree(const char *value)
7784 char cwd[SIZEOF_STR];
7786 if (!getcwd(cwd, sizeof(cwd)))
7787 die("Failed to get cwd path: %s", strerror(errno));
7788 if (chdir(cwd) < 0)
7789 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7790 if (chdir(opt_git_dir) < 0)
7791 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
7792 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7793 die("Failed to get git path: %s", strerror(errno));
7794 if (chdir(value) < 0)
7795 die("Failed to chdir(%s): %s", value, strerror(errno));
7796 if (!getcwd(cwd, sizeof(cwd)))
7797 die("Failed to get cwd path: %s", strerror(errno));
7798 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7799 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7800 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7801 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7802 opt_is_inside_work_tree = TRUE;
7805 static void
7806 parse_git_color_option(enum line_type type, char *value)
7808 struct line_info *info = &line_info[type];
7809 const char *argv[SIZEOF_ARG];
7810 int argc = 0;
7811 bool first_color = TRUE;
7812 int i;
7814 if (!argv_from_string(argv, &argc, value))
7815 return;
7817 info->fg = COLOR_DEFAULT;
7818 info->bg = COLOR_DEFAULT;
7819 info->attr = 0;
7821 for (i = 0; i < argc; i++) {
7822 int attr = 0;
7824 if (set_attribute(&attr, argv[i])) {
7825 info->attr |= attr;
7827 } else if (set_color(&attr, argv[i])) {
7828 if (first_color)
7829 info->fg = attr;
7830 else
7831 info->bg = attr;
7832 first_color = FALSE;
7837 static void
7838 set_git_color_option(const char *name, char *value)
7840 static const struct enum_map color_option_map[] = {
7841 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7842 ENUM_MAP("branch.local", LINE_MAIN_REF),
7843 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7844 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7846 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7847 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7848 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7849 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7850 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7851 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7852 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7854 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7856 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7857 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7858 ENUM_MAP("status.added", LINE_STAT_STAGED),
7859 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7860 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7861 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7864 int type = LINE_NONE;
7866 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7867 parse_git_color_option(type, value);
7871 static void
7872 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
7874 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
7875 opt_encoding_arg[0] = 0;
7878 static int
7879 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7881 if (!strcmp(name, "i18n.commitencoding"))
7882 set_encoding(&opt_encoding, value, FALSE);
7884 else if (!strcmp(name, "gui.encoding"))
7885 set_encoding(&opt_encoding, value, TRUE);
7887 else if (!strcmp(name, "core.editor"))
7888 string_ncopy(opt_editor, value, valuelen);
7890 else if (!strcmp(name, "core.worktree"))
7891 set_work_tree(value);
7893 else if (!strcmp(name, "core.abbrev"))
7894 parse_id(&opt_id_cols, value);
7896 else if (!prefixcmp(name, "tig.color."))
7897 set_repo_config_option(name + 10, value, option_color_command);
7899 else if (!prefixcmp(name, "tig.bind."))
7900 set_repo_config_option(name + 9, value, option_bind_command);
7902 else if (!prefixcmp(name, "tig."))
7903 set_repo_config_option(name + 4, value, option_set_command);
7905 else if (!prefixcmp(name, "color."))
7906 set_git_color_option(name + STRING_SIZE("color."), value);
7908 else if (*opt_head && !prefixcmp(name, "branch.") &&
7909 !strncmp(name + 7, opt_head, strlen(opt_head)))
7910 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7912 return OK;
7915 static int
7916 load_git_config(void)
7918 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7920 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7923 static int
7924 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7926 if (!opt_git_dir[0]) {
7927 string_ncopy(opt_git_dir, name, namelen);
7929 } else if (opt_is_inside_work_tree == -1) {
7930 /* This can be 3 different values depending on the
7931 * version of git being used. If git-rev-parse does not
7932 * understand --is-inside-work-tree it will simply echo
7933 * the option else either "true" or "false" is printed.
7934 * Default to true for the unknown case. */
7935 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7937 } else if (*name == '.') {
7938 string_ncopy(opt_cdup, name, namelen);
7940 } else {
7941 string_ncopy(opt_prefix, name, namelen);
7944 return OK;
7947 static int
7948 load_repo_info(void)
7950 const char *rev_parse_argv[] = {
7951 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7952 "--show-cdup", "--show-prefix", NULL
7955 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7960 * Main
7963 static const char usage[] =
7964 "tig " TIG_VERSION " (" __DATE__ ")\n"
7965 "\n"
7966 "Usage: tig [options] [revs] [--] [paths]\n"
7967 " or: tig show [options] [revs] [--] [paths]\n"
7968 " or: tig blame [options] [rev] [--] path\n"
7969 " or: tig status\n"
7970 " or: tig < [git command output]\n"
7971 "\n"
7972 "Options:\n"
7973 " +<number> Select line <number> in the first view\n"
7974 " -v, --version Show version and exit\n"
7975 " -h, --help Show help message and exit";
7977 static void __NORETURN
7978 quit(int sig)
7980 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7981 if (cursed)
7982 endwin();
7983 exit(0);
7986 static void __NORETURN
7987 die(const char *err, ...)
7989 va_list args;
7991 endwin();
7993 va_start(args, err);
7994 fputs("tig: ", stderr);
7995 vfprintf(stderr, err, args);
7996 fputs("\n", stderr);
7997 va_end(args);
7999 exit(1);
8002 static void
8003 warn(const char *msg, ...)
8005 va_list args;
8007 va_start(args, msg);
8008 fputs("tig warning: ", stderr);
8009 vfprintf(stderr, msg, args);
8010 fputs("\n", stderr);
8011 va_end(args);
8014 static int
8015 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8017 const char ***filter_args = data;
8019 return argv_append(filter_args, name) ? OK : ERR;
8022 static void
8023 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8025 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8026 const char **all_argv = NULL;
8028 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8029 !argv_append_array(&all_argv, argv) ||
8030 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8031 die("Failed to split arguments");
8032 argv_free(all_argv);
8033 free(all_argv);
8036 static void
8037 filter_options(const char *argv[], bool blame)
8039 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8041 if (blame)
8042 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
8043 else
8044 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
8046 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8049 static enum request
8050 parse_options(int argc, const char *argv[])
8052 enum request request = REQ_VIEW_MAIN;
8053 const char *subcommand;
8054 bool seen_dashdash = FALSE;
8055 const char **filter_argv = NULL;
8056 int i;
8058 if (!isatty(STDIN_FILENO))
8059 return REQ_VIEW_PAGER;
8061 if (argc <= 1)
8062 return REQ_VIEW_MAIN;
8064 subcommand = argv[1];
8065 if (!strcmp(subcommand, "status")) {
8066 if (argc > 2)
8067 warn("ignoring arguments after `%s'", subcommand);
8068 return REQ_VIEW_STATUS;
8070 } else if (!strcmp(subcommand, "blame")) {
8071 request = REQ_VIEW_BLAME;
8073 } else if (!strcmp(subcommand, "show")) {
8074 request = REQ_VIEW_DIFF;
8076 } else {
8077 subcommand = NULL;
8080 for (i = 1 + !!subcommand; i < argc; i++) {
8081 const char *opt = argv[i];
8083 // stop parsing our options after -- and let rev-parse handle the rest
8084 if (!seen_dashdash) {
8085 if (!strcmp(opt, "--")) {
8086 seen_dashdash = TRUE;
8087 continue;
8089 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8090 printf("tig version %s\n", TIG_VERSION);
8091 quit(0);
8093 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8094 printf("%s\n", usage);
8095 quit(0);
8097 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8098 opt_lineno = atoi(opt + 1);
8099 continue;
8104 if (!argv_append(&filter_argv, opt))
8105 die("command too long");
8108 if (filter_argv)
8109 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8111 /* Finish validating and setting up blame options */
8112 if (request == REQ_VIEW_BLAME) {
8113 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8114 die("invalid number of options to blame\n\n%s", usage);
8116 if (opt_rev_argv) {
8117 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8120 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8123 return request;
8127 main(int argc, const char *argv[])
8129 const char *codeset = ENCODING_UTF8;
8130 enum request request = parse_options(argc, argv);
8131 struct view *view;
8132 int i;
8134 signal(SIGINT, quit);
8135 signal(SIGPIPE, SIG_IGN);
8137 if (setlocale(LC_ALL, "")) {
8138 codeset = nl_langinfo(CODESET);
8141 foreach_view(view, i) {
8142 add_keymap(&view->ops->keymap);
8145 if (load_repo_info() == ERR)
8146 die("Failed to load repo info.");
8148 if (load_options() == ERR)
8149 die("Failed to load user config.");
8151 if (load_git_config() == ERR)
8152 die("Failed to load repo config.");
8154 /* Require a git repository unless when running in pager mode. */
8155 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8156 die("Not a git repository");
8158 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8159 char translit[SIZEOF_STR];
8161 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8162 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8163 else
8164 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8165 if (opt_iconv_out == ICONV_NONE)
8166 die("Failed to initialize character set conversion");
8169 if (load_refs() == ERR)
8170 die("Failed to load refs.");
8172 init_display();
8174 while (view_driver(display[current_view], request)) {
8175 int key = get_input(0);
8177 view = display[current_view];
8178 request = get_keybinding(&view->ops->keymap, key);
8180 /* Some low-level request handling. This keeps access to
8181 * status_win restricted. */
8182 switch (request) {
8183 case REQ_NONE:
8184 report("Unknown key, press %s for help",
8185 get_view_key(view, REQ_VIEW_HELP));
8186 break;
8187 case REQ_PROMPT:
8189 char *cmd = read_prompt(":");
8191 if (cmd && string_isnumber(cmd)) {
8192 int lineno = view->pos.lineno + 1;
8194 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8195 select_view_line(view, lineno - 1);
8196 report_clear();
8197 } else {
8198 report("Unable to parse '%s' as a line number", cmd);
8200 } else if (cmd && iscommit(cmd)) {
8201 string_ncopy(opt_search, cmd, strlen(cmd));
8203 request = view_request(view, REQ_JUMP_COMMIT);
8204 if (request == REQ_JUMP_COMMIT) {
8205 report("Jumping to commits is not supported by the '%s' view", view->name);
8208 } else if (cmd && strlen(cmd) == 1) {
8209 request = get_keybinding(&view->ops->keymap, cmd[0]);
8210 break;
8212 } else if (cmd && cmd[0] == '!') {
8213 struct view *next = VIEW(REQ_VIEW_PAGER);
8214 const char *argv[SIZEOF_ARG];
8215 int argc = 0;
8217 cmd++;
8218 /* When running random commands, initially show the
8219 * command in the title. However, it maybe later be
8220 * overwritten if a commit line is selected. */
8221 string_ncopy(next->ref, cmd, strlen(cmd));
8223 if (!argv_from_string(argv, &argc, cmd)) {
8224 report("Too many arguments");
8225 } else if (!format_argv(&next->argv, argv, FALSE)) {
8226 report("Argument formatting failed");
8227 } else {
8228 next->dir = NULL;
8229 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8232 } else if (cmd) {
8233 request = get_request(cmd);
8234 if (request != REQ_UNKNOWN)
8235 break;
8237 char *args = strchr(cmd, ' ');
8238 if (args) {
8239 *args++ = 0;
8240 if (set_option(cmd, args) == OPT_OK) {
8241 request = REQ_SCREEN_REDRAW;
8242 if (!strcmp(cmd, "color"))
8243 init_colors();
8246 break;
8249 request = REQ_NONE;
8250 break;
8252 case REQ_SEARCH:
8253 case REQ_SEARCH_BACK:
8255 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8256 char *search = read_prompt(prompt);
8258 if (search)
8259 string_ncopy(opt_search, search, strlen(search));
8260 else if (*opt_search)
8261 request = request == REQ_SEARCH ?
8262 REQ_FIND_NEXT :
8263 REQ_FIND_PREV;
8264 else
8265 request = REQ_NONE;
8266 break;
8268 default:
8269 break;
8273 quit(0);
8275 return 0;