Read commit IDs from stdin when opened with --stdin
[tig.git] / tig.c
blob0bcbfc8892dbc44640b1d25ae1527ea160aa1b3d
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 bool opt_stdin = FALSE;
408 static int opt_diff_context = 3;
409 static char opt_diff_context_arg[9] = "";
410 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
411 static char opt_ignore_space_arg[22] = "";
412 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
413 static char opt_commit_order_arg[22] = "";
414 static bool opt_notes = TRUE;
415 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
416 static int opt_num_interval = 5;
417 static double opt_hscroll = 0.50;
418 static double opt_scale_split_view = 2.0 / 3.0;
419 static double opt_scale_vsplit_view = 0.5;
420 static bool opt_vsplit = FALSE;
421 static int opt_tab_size = 8;
422 static int opt_author_width = AUTHOR_WIDTH;
423 static int opt_filename_width = FILENAME_WIDTH;
424 static char opt_path[SIZEOF_STR] = "";
425 static char opt_file[SIZEOF_STR] = "";
426 static char opt_ref[SIZEOF_REF] = "";
427 static unsigned long opt_goto_line = 0;
428 static char opt_head[SIZEOF_REF] = "";
429 static char opt_remote[SIZEOF_REF] = "";
430 static struct encoding *opt_encoding = NULL;
431 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
432 static iconv_t opt_iconv_out = ICONV_NONE;
433 static char opt_search[SIZEOF_STR] = "";
434 static char opt_cdup[SIZEOF_STR] = "";
435 static char opt_prefix[SIZEOF_STR] = "";
436 static char opt_git_dir[SIZEOF_STR] = "";
437 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
438 static char opt_editor[SIZEOF_STR] = "";
439 static FILE *opt_tty = NULL;
440 static const char **opt_diff_argv = NULL;
441 static const char **opt_rev_argv = NULL;
442 static const char **opt_file_argv = NULL;
443 static const char **opt_blame_argv = NULL;
444 static int opt_lineno = 0;
445 static bool opt_show_id = FALSE;
446 static int opt_id_cols = ID_WIDTH;
448 #define is_initial_commit() (!get_ref_head())
449 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
450 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
452 static inline void
453 update_diff_context_arg(int diff_context)
455 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
456 string_ncopy(opt_diff_context_arg, "-U3", 3);
459 static inline void
460 update_ignore_space_arg()
462 if (opt_ignore_space == IGNORE_SPACE_ALL) {
463 string_copy(opt_ignore_space_arg, "--ignore-all-space");
464 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
465 string_copy(opt_ignore_space_arg, "--ignore-space-change");
466 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
467 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
468 } else {
469 string_copy(opt_ignore_space_arg, "");
473 static inline void
474 update_commit_order_arg()
476 if (opt_commit_order == COMMIT_ORDER_TOPO) {
477 string_copy(opt_commit_order_arg, "--topo-order");
478 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
479 string_copy(opt_commit_order_arg, "--date-order");
480 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
481 string_copy(opt_commit_order_arg, "--reverse");
482 } else {
483 string_copy(opt_commit_order_arg, "");
487 static inline void
488 update_notes_arg()
490 if (opt_notes) {
491 string_copy(opt_notes_arg, "--show-notes");
492 } else {
493 /* Notes are disabled by default when passing --pretty args. */
494 string_copy(opt_notes_arg, "");
499 * Line-oriented content detection.
502 #define LINE_INFO \
503 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
505 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
506 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
507 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
508 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
509 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
510 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
511 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
512 LINE(DIFF_DELETED_FILE_MODE, \
513 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
514 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
515 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
517 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
518 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
519 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
520 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
521 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
522 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
523 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
524 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
527 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
528 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
529 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
530 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
531 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
532 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
533 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
534 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
537 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
538 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
539 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
540 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
541 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
542 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
543 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
544 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
545 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
546 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
547 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
548 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
549 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
550 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
551 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
552 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
553 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
554 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
555 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
556 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
557 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
558 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
559 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
560 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
561 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
562 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
563 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
564 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
565 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
566 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
567 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
568 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
569 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
570 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
571 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
572 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
573 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
574 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
575 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
576 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
578 enum line_type {
579 #define LINE(type, line, fg, bg, attr) \
580 LINE_##type
581 LINE_INFO,
582 LINE_NONE
583 #undef LINE
586 struct line_info {
587 const char *name; /* Option name. */
588 int namelen; /* Size of option name. */
589 const char *line; /* The start of line to match. */
590 int linelen; /* Size of string to match. */
591 int fg, bg, attr; /* Color and text attributes for the lines. */
592 int color_pair;
595 static struct line_info line_info[] = {
596 #define LINE(type, line, fg, bg, attr) \
597 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
598 LINE_INFO
599 #undef LINE
602 static struct line_info **color_pair;
603 static size_t color_pairs;
605 static struct line_info *custom_color;
606 static size_t custom_colors;
608 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
609 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
611 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
612 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
614 /* Color IDs must be 1 or higher. [GH #15] */
615 #define COLOR_ID(line_type) ((line_type) + 1)
617 static enum line_type
618 get_line_type(const char *line)
620 int linelen = strlen(line);
621 enum line_type type;
623 for (type = 0; type < custom_colors; type++)
624 /* Case insensitive search matches Signed-off-by lines better. */
625 if (linelen >= custom_color[type].linelen &&
626 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
627 return TO_CUSTOM_COLOR_TYPE(type);
629 for (type = 0; type < ARRAY_SIZE(line_info); type++)
630 /* Case insensitive search matches Signed-off-by lines better. */
631 if (linelen >= line_info[type].linelen &&
632 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
633 return type;
635 return LINE_DEFAULT;
638 static enum line_type
639 get_line_type_from_ref(const struct ref *ref)
641 if (ref->head)
642 return LINE_MAIN_HEAD;
643 else if (ref->ltag)
644 return LINE_MAIN_LOCAL_TAG;
645 else if (ref->tag)
646 return LINE_MAIN_TAG;
647 else if (ref->tracked)
648 return LINE_MAIN_TRACKED;
649 else if (ref->remote)
650 return LINE_MAIN_REMOTE;
651 else if (ref->replace)
652 return LINE_MAIN_REPLACE;
654 return LINE_MAIN_REF;
657 static inline struct line_info *
658 get_line(enum line_type type)
660 if (type > LINE_NONE) {
661 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
662 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
663 } else {
664 assert(type < ARRAY_SIZE(line_info));
665 return &line_info[type];
669 static inline int
670 get_line_color(enum line_type type)
672 return COLOR_ID(get_line(type)->color_pair);
675 static inline int
676 get_line_attr(enum line_type type)
678 struct line_info *info = get_line(type);
680 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
683 static struct line_info *
684 get_line_info(const char *name)
686 size_t namelen = strlen(name);
687 enum line_type type;
689 for (type = 0; type < ARRAY_SIZE(line_info); type++)
690 if (enum_equals(line_info[type], name, namelen))
691 return &line_info[type];
693 return NULL;
696 static struct line_info *
697 add_custom_color(const char *quoted_line)
699 struct line_info *info;
700 char *line;
701 size_t linelen;
703 if (!realloc_custom_color(&custom_color, custom_colors, 1))
704 die("Failed to alloc custom line info");
706 linelen = strlen(quoted_line) - 1;
707 line = malloc(linelen);
708 if (!line)
709 return NULL;
711 strncpy(line, quoted_line + 1, linelen);
712 line[linelen - 1] = 0;
714 info = &custom_color[custom_colors++];
715 info->name = info->line = line;
716 info->namelen = info->linelen = strlen(line);
718 return info;
721 static void
722 init_line_info_color_pair(struct line_info *info, enum line_type type,
723 int default_bg, int default_fg)
725 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
726 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
727 int i;
729 for (i = 0; i < color_pairs; i++) {
730 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
731 info->color_pair = i;
732 return;
736 if (!realloc_color_pair(&color_pair, color_pairs, 1))
737 die("Failed to alloc color pair");
739 color_pair[color_pairs] = info;
740 info->color_pair = color_pairs++;
741 init_pair(COLOR_ID(info->color_pair), fg, bg);
744 static void
745 init_colors(void)
747 int default_bg = line_info[LINE_DEFAULT].bg;
748 int default_fg = line_info[LINE_DEFAULT].fg;
749 enum line_type type;
751 start_color();
753 if (assume_default_colors(default_fg, default_bg) == ERR) {
754 default_bg = COLOR_BLACK;
755 default_fg = COLOR_WHITE;
758 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
759 struct line_info *info = &line_info[type];
761 init_line_info_color_pair(info, type, default_bg, default_fg);
764 for (type = 0; type < custom_colors; type++) {
765 struct line_info *info = &custom_color[type];
767 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
768 default_bg, default_fg);
772 struct line {
773 enum line_type type;
774 unsigned int lineno:24;
776 /* State flags */
777 unsigned int selected:1;
778 unsigned int dirty:1;
779 unsigned int cleareol:1;
780 unsigned int dont_free:1;
781 unsigned int wrapped:1;
783 void *data; /* User data */
788 * Keys
791 struct keybinding {
792 int alias;
793 enum request request;
796 static struct keybinding default_keybindings[] = {
797 /* View switching */
798 { 'm', REQ_VIEW_MAIN },
799 { 'd', REQ_VIEW_DIFF },
800 { 'l', REQ_VIEW_LOG },
801 { 't', REQ_VIEW_TREE },
802 { 'f', REQ_VIEW_BLOB },
803 { 'B', REQ_VIEW_BLAME },
804 { 'H', REQ_VIEW_BRANCH },
805 { 'p', REQ_VIEW_PAGER },
806 { 'h', REQ_VIEW_HELP },
807 { 'S', REQ_VIEW_STATUS },
808 { 'c', REQ_VIEW_STAGE },
810 /* View manipulation */
811 { 'q', REQ_VIEW_CLOSE },
812 { KEY_TAB, REQ_VIEW_NEXT },
813 { KEY_RETURN, REQ_ENTER },
814 { KEY_UP, REQ_PREVIOUS },
815 { KEY_CTL('P'), REQ_PREVIOUS },
816 { KEY_DOWN, REQ_NEXT },
817 { KEY_CTL('N'), REQ_NEXT },
818 { 'R', REQ_REFRESH },
819 { KEY_F(5), REQ_REFRESH },
820 { 'O', REQ_MAXIMIZE },
821 { ',', REQ_PARENT },
823 /* View specific */
824 { 'u', REQ_STATUS_UPDATE },
825 { '!', REQ_STATUS_REVERT },
826 { 'M', REQ_STATUS_MERGE },
827 { '1', REQ_STAGE_UPDATE_LINE },
828 { '@', REQ_STAGE_NEXT },
829 { '[', REQ_DIFF_CONTEXT_DOWN },
830 { ']', REQ_DIFF_CONTEXT_UP },
832 /* Cursor navigation */
833 { 'k', REQ_MOVE_UP },
834 { 'j', REQ_MOVE_DOWN },
835 { KEY_HOME, REQ_MOVE_FIRST_LINE },
836 { KEY_END, REQ_MOVE_LAST_LINE },
837 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
838 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
839 { ' ', REQ_MOVE_PAGE_DOWN },
840 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
841 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
842 { 'b', REQ_MOVE_PAGE_UP },
843 { '-', REQ_MOVE_PAGE_UP },
845 /* Scrolling */
846 { '|', REQ_SCROLL_FIRST_COL },
847 { KEY_LEFT, REQ_SCROLL_LEFT },
848 { KEY_RIGHT, REQ_SCROLL_RIGHT },
849 { KEY_IC, REQ_SCROLL_LINE_UP },
850 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
851 { KEY_DC, REQ_SCROLL_LINE_DOWN },
852 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
853 { 'w', REQ_SCROLL_PAGE_UP },
854 { 's', REQ_SCROLL_PAGE_DOWN },
856 /* Searching */
857 { '/', REQ_SEARCH },
858 { '?', REQ_SEARCH_BACK },
859 { 'n', REQ_FIND_NEXT },
860 { 'N', REQ_FIND_PREV },
862 /* Misc */
863 { 'Q', REQ_QUIT },
864 { 'z', REQ_STOP_LOADING },
865 { 'v', REQ_SHOW_VERSION },
866 { 'r', REQ_SCREEN_REDRAW },
867 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
868 { 'o', REQ_OPTIONS },
869 { '.', REQ_TOGGLE_LINENO },
870 { 'D', REQ_TOGGLE_DATE },
871 { 'A', REQ_TOGGLE_AUTHOR },
872 { 'g', REQ_TOGGLE_REV_GRAPH },
873 { '~', REQ_TOGGLE_GRAPHIC },
874 { '#', REQ_TOGGLE_FILENAME },
875 { 'F', REQ_TOGGLE_REFS },
876 { 'I', REQ_TOGGLE_SORT_ORDER },
877 { 'i', REQ_TOGGLE_SORT_FIELD },
878 { 'W', REQ_TOGGLE_IGNORE_SPACE },
879 { 'X', REQ_TOGGLE_ID },
880 { ':', REQ_PROMPT },
881 { 'e', REQ_EDIT },
884 struct keymap {
885 const char *name;
886 struct keymap *next;
887 struct keybinding *data;
888 size_t size;
889 bool hidden;
892 static struct keymap generic_keymap = { "generic" };
893 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
895 static struct keymap *keymaps = &generic_keymap;
897 static void
898 add_keymap(struct keymap *keymap)
900 keymap->next = keymaps;
901 keymaps = keymap;
904 static struct keymap *
905 get_keymap(const char *name)
907 struct keymap *keymap = keymaps;
909 while (keymap) {
910 if (!strcasecmp(keymap->name, name))
911 return keymap;
912 keymap = keymap->next;
915 return NULL;
919 static void
920 add_keybinding(struct keymap *table, enum request request, int key)
922 size_t i;
924 for (i = 0; i < table->size; i++) {
925 if (table->data[i].alias == key) {
926 table->data[i].request = request;
927 return;
931 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
932 if (!table->data)
933 die("Failed to allocate keybinding");
934 table->data[table->size].alias = key;
935 table->data[table->size++].request = request;
937 if (request == REQ_NONE && is_generic_keymap(table)) {
938 int i;
940 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
941 if (default_keybindings[i].alias == key)
942 default_keybindings[i].request = REQ_NONE;
946 /* Looks for a key binding first in the given map, then in the generic map, and
947 * lastly in the default keybindings. */
948 static enum request
949 get_keybinding(struct keymap *keymap, int key)
951 size_t i;
953 for (i = 0; i < keymap->size; i++)
954 if (keymap->data[i].alias == key)
955 return keymap->data[i].request;
957 for (i = 0; i < generic_keymap.size; i++)
958 if (generic_keymap.data[i].alias == key)
959 return generic_keymap.data[i].request;
961 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
962 if (default_keybindings[i].alias == key)
963 return default_keybindings[i].request;
965 return (enum request) key;
969 struct key {
970 const char *name;
971 int value;
974 static const struct key key_table[] = {
975 { "Enter", KEY_RETURN },
976 { "Space", ' ' },
977 { "Backspace", KEY_BACKSPACE },
978 { "Tab", KEY_TAB },
979 { "Escape", KEY_ESC },
980 { "Left", KEY_LEFT },
981 { "Right", KEY_RIGHT },
982 { "Up", KEY_UP },
983 { "Down", KEY_DOWN },
984 { "Insert", KEY_IC },
985 { "Delete", KEY_DC },
986 { "Hash", '#' },
987 { "Home", KEY_HOME },
988 { "End", KEY_END },
989 { "PageUp", KEY_PPAGE },
990 { "PageDown", KEY_NPAGE },
991 { "F1", KEY_F(1) },
992 { "F2", KEY_F(2) },
993 { "F3", KEY_F(3) },
994 { "F4", KEY_F(4) },
995 { "F5", KEY_F(5) },
996 { "F6", KEY_F(6) },
997 { "F7", KEY_F(7) },
998 { "F8", KEY_F(8) },
999 { "F9", KEY_F(9) },
1000 { "F10", KEY_F(10) },
1001 { "F11", KEY_F(11) },
1002 { "F12", KEY_F(12) },
1005 static int
1006 get_key_value(const char *name)
1008 int i;
1010 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1011 if (!strcasecmp(key_table[i].name, name))
1012 return key_table[i].value;
1014 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1015 return (int)name[1] & 0x1f;
1016 if (strlen(name) == 1 && isprint(*name))
1017 return (int) *name;
1018 return ERR;
1021 static const char *
1022 get_key_name(int key_value)
1024 static char key_char[] = "'X'\0";
1025 const char *seq = NULL;
1026 int key;
1028 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1029 if (key_table[key].value == key_value)
1030 seq = key_table[key].name;
1032 if (seq == NULL && key_value < 0x7f) {
1033 char *s = key_char + 1;
1035 if (key_value >= 0x20) {
1036 *s++ = key_value;
1037 } else {
1038 *s++ = '^';
1039 *s++ = 0x40 | (key_value & 0x1f);
1041 *s++ = '\'';
1042 *s++ = '\0';
1043 seq = key_char;
1046 return seq ? seq : "(no key)";
1049 static bool
1050 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1052 const char *sep = *pos > 0 ? ", " : "";
1053 const char *keyname = get_key_name(keybinding->alias);
1055 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1058 static bool
1059 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1060 struct keymap *keymap, bool all)
1062 int i;
1064 for (i = 0; i < keymap->size; i++) {
1065 if (keymap->data[i].request == request) {
1066 if (!append_key(buf, pos, &keymap->data[i]))
1067 return FALSE;
1068 if (!all)
1069 break;
1073 return TRUE;
1076 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1078 static const char *
1079 get_keys(struct keymap *keymap, enum request request, bool all)
1081 static char buf[BUFSIZ];
1082 size_t pos = 0;
1083 int i;
1085 buf[pos] = 0;
1087 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1088 return "Too many keybindings!";
1089 if (pos > 0 && !all)
1090 return buf;
1092 if (!is_generic_keymap(keymap)) {
1093 /* Only the generic keymap includes the default keybindings when
1094 * listing all keys. */
1095 if (all)
1096 return buf;
1098 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1099 return "Too many keybindings!";
1100 if (pos)
1101 return buf;
1104 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1105 if (default_keybindings[i].request == request) {
1106 if (!append_key(buf, &pos, &default_keybindings[i]))
1107 return "Too many keybindings!";
1108 if (!all)
1109 return buf;
1113 return buf;
1116 enum run_request_flag {
1117 RUN_REQUEST_DEFAULT = 0,
1118 RUN_REQUEST_FORCE = 1,
1119 RUN_REQUEST_SILENT = 2,
1120 RUN_REQUEST_CONFIRM = 4,
1121 RUN_REQUEST_EXIT = 8,
1124 struct run_request {
1125 struct keymap *keymap;
1126 int key;
1127 const char **argv;
1128 bool silent;
1129 bool confirm;
1130 bool exit;
1133 static struct run_request *run_request;
1134 static size_t run_requests;
1136 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1138 static bool
1139 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1141 bool force = flags & RUN_REQUEST_FORCE;
1142 struct run_request *req;
1144 if (!force && get_keybinding(keymap, key) != key)
1145 return TRUE;
1147 if (!realloc_run_requests(&run_request, run_requests, 1))
1148 return FALSE;
1150 if (!argv_copy(&run_request[run_requests].argv, argv))
1151 return FALSE;
1153 req = &run_request[run_requests++];
1154 req->silent = flags & RUN_REQUEST_SILENT;
1155 req->confirm = flags & RUN_REQUEST_CONFIRM;
1156 req->exit = flags & RUN_REQUEST_EXIT;
1157 req->keymap = keymap;
1158 req->key = key;
1160 add_keybinding(keymap, REQ_NONE + run_requests, key);
1161 return TRUE;
1164 static struct run_request *
1165 get_run_request(enum request request)
1167 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1168 return NULL;
1169 return &run_request[request - REQ_NONE - 1];
1172 static void
1173 add_builtin_run_requests(void)
1175 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1176 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1177 const char *commit[] = { "git", "commit", NULL };
1178 const char *gc[] = { "git", "gc", NULL };
1180 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1181 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1182 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1183 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1187 * User config file handling.
1190 #define OPT_ERR_INFO \
1191 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1192 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1193 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1194 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1195 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1196 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1197 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1198 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1199 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1200 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1201 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1202 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1203 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1204 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1205 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1206 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1207 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1208 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1210 enum option_code {
1211 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1212 OPT_ERR_INFO
1213 #undef OPT_ERR_
1214 OPT_OK
1217 static const char *option_errors[] = {
1218 #define OPT_ERR_(name, msg) msg
1219 OPT_ERR_INFO
1220 #undef OPT_ERR_
1223 static const struct enum_map color_map[] = {
1224 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1225 COLOR_MAP(DEFAULT),
1226 COLOR_MAP(BLACK),
1227 COLOR_MAP(BLUE),
1228 COLOR_MAP(CYAN),
1229 COLOR_MAP(GREEN),
1230 COLOR_MAP(MAGENTA),
1231 COLOR_MAP(RED),
1232 COLOR_MAP(WHITE),
1233 COLOR_MAP(YELLOW),
1236 static const struct enum_map attr_map[] = {
1237 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1238 ATTR_MAP(NORMAL),
1239 ATTR_MAP(BLINK),
1240 ATTR_MAP(BOLD),
1241 ATTR_MAP(DIM),
1242 ATTR_MAP(REVERSE),
1243 ATTR_MAP(STANDOUT),
1244 ATTR_MAP(UNDERLINE),
1247 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1249 static enum option_code
1250 parse_step(double *opt, const char *arg)
1252 *opt = atoi(arg);
1253 if (!strchr(arg, '%'))
1254 return OPT_OK;
1256 /* "Shift down" so 100% and 1 does not conflict. */
1257 *opt = (*opt - 1) / 100;
1258 if (*opt >= 1.0) {
1259 *opt = 0.99;
1260 return OPT_ERR_INVALID_STEP_VALUE;
1262 if (*opt < 0.0) {
1263 *opt = 1;
1264 return OPT_ERR_INVALID_STEP_VALUE;
1266 return OPT_OK;
1269 static enum option_code
1270 parse_int(int *opt, const char *arg, int min, int max)
1272 int value = atoi(arg);
1274 if (min <= value && value <= max) {
1275 *opt = value;
1276 return OPT_OK;
1279 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1282 #define parse_id(opt, arg) \
1283 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1285 static bool
1286 set_color(int *color, const char *name)
1288 if (map_enum(color, color_map, name))
1289 return TRUE;
1290 if (!prefixcmp(name, "color"))
1291 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1292 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1293 return parse_int(color, name, 0, 255) == OPT_OK;
1296 /* Wants: object fgcolor bgcolor [attribute] */
1297 static enum option_code
1298 option_color_command(int argc, const char *argv[])
1300 struct line_info *info;
1302 if (argc < 3)
1303 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1305 if (*argv[0] == '"' || *argv[0] == '\'') {
1306 info = add_custom_color(argv[0]);
1307 } else {
1308 info = get_line_info(argv[0]);
1310 if (!info) {
1311 static const struct enum_map obsolete[] = {
1312 ENUM_MAP("main-delim", LINE_DELIMITER),
1313 ENUM_MAP("main-date", LINE_DATE),
1314 ENUM_MAP("main-author", LINE_AUTHOR),
1315 ENUM_MAP("blame-id", LINE_ID),
1317 int index;
1319 if (!map_enum(&index, obsolete, argv[0]))
1320 return OPT_ERR_UNKNOWN_COLOR_NAME;
1321 info = &line_info[index];
1324 if (!set_color(&info->fg, argv[1]) ||
1325 !set_color(&info->bg, argv[2]))
1326 return OPT_ERR_UNKNOWN_COLOR;
1328 info->attr = 0;
1329 while (argc-- > 3) {
1330 int attr;
1332 if (!set_attribute(&attr, argv[argc]))
1333 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1334 info->attr |= attr;
1337 return OPT_OK;
1340 static enum option_code
1341 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1343 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1344 ? TRUE : FALSE;
1345 if (matched)
1346 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1347 return OPT_OK;
1350 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1352 static enum option_code
1353 parse_enum_do(unsigned int *opt, const char *arg,
1354 const struct enum_map *map, size_t map_size)
1356 bool is_true;
1358 assert(map_size > 1);
1360 if (map_enum_do(map, map_size, (int *) opt, arg))
1361 return OPT_OK;
1363 parse_bool(&is_true, arg);
1364 *opt = is_true ? map[1].value : map[0].value;
1365 return OPT_OK;
1368 #define parse_enum(opt, arg, map) \
1369 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1371 static enum option_code
1372 parse_string(char *opt, const char *arg, size_t optsize)
1374 int arglen = strlen(arg);
1376 switch (arg[0]) {
1377 case '\"':
1378 case '\'':
1379 if (arglen == 1 || arg[arglen - 1] != arg[0])
1380 return OPT_ERR_UNMATCHED_QUOTATION;
1381 arg += 1; arglen -= 2;
1382 default:
1383 string_ncopy_do(opt, optsize, arg, arglen);
1384 return OPT_OK;
1388 static enum option_code
1389 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1391 char buf[SIZEOF_STR];
1392 enum option_code code = parse_string(buf, arg, sizeof(buf));
1394 if (code == OPT_OK) {
1395 struct encoding *encoding = *encoding_ref;
1397 if (encoding && !priority)
1398 return code;
1399 encoding = encoding_open(buf);
1400 if (encoding)
1401 *encoding_ref = encoding;
1404 return code;
1407 static enum option_code
1408 parse_args(const char ***args, const char *argv[])
1410 if (*args == NULL && !argv_copy(args, argv))
1411 return OPT_ERR_OUT_OF_MEMORY;
1412 return OPT_OK;
1415 /* Wants: name = value */
1416 static enum option_code
1417 option_set_command(int argc, const char *argv[])
1419 if (argc < 3)
1420 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1422 if (strcmp(argv[1], "="))
1423 return OPT_ERR_NO_VALUE_ASSIGNED;
1425 if (!strcmp(argv[0], "blame-options"))
1426 return parse_args(&opt_blame_argv, argv + 2);
1428 if (argc != 3)
1429 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1431 if (!strcmp(argv[0], "show-author"))
1432 return parse_enum(&opt_author, argv[2], author_map);
1434 if (!strcmp(argv[0], "show-date"))
1435 return parse_enum(&opt_date, argv[2], date_map);
1437 if (!strcmp(argv[0], "show-rev-graph"))
1438 return parse_bool(&opt_rev_graph, argv[2]);
1440 if (!strcmp(argv[0], "show-refs"))
1441 return parse_bool(&opt_show_refs, argv[2]);
1443 if (!strcmp(argv[0], "show-changes"))
1444 return parse_bool(&opt_show_changes, argv[2]);
1446 if (!strcmp(argv[0], "show-notes")) {
1447 bool matched = FALSE;
1448 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1450 if (res == OPT_OK && matched) {
1451 update_notes_arg();
1452 return res;
1455 opt_notes = TRUE;
1456 strcpy(opt_notes_arg, "--show-notes=");
1457 res = parse_string(opt_notes_arg + 8, argv[2],
1458 sizeof(opt_notes_arg) - 8);
1459 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1460 opt_notes_arg[7] = '\0';
1461 return res;
1464 if (!strcmp(argv[0], "show-line-numbers"))
1465 return parse_bool(&opt_line_number, argv[2]);
1467 if (!strcmp(argv[0], "line-graphics"))
1468 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1470 if (!strcmp(argv[0], "line-number-interval"))
1471 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1473 if (!strcmp(argv[0], "author-width"))
1474 return parse_int(&opt_author_width, argv[2], 0, 1024);
1476 if (!strcmp(argv[0], "filename-width"))
1477 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1479 if (!strcmp(argv[0], "show-filename"))
1480 return parse_enum(&opt_filename, argv[2], filename_map);
1482 if (!strcmp(argv[0], "horizontal-scroll"))
1483 return parse_step(&opt_hscroll, argv[2]);
1485 if (!strcmp(argv[0], "split-view-height"))
1486 return parse_step(&opt_scale_split_view, argv[2]);
1488 if (!strcmp(argv[0], "vertical-split"))
1489 return parse_bool(&opt_vsplit, argv[2]);
1491 if (!strcmp(argv[0], "tab-size"))
1492 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1494 if (!strcmp(argv[0], "diff-context")) {
1495 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1497 if (code == OPT_OK)
1498 update_diff_context_arg(opt_diff_context);
1499 return code;
1502 if (!strcmp(argv[0], "ignore-space")) {
1503 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1505 if (code == OPT_OK)
1506 update_ignore_space_arg();
1507 return code;
1510 if (!strcmp(argv[0], "commit-order")) {
1511 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1513 if (code == OPT_OK)
1514 update_commit_order_arg();
1515 return code;
1518 if (!strcmp(argv[0], "status-untracked-dirs"))
1519 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1521 if (!strcmp(argv[0], "read-git-colors"))
1522 return parse_bool(&opt_read_git_colors, argv[2]);
1524 if (!strcmp(argv[0], "ignore-case"))
1525 return parse_bool(&opt_ignore_case, argv[2]);
1527 if (!strcmp(argv[0], "wrap-lines"))
1528 return parse_bool(&opt_wrap_lines, argv[2]);
1530 if (!strcmp(argv[0], "show-id"))
1531 return parse_bool(&opt_show_id, argv[2]);
1533 if (!strcmp(argv[0], "id-width"))
1534 return parse_id(&opt_id_cols, argv[2]);
1536 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1539 /* Wants: mode request key */
1540 static enum option_code
1541 option_bind_command(int argc, const char *argv[])
1543 enum request request;
1544 struct keymap *keymap;
1545 int key;
1547 if (argc < 3)
1548 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1550 if (!(keymap = get_keymap(argv[0])))
1551 return OPT_ERR_UNKNOWN_KEY_MAP;
1553 key = get_key_value(argv[1]);
1554 if (key == ERR)
1555 return OPT_ERR_UNKNOWN_KEY;
1557 request = get_request(argv[2]);
1558 if (request == REQ_UNKNOWN) {
1559 static const struct enum_map obsolete[] = {
1560 ENUM_MAP("cherry-pick", REQ_NONE),
1561 ENUM_MAP("screen-resize", REQ_NONE),
1562 ENUM_MAP("tree-parent", REQ_PARENT),
1564 int alias;
1566 if (map_enum(&alias, obsolete, argv[2])) {
1567 if (alias != REQ_NONE)
1568 add_keybinding(keymap, alias, key);
1569 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1572 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1573 enum run_request_flag flags = RUN_REQUEST_FORCE;
1575 while (*argv[2]) {
1576 if (*argv[2] == '@') {
1577 flags |= RUN_REQUEST_SILENT;
1578 } else if (*argv[2] == '?') {
1579 flags |= RUN_REQUEST_CONFIRM;
1580 } else if (*argv[2] == '<') {
1581 flags |= RUN_REQUEST_EXIT;
1582 } else {
1583 break;
1585 argv[2]++;
1588 return add_run_request(keymap, key, argv + 2, flags)
1589 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1591 if (request == REQ_UNKNOWN)
1592 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1594 add_keybinding(keymap, request, key);
1596 return OPT_OK;
1600 static enum option_code load_option_file(const char *path);
1602 static enum option_code
1603 option_source_command(int argc, const char *argv[])
1605 if (argc < 1)
1606 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1608 return load_option_file(argv[0]);
1611 static enum option_code
1612 set_option(const char *opt, char *value)
1614 const char *argv[SIZEOF_ARG];
1615 int argc = 0;
1617 if (!argv_from_string(argv, &argc, value))
1618 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1620 if (!strcmp(opt, "color"))
1621 return option_color_command(argc, argv);
1623 if (!strcmp(opt, "set"))
1624 return option_set_command(argc, argv);
1626 if (!strcmp(opt, "bind"))
1627 return option_bind_command(argc, argv);
1629 if (!strcmp(opt, "source"))
1630 return option_source_command(argc, argv);
1632 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1635 struct config_state {
1636 const char *path;
1637 int lineno;
1638 bool errors;
1641 static int
1642 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1644 struct config_state *config = data;
1645 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1647 config->lineno++;
1649 /* Check for comment markers, since read_properties() will
1650 * only ensure opt and value are split at first " \t". */
1651 optlen = strcspn(opt, "#");
1652 if (optlen == 0)
1653 return OK;
1655 if (opt[optlen] == 0) {
1656 /* Look for comment endings in the value. */
1657 size_t len = strcspn(value, "#");
1659 if (len < valuelen) {
1660 valuelen = len;
1661 value[valuelen] = 0;
1664 status = set_option(opt, value);
1667 if (status != OPT_OK) {
1668 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1669 option_errors[status], (int) optlen, opt);
1670 config->errors = TRUE;
1673 /* Always keep going if errors are encountered. */
1674 return OK;
1677 static enum option_code
1678 load_option_file(const char *path)
1680 struct config_state config = { path, 0, FALSE };
1681 struct io io;
1683 /* Do not read configuration from stdin if set to "" */
1684 if (!path || !strlen(path))
1685 return OPT_OK;
1687 /* It's OK that the file doesn't exist. */
1688 if (!io_open(&io, "%s", path))
1689 return OPT_ERR_FILE_DOES_NOT_EXIST;
1691 if (io_load(&io, " \t", read_option, &config) == ERR ||
1692 config.errors == TRUE)
1693 warn("Errors while loading %s.", path);
1694 return OPT_OK;
1697 static int
1698 load_options(void)
1700 const char *home = getenv("HOME");
1701 const char *tigrc_user = getenv("TIGRC_USER");
1702 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1703 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1704 char buf[SIZEOF_STR];
1706 if (!tigrc_system)
1707 tigrc_system = SYSCONFDIR "/tigrc";
1708 load_option_file(tigrc_system);
1710 if (!tigrc_user) {
1711 if (!home || !string_format(buf, "%s/.tigrc", home))
1712 return ERR;
1713 tigrc_user = buf;
1715 load_option_file(tigrc_user);
1717 /* Add _after_ loading config files to avoid adding run requests
1718 * that conflict with keybindings. */
1719 add_builtin_run_requests();
1721 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1722 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1723 int argc = 0;
1725 if (!string_format(buf, "%s", tig_diff_opts) ||
1726 !argv_from_string(diff_opts, &argc, buf))
1727 die("TIG_DIFF_OPTS contains too many arguments");
1728 else if (!argv_copy(&opt_diff_argv, diff_opts))
1729 die("Failed to format TIG_DIFF_OPTS arguments");
1732 return OK;
1737 * The viewer
1740 struct view;
1741 struct view_ops;
1743 /* The display array of active views and the index of the current view. */
1744 static struct view *display[2];
1745 static WINDOW *display_win[2];
1746 static WINDOW *display_title[2];
1747 static WINDOW *display_sep;
1749 static unsigned int current_view;
1751 #define foreach_displayed_view(view, i) \
1752 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1754 #define displayed_views() (display[1] != NULL ? 2 : 1)
1756 /* Current head and commit ID */
1757 static char ref_blob[SIZEOF_REF] = "";
1758 static char ref_commit[SIZEOF_REF] = "HEAD";
1759 static char ref_head[SIZEOF_REF] = "HEAD";
1760 static char ref_branch[SIZEOF_REF] = "";
1762 enum view_flag {
1763 VIEW_NO_FLAGS = 0,
1764 VIEW_ALWAYS_LINENO = 1 << 0,
1765 VIEW_CUSTOM_STATUS = 1 << 1,
1766 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1767 VIEW_ADD_PAGER_REFS = 1 << 3,
1768 VIEW_OPEN_DIFF = 1 << 4,
1769 VIEW_NO_REF = 1 << 5,
1770 VIEW_NO_GIT_DIR = 1 << 6,
1771 VIEW_DIFF_LIKE = 1 << 7,
1772 VIEW_STDIN = 1 << 8,
1775 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1777 struct position {
1778 unsigned long offset; /* Offset of the window top */
1779 unsigned long col; /* Offset from the window side. */
1780 unsigned long lineno; /* Current line number */
1783 struct view {
1784 const char *name; /* View name */
1785 const char *id; /* Points to either of ref_{head,commit,blob} */
1787 struct view_ops *ops; /* View operations */
1789 char ref[SIZEOF_REF]; /* Hovered commit reference */
1790 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1792 int height, width; /* The width and height of the main window */
1793 WINDOW *win; /* The main window */
1795 /* Navigation */
1796 struct position pos; /* Current position. */
1797 struct position prev_pos; /* Previous position. */
1799 /* Searching */
1800 char grep[SIZEOF_STR]; /* Search string */
1801 regex_t *regex; /* Pre-compiled regexp */
1803 /* If non-NULL, points to the view that opened this view. If this view
1804 * is closed tig will switch back to the parent view. */
1805 struct view *parent;
1806 struct view *prev;
1808 /* Buffering */
1809 size_t lines; /* Total number of lines */
1810 struct line *line; /* Line index */
1811 unsigned int digits; /* Number of digits in the lines member. */
1813 /* Number of lines with custom status, not to be counted in the
1814 * view title. */
1815 unsigned int custom_lines;
1817 /* Drawing */
1818 struct line *curline; /* Line currently being drawn. */
1819 enum line_type curtype; /* Attribute currently used for drawing. */
1820 unsigned long col; /* Column when drawing. */
1821 bool has_scrolled; /* View was scrolled. */
1823 /* Loading */
1824 const char **argv; /* Shell command arguments. */
1825 const char *dir; /* Directory from which to execute. */
1826 struct io io;
1827 struct io *pipe;
1828 time_t start_time;
1829 time_t update_secs;
1830 struct encoding *encoding;
1831 bool unrefreshable;
1833 /* Private data */
1834 void *private;
1837 enum open_flags {
1838 OPEN_DEFAULT = 0, /* Use default view switching. */
1839 OPEN_SPLIT = 1, /* Split current view. */
1840 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1841 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1842 OPEN_PREPARED = 32, /* Open already prepared command. */
1843 OPEN_EXTRA = 64, /* Open extra data from command. */
1846 struct view_ops {
1847 /* What type of content being displayed. Used in the title bar. */
1848 const char *type;
1849 /* What keymap does this view have */
1850 struct keymap keymap;
1851 /* Flags to control the view behavior. */
1852 enum view_flag flags;
1853 /* Size of private data. */
1854 size_t private_size;
1855 /* Open and reads in all view content. */
1856 bool (*open)(struct view *view, enum open_flags flags);
1857 /* Read one line; updates view->line. */
1858 bool (*read)(struct view *view, char *data);
1859 /* Draw one line; @lineno must be < view->height. */
1860 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1861 /* Depending on view handle a special requests. */
1862 enum request (*request)(struct view *view, enum request request, struct line *line);
1863 /* Search for regexp in a line. */
1864 bool (*grep)(struct view *view, struct line *line);
1865 /* Select line */
1866 void (*select)(struct view *view, struct line *line);
1869 #define VIEW_OPS(id, name, ref) name##_ops
1870 static struct view_ops VIEW_INFO(VIEW_OPS);
1872 static struct view views[] = {
1873 #define VIEW_DATA(id, name, ref) \
1874 { #name, ref, &name##_ops }
1875 VIEW_INFO(VIEW_DATA)
1878 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1880 #define foreach_view(view, i) \
1881 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1883 #define view_is_displayed(view) \
1884 (view == display[0] || view == display[1])
1886 #define view_has_line(view, line_) \
1887 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1889 static enum request
1890 view_request(struct view *view, enum request request)
1892 if (!view || !view->lines)
1893 return request;
1895 if (request == REQ_REFRESH && view->unrefreshable) {
1896 report("This view can not be refreshed");
1897 return REQ_NONE;
1900 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1904 * View drawing.
1907 static inline void
1908 set_view_attr(struct view *view, enum line_type type)
1910 if (!view->curline->selected && view->curtype != type) {
1911 (void) wattrset(view->win, get_line_attr(type));
1912 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1913 view->curtype = type;
1917 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1919 static bool
1920 draw_chars(struct view *view, enum line_type type, const char *string,
1921 int max_len, bool use_tilde)
1923 static char out_buffer[BUFSIZ * 2];
1924 int len = 0;
1925 int col = 0;
1926 int trimmed = FALSE;
1927 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1929 if (max_len <= 0)
1930 return VIEW_MAX_LEN(view) <= 0;
1932 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1934 set_view_attr(view, type);
1935 if (len > 0) {
1936 if (opt_iconv_out != ICONV_NONE) {
1937 size_t inlen = len + 1;
1938 char *instr = calloc(1, inlen);
1939 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1940 if (!instr)
1941 return VIEW_MAX_LEN(view) <= 0;
1943 strncpy(instr, string, len);
1945 char *outbuf = out_buffer;
1946 size_t outlen = sizeof(out_buffer);
1948 size_t ret;
1950 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1951 if (ret != (size_t) -1) {
1952 string = out_buffer;
1953 len = sizeof(out_buffer) - outlen;
1955 free(instr);
1958 waddnstr(view->win, string, len);
1960 if (trimmed && use_tilde) {
1961 set_view_attr(view, LINE_DELIMITER);
1962 waddch(view->win, '~');
1963 col++;
1967 view->col += col;
1968 return VIEW_MAX_LEN(view) <= 0;
1971 static bool
1972 draw_space(struct view *view, enum line_type type, int max, int spaces)
1974 static char space[] = " ";
1976 spaces = MIN(max, spaces);
1978 while (spaces > 0) {
1979 int len = MIN(spaces, sizeof(space) - 1);
1981 if (draw_chars(view, type, space, len, FALSE))
1982 return TRUE;
1983 spaces -= len;
1986 return VIEW_MAX_LEN(view) <= 0;
1989 static bool
1990 draw_text(struct view *view, enum line_type type, const char *string)
1992 static char text[SIZEOF_STR];
1994 do {
1995 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1997 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1998 return TRUE;
1999 string += pos;
2000 } while (*string);
2002 return VIEW_MAX_LEN(view) <= 0;
2005 static bool PRINTF_LIKE(3, 4)
2006 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2008 char text[SIZEOF_STR];
2009 int retval;
2011 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2012 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2015 static bool
2016 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2018 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2019 int max = VIEW_MAX_LEN(view);
2020 int i;
2022 if (max < size)
2023 size = max;
2025 set_view_attr(view, type);
2026 /* Using waddch() instead of waddnstr() ensures that
2027 * they'll be rendered correctly for the cursor line. */
2028 for (i = skip; i < size; i++)
2029 waddch(view->win, graphic[i]);
2031 view->col += size;
2032 if (separator) {
2033 if (size < max && skip <= size)
2034 waddch(view->win, ' ');
2035 view->col++;
2038 return VIEW_MAX_LEN(view) <= 0;
2041 static bool
2042 draw_field(struct view *view, enum line_type type, const char *text, int width, bool trim)
2044 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2045 int col = view->col;
2047 if (!text)
2048 return draw_space(view, type, max, max);
2050 return draw_chars(view, type, text, max - 1, trim)
2051 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2054 static bool
2055 draw_date(struct view *view, struct time *time)
2057 const char *date = mkdate(time, opt_date);
2058 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2060 if (opt_date == DATE_NO)
2061 return FALSE;
2063 return draw_field(view, LINE_DATE, date, cols, FALSE);
2066 static bool
2067 draw_author(struct view *view, const char *author)
2069 bool trim = author_trim(opt_author_width);
2070 const char *text = mkauthor(author, opt_author_width, opt_author);
2072 if (opt_author == AUTHOR_NO)
2073 return FALSE;
2075 return draw_field(view, LINE_AUTHOR, text, opt_author_width, trim);
2078 static bool
2079 draw_id(struct view *view, enum line_type type, const char *id)
2081 return draw_field(view, type, id, opt_id_cols, FALSE);
2084 static bool
2085 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2087 bool trim = filename && strlen(filename) >= opt_filename_width;
2089 if (opt_filename == FILENAME_NO)
2090 return FALSE;
2092 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2093 return FALSE;
2095 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, trim);
2098 static bool
2099 draw_mode(struct view *view, mode_t mode)
2101 const char *str = mkmode(mode);
2103 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), FALSE);
2106 static bool
2107 draw_lineno(struct view *view, unsigned int lineno)
2109 char number[10];
2110 int digits3 = view->digits < 3 ? 3 : view->digits;
2111 int max = MIN(VIEW_MAX_LEN(view), digits3);
2112 char *text = NULL;
2113 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2115 if (!opt_line_number)
2116 return FALSE;
2118 lineno += view->pos.offset + 1;
2119 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2120 static char fmt[] = "%1ld";
2122 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2123 if (string_format(number, fmt, lineno))
2124 text = number;
2126 if (text)
2127 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2128 else
2129 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2130 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2133 static bool
2134 draw_refs(struct view *view, struct ref_list *refs)
2136 size_t i;
2138 if (!opt_show_refs || !refs)
2139 return FALSE;
2141 for (i = 0; i < refs->size; i++) {
2142 struct ref *ref = refs->refs[i];
2143 enum line_type type = get_line_type_from_ref(ref);
2145 if (draw_formatted(view, type, "[%s]", ref->name))
2146 return TRUE;
2148 if (draw_text(view, LINE_DEFAULT, " "))
2149 return TRUE;
2152 return FALSE;
2155 static bool
2156 draw_view_line(struct view *view, unsigned int lineno)
2158 struct line *line;
2159 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2161 assert(view_is_displayed(view));
2163 if (view->pos.offset + lineno >= view->lines)
2164 return FALSE;
2166 line = &view->line[view->pos.offset + lineno];
2168 wmove(view->win, lineno, 0);
2169 if (line->cleareol)
2170 wclrtoeol(view->win);
2171 view->col = 0;
2172 view->curline = line;
2173 view->curtype = LINE_NONE;
2174 line->selected = FALSE;
2175 line->dirty = line->cleareol = 0;
2177 if (selected) {
2178 set_view_attr(view, LINE_CURSOR);
2179 line->selected = TRUE;
2180 view->ops->select(view, line);
2183 return view->ops->draw(view, line, lineno);
2186 static void
2187 redraw_view_dirty(struct view *view)
2189 bool dirty = FALSE;
2190 int lineno;
2192 for (lineno = 0; lineno < view->height; lineno++) {
2193 if (view->pos.offset + lineno >= view->lines)
2194 break;
2195 if (!view->line[view->pos.offset + lineno].dirty)
2196 continue;
2197 dirty = TRUE;
2198 if (!draw_view_line(view, lineno))
2199 break;
2202 if (!dirty)
2203 return;
2204 wnoutrefresh(view->win);
2207 static void
2208 redraw_view_from(struct view *view, int lineno)
2210 assert(0 <= lineno && lineno < view->height);
2212 for (; lineno < view->height; lineno++) {
2213 if (!draw_view_line(view, lineno))
2214 break;
2217 wnoutrefresh(view->win);
2220 static void
2221 redraw_view(struct view *view)
2223 werase(view->win);
2224 redraw_view_from(view, 0);
2228 static void
2229 update_view_title(struct view *view)
2231 char buf[SIZEOF_STR];
2232 char state[SIZEOF_STR];
2233 size_t bufpos = 0, statelen = 0;
2234 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2235 struct line *line = &view->line[view->pos.lineno];
2237 assert(view_is_displayed(view));
2239 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2240 line->lineno) {
2241 unsigned int view_lines = view->pos.offset + view->height;
2242 unsigned int lines = view->lines
2243 ? MIN(view_lines, view->lines) * 100 / view->lines
2244 : 0;
2246 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2247 view->ops->type,
2248 line->lineno,
2249 view->lines - view->custom_lines,
2250 lines);
2254 if (view->pipe) {
2255 time_t secs = time(NULL) - view->start_time;
2257 /* Three git seconds are a long time ... */
2258 if (secs > 2)
2259 string_format_from(state, &statelen, " loading %lds", secs);
2262 string_format_from(buf, &bufpos, "[%s]", view->name);
2263 if (*view->ref && bufpos < view->width) {
2264 size_t refsize = strlen(view->ref);
2265 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2267 if (minsize < view->width)
2268 refsize = view->width - minsize + 7;
2269 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2272 if (statelen && bufpos < view->width) {
2273 string_format_from(buf, &bufpos, "%s", state);
2276 if (view == display[current_view])
2277 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2278 else
2279 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2281 mvwaddnstr(window, 0, 0, buf, bufpos);
2282 wclrtoeol(window);
2283 wnoutrefresh(window);
2286 static int
2287 apply_step(double step, int value)
2289 if (step >= 1)
2290 return (int) step;
2291 value *= step + 0.01;
2292 return value ? value : 1;
2295 static void
2296 apply_horizontal_split(struct view *base, struct view *view)
2298 view->width = base->width;
2299 view->height = apply_step(opt_scale_split_view, base->height);
2300 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2301 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2302 base->height -= view->height;
2305 static void
2306 apply_vertical_split(struct view *base, struct view *view)
2308 view->height = base->height;
2309 view->width = apply_step(opt_scale_vsplit_view, base->width);
2310 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2311 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2312 base->width -= view->width;
2315 static void
2316 redraw_display_separator(bool clear)
2318 if (displayed_views() > 1 && opt_vsplit) {
2319 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2321 if (clear)
2322 wclear(display_sep);
2323 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2324 wnoutrefresh(display_sep);
2328 static void
2329 resize_display(void)
2331 int x, y, i;
2332 struct view *base = display[0];
2333 struct view *view = display[1] ? display[1] : display[0];
2335 /* Setup window dimensions */
2337 getmaxyx(stdscr, base->height, base->width);
2339 /* Make room for the status window. */
2340 base->height -= 1;
2342 if (view != base) {
2343 if (opt_vsplit) {
2344 apply_vertical_split(base, view);
2346 /* Make room for the separator bar. */
2347 view->width -= 1;
2348 } else {
2349 apply_horizontal_split(base, view);
2352 /* Make room for the title bar. */
2353 view->height -= 1;
2356 /* Make room for the title bar. */
2357 base->height -= 1;
2359 x = y = 0;
2361 foreach_displayed_view (view, i) {
2362 if (!display_win[i]) {
2363 display_win[i] = newwin(view->height, view->width, y, x);
2364 if (!display_win[i])
2365 die("Failed to create %s view", view->name);
2367 scrollok(display_win[i], FALSE);
2369 display_title[i] = newwin(1, view->width, y + view->height, x);
2370 if (!display_title[i])
2371 die("Failed to create title window");
2373 } else {
2374 wresize(display_win[i], view->height, view->width);
2375 mvwin(display_win[i], y, x);
2376 wresize(display_title[i], 1, view->width);
2377 mvwin(display_title[i], y + view->height, x);
2380 if (i > 0 && opt_vsplit) {
2381 if (!display_sep) {
2382 display_sep = newwin(view->height, 1, 0, x - 1);
2383 if (!display_sep)
2384 die("Failed to create separator window");
2386 } else {
2387 wresize(display_sep, view->height, 1);
2388 mvwin(display_sep, 0, x - 1);
2392 view->win = display_win[i];
2394 if (opt_vsplit)
2395 x += view->width + 1;
2396 else
2397 y += view->height + 1;
2400 redraw_display_separator(FALSE);
2403 static void
2404 redraw_display(bool clear)
2406 struct view *view;
2407 int i;
2409 foreach_displayed_view (view, i) {
2410 if (clear)
2411 wclear(view->win);
2412 redraw_view(view);
2413 update_view_title(view);
2416 redraw_display_separator(clear);
2420 * Option management
2423 #define TOGGLE_MENU \
2424 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2425 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2426 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2427 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2428 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2429 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2430 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2431 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2432 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2433 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL) \
2434 TOGGLE_(ID, 'X', "commit ID display", &opt_show_id, NULL)
2436 static bool
2437 toggle_option(enum request request)
2439 const struct {
2440 enum request request;
2441 const struct enum_map *map;
2442 size_t map_size;
2443 } data[] = {
2444 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2445 TOGGLE_MENU
2446 #undef TOGGLE_
2448 const struct menu_item menu[] = {
2449 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2450 TOGGLE_MENU
2451 #undef TOGGLE_
2452 { 0 }
2454 int i = 0;
2456 if (request == REQ_OPTIONS) {
2457 if (!prompt_menu("Toggle option", menu, &i))
2458 return FALSE;
2459 } else {
2460 while (i < ARRAY_SIZE(data) && data[i].request != request)
2461 i++;
2462 if (i >= ARRAY_SIZE(data))
2463 die("Invalid request (%d)", request);
2466 if (data[i].map != NULL) {
2467 unsigned int *opt = menu[i].data;
2469 *opt = (*opt + 1) % data[i].map_size;
2470 if (data[i].map == ignore_space_map) {
2471 update_ignore_space_arg();
2472 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2473 return TRUE;
2475 } else if (data[i].map == commit_order_map) {
2476 update_commit_order_arg();
2477 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2478 return TRUE;
2481 redraw_display(FALSE);
2482 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2484 } else {
2485 bool *option = menu[i].data;
2487 *option = !*option;
2488 redraw_display(FALSE);
2489 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2492 return FALSE;
2497 * Navigation
2500 static bool
2501 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2503 if (lineno >= view->lines)
2504 lineno = view->lines > 0 ? view->lines - 1 : 0;
2506 if (offset > lineno || offset + view->height <= lineno) {
2507 unsigned long half = view->height / 2;
2509 if (lineno > half)
2510 offset = lineno - half;
2511 else
2512 offset = 0;
2515 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2516 view->pos.offset = offset;
2517 view->pos.lineno = lineno;
2518 return TRUE;
2521 return FALSE;
2524 /* Scrolling backend */
2525 static void
2526 do_scroll_view(struct view *view, int lines)
2528 bool redraw_current_line = FALSE;
2530 /* The rendering expects the new offset. */
2531 view->pos.offset += lines;
2533 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2534 assert(lines);
2536 /* Move current line into the view. */
2537 if (view->pos.lineno < view->pos.offset) {
2538 view->pos.lineno = view->pos.offset;
2539 redraw_current_line = TRUE;
2540 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2541 view->pos.lineno = view->pos.offset + view->height - 1;
2542 redraw_current_line = TRUE;
2545 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2547 /* Redraw the whole screen if scrolling is pointless. */
2548 if (view->height < ABS(lines)) {
2549 redraw_view(view);
2551 } else {
2552 int line = lines > 0 ? view->height - lines : 0;
2553 int end = line + ABS(lines);
2555 scrollok(view->win, TRUE);
2556 wscrl(view->win, lines);
2557 scrollok(view->win, FALSE);
2559 while (line < end && draw_view_line(view, line))
2560 line++;
2562 if (redraw_current_line)
2563 draw_view_line(view, view->pos.lineno - view->pos.offset);
2564 wnoutrefresh(view->win);
2567 view->has_scrolled = TRUE;
2568 report_clear();
2571 /* Scroll frontend */
2572 static void
2573 scroll_view(struct view *view, enum request request)
2575 int lines = 1;
2577 assert(view_is_displayed(view));
2579 switch (request) {
2580 case REQ_SCROLL_FIRST_COL:
2581 view->pos.col = 0;
2582 redraw_view_from(view, 0);
2583 report_clear();
2584 return;
2585 case REQ_SCROLL_LEFT:
2586 if (view->pos.col == 0) {
2587 report("Cannot scroll beyond the first column");
2588 return;
2590 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2591 view->pos.col = 0;
2592 else
2593 view->pos.col -= apply_step(opt_hscroll, view->width);
2594 redraw_view_from(view, 0);
2595 report_clear();
2596 return;
2597 case REQ_SCROLL_RIGHT:
2598 view->pos.col += apply_step(opt_hscroll, view->width);
2599 redraw_view(view);
2600 report_clear();
2601 return;
2602 case REQ_SCROLL_PAGE_DOWN:
2603 lines = view->height;
2604 case REQ_SCROLL_LINE_DOWN:
2605 if (view->pos.offset + lines > view->lines)
2606 lines = view->lines - view->pos.offset;
2608 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2609 report("Cannot scroll beyond the last line");
2610 return;
2612 break;
2614 case REQ_SCROLL_PAGE_UP:
2615 lines = view->height;
2616 case REQ_SCROLL_LINE_UP:
2617 if (lines > view->pos.offset)
2618 lines = view->pos.offset;
2620 if (lines == 0) {
2621 report("Cannot scroll beyond the first line");
2622 return;
2625 lines = -lines;
2626 break;
2628 default:
2629 die("request %d not handled in switch", request);
2632 do_scroll_view(view, lines);
2635 /* Cursor moving */
2636 static void
2637 move_view(struct view *view, enum request request)
2639 int scroll_steps = 0;
2640 int steps;
2642 switch (request) {
2643 case REQ_MOVE_FIRST_LINE:
2644 steps = -view->pos.lineno;
2645 break;
2647 case REQ_MOVE_LAST_LINE:
2648 steps = view->lines - view->pos.lineno - 1;
2649 break;
2651 case REQ_MOVE_PAGE_UP:
2652 steps = view->height > view->pos.lineno
2653 ? -view->pos.lineno : -view->height;
2654 break;
2656 case REQ_MOVE_PAGE_DOWN:
2657 steps = view->pos.lineno + view->height >= view->lines
2658 ? view->lines - view->pos.lineno - 1 : view->height;
2659 break;
2661 case REQ_MOVE_UP:
2662 case REQ_PREVIOUS:
2663 steps = -1;
2664 break;
2666 case REQ_MOVE_DOWN:
2667 case REQ_NEXT:
2668 steps = 1;
2669 break;
2671 default:
2672 die("request %d not handled in switch", request);
2675 if (steps <= 0 && view->pos.lineno == 0) {
2676 report("Cannot move beyond the first line");
2677 return;
2679 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2680 report("Cannot move beyond the last line");
2681 return;
2684 /* Move the current line */
2685 view->pos.lineno += steps;
2686 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2688 /* Check whether the view needs to be scrolled */
2689 if (view->pos.lineno < view->pos.offset ||
2690 view->pos.lineno >= view->pos.offset + view->height) {
2691 scroll_steps = steps;
2692 if (steps < 0 && -steps > view->pos.offset) {
2693 scroll_steps = -view->pos.offset;
2695 } else if (steps > 0) {
2696 if (view->pos.lineno == view->lines - 1 &&
2697 view->lines > view->height) {
2698 scroll_steps = view->lines - view->pos.offset - 1;
2699 if (scroll_steps >= view->height)
2700 scroll_steps -= view->height - 1;
2705 if (!view_is_displayed(view)) {
2706 view->pos.offset += scroll_steps;
2707 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2708 view->ops->select(view, &view->line[view->pos.lineno]);
2709 return;
2712 /* Repaint the old "current" line if we be scrolling */
2713 if (ABS(steps) < view->height)
2714 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2716 if (scroll_steps) {
2717 do_scroll_view(view, scroll_steps);
2718 return;
2721 /* Draw the current line */
2722 draw_view_line(view, view->pos.lineno - view->pos.offset);
2724 wnoutrefresh(view->win);
2725 report_clear();
2730 * Searching
2733 static void search_view(struct view *view, enum request request);
2735 static bool
2736 grep_text(struct view *view, const char *text[])
2738 regmatch_t pmatch;
2739 size_t i;
2741 for (i = 0; text[i]; i++)
2742 if (*text[i] &&
2743 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2744 return TRUE;
2745 return FALSE;
2748 static void
2749 select_view_line(struct view *view, unsigned long lineno)
2751 struct position old = view->pos;
2753 if (goto_view_line(view, view->pos.offset, lineno)) {
2754 if (view_is_displayed(view)) {
2755 if (old.offset != view->pos.offset) {
2756 redraw_view(view);
2757 } else {
2758 draw_view_line(view, old.lineno - view->pos.offset);
2759 draw_view_line(view, view->pos.lineno - view->pos.offset);
2760 wnoutrefresh(view->win);
2762 } else {
2763 view->ops->select(view, &view->line[view->pos.lineno]);
2768 static void
2769 find_next(struct view *view, enum request request)
2771 unsigned long lineno = view->pos.lineno;
2772 int direction;
2774 if (!*view->grep) {
2775 if (!*opt_search)
2776 report("No previous search");
2777 else
2778 search_view(view, request);
2779 return;
2782 switch (request) {
2783 case REQ_SEARCH:
2784 case REQ_FIND_NEXT:
2785 direction = 1;
2786 break;
2788 case REQ_SEARCH_BACK:
2789 case REQ_FIND_PREV:
2790 direction = -1;
2791 break;
2793 default:
2794 return;
2797 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2798 lineno += direction;
2800 /* Note, lineno is unsigned long so will wrap around in which case it
2801 * will become bigger than view->lines. */
2802 for (; lineno < view->lines; lineno += direction) {
2803 if (view->ops->grep(view, &view->line[lineno])) {
2804 select_view_line(view, lineno);
2805 report("Line %ld matches '%s'", lineno + 1, view->grep);
2806 return;
2810 report("No match found for '%s'", view->grep);
2813 static void
2814 search_view(struct view *view, enum request request)
2816 int regex_err;
2817 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
2819 if (view->regex) {
2820 regfree(view->regex);
2821 *view->grep = 0;
2822 } else {
2823 view->regex = calloc(1, sizeof(*view->regex));
2824 if (!view->regex)
2825 return;
2828 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
2829 if (regex_err != 0) {
2830 char buf[SIZEOF_STR] = "unknown error";
2832 regerror(regex_err, view->regex, buf, sizeof(buf));
2833 report("Search failed: %s", buf);
2834 return;
2837 string_copy(view->grep, opt_search);
2839 find_next(view, request);
2843 * Incremental updating
2846 static inline bool
2847 check_position(struct position *pos)
2849 return pos->lineno || pos->col || pos->offset;
2852 static inline void
2853 clear_position(struct position *pos)
2855 memset(pos, 0, sizeof(*pos));
2858 static void
2859 reset_view(struct view *view)
2861 int i;
2863 for (i = 0; i < view->lines; i++)
2864 if (!view->line[i].dont_free)
2865 free(view->line[i].data);
2866 free(view->line);
2868 view->prev_pos = view->pos;
2869 clear_position(&view->pos);
2871 view->line = NULL;
2872 view->lines = 0;
2873 view->vid[0] = 0;
2874 view->custom_lines = 0;
2875 view->update_secs = 0;
2878 static const char *
2879 format_arg(const char *name)
2881 static struct {
2882 const char *name;
2883 size_t namelen;
2884 const char *value;
2885 const char *value_if_empty;
2886 } vars[] = {
2887 #define FORMAT_VAR(name, value, value_if_empty) \
2888 { name, STRING_SIZE(name), value, value_if_empty }
2889 FORMAT_VAR("%(directory)", opt_path, "."),
2890 FORMAT_VAR("%(file)", opt_file, ""),
2891 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2892 FORMAT_VAR("%(head)", ref_head, ""),
2893 FORMAT_VAR("%(commit)", ref_commit, ""),
2894 FORMAT_VAR("%(blob)", ref_blob, ""),
2895 FORMAT_VAR("%(branch)", ref_branch, ""),
2897 int i;
2899 if (!prefixcmp(name, "%(prompt"))
2900 return read_prompt("Command argument: ");
2902 for (i = 0; i < ARRAY_SIZE(vars); i++)
2903 if (!strncmp(name, vars[i].name, vars[i].namelen))
2904 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2906 report("Unknown replacement: `%s`", name);
2907 return NULL;
2910 static bool
2911 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2913 char buf[SIZEOF_STR];
2914 int argc;
2916 argv_free(*dst_argv);
2918 for (argc = 0; src_argv[argc]; argc++) {
2919 const char *arg = src_argv[argc];
2920 size_t bufpos = 0;
2922 if (!strcmp(arg, "%(fileargs)")) {
2923 if (!argv_append_array(dst_argv, opt_file_argv))
2924 break;
2925 continue;
2927 } else if (!strcmp(arg, "%(diffargs)")) {
2928 if (!argv_append_array(dst_argv, opt_diff_argv))
2929 break;
2930 continue;
2932 } else if (!strcmp(arg, "%(blameargs)")) {
2933 if (!argv_append_array(dst_argv, opt_blame_argv))
2934 break;
2935 continue;
2937 } else if (!strcmp(arg, "%(revargs)") ||
2938 (first && !strcmp(arg, "%(commit)"))) {
2939 if (!argv_append_array(dst_argv, opt_rev_argv))
2940 break;
2941 continue;
2944 while (arg) {
2945 char *next = strstr(arg, "%(");
2946 int len = next - arg;
2947 const char *value;
2949 if (!next) {
2950 len = strlen(arg);
2951 value = "";
2953 } else {
2954 value = format_arg(next);
2956 if (!value) {
2957 return FALSE;
2961 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2962 return FALSE;
2964 arg = next ? strchr(next, ')') + 1 : NULL;
2967 if (!argv_append(dst_argv, buf))
2968 break;
2971 return src_argv[argc] == NULL;
2974 static bool
2975 restore_view_position(struct view *view)
2977 /* A view without a previous view is the first view */
2978 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2979 select_view_line(view, opt_lineno - 1);
2980 opt_lineno = 0;
2983 /* Ensure that the view position is in a valid state. */
2984 if (!check_position(&view->prev_pos) ||
2985 (view->pipe && view->lines <= view->prev_pos.lineno))
2986 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2988 /* Changing the view position cancels the restoring. */
2989 /* FIXME: Changing back to the first line is not detected. */
2990 if (check_position(&view->pos)) {
2991 clear_position(&view->prev_pos);
2992 return FALSE;
2995 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2996 view_is_displayed(view))
2997 werase(view->win);
2999 view->pos.col = view->prev_pos.col;
3000 clear_position(&view->prev_pos);
3002 return TRUE;
3005 static void
3006 end_update(struct view *view, bool force)
3008 if (!view->pipe)
3009 return;
3010 while (!view->ops->read(view, NULL))
3011 if (!force)
3012 return;
3013 if (force)
3014 io_kill(view->pipe);
3015 io_done(view->pipe);
3016 view->pipe = NULL;
3019 static void
3020 setup_update(struct view *view, const char *vid)
3022 reset_view(view);
3023 string_copy_rev(view->vid, vid);
3024 view->pipe = &view->io;
3025 view->start_time = time(NULL);
3028 static bool
3029 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3031 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3032 bool extra = !!(flags & (OPEN_EXTRA));
3033 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3034 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3035 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3037 opt_stdin = FALSE;
3039 if ((!reload && !strcmp(view->vid, view->id)) ||
3040 ((flags & OPEN_REFRESH) && view->unrefreshable))
3041 return TRUE;
3043 if (view->pipe) {
3044 if (extra)
3045 io_done(view->pipe);
3046 else
3047 end_update(view, TRUE);
3050 view->unrefreshable = use_stdin;
3052 if (!refresh && argv) {
3053 view->dir = dir;
3054 if (!format_argv(&view->argv, argv, !view->prev)) {
3055 report("Failed to format %s arguments", view->name);
3056 return FALSE;
3059 /* Put the current ref_* value to the view title ref
3060 * member. This is needed by the blob view. Most other
3061 * views sets it automatically after loading because the
3062 * first line is a commit line. */
3063 string_copy_rev(view->ref, view->id);
3066 if (view->argv && view->argv[0] &&
3067 !io_run(&view->io, io_type, view->dir, view->argv)) {
3068 report("Failed to open %s view", view->name);
3069 return FALSE;
3072 if (!extra)
3073 setup_update(view, view->id);
3075 return TRUE;
3078 static bool
3079 update_view(struct view *view)
3081 char *line;
3082 /* Clear the view and redraw everything since the tree sorting
3083 * might have rearranged things. */
3084 bool redraw = view->lines == 0;
3085 bool can_read = TRUE;
3086 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3088 if (!view->pipe)
3089 return TRUE;
3091 if (!io_can_read(view->pipe, FALSE)) {
3092 if (view->lines == 0 && view_is_displayed(view)) {
3093 time_t secs = time(NULL) - view->start_time;
3095 if (secs > 1 && secs > view->update_secs) {
3096 if (view->update_secs == 0)
3097 redraw_view(view);
3098 update_view_title(view);
3099 view->update_secs = secs;
3102 return TRUE;
3105 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3106 if (encoding) {
3107 line = encoding_convert(encoding, line);
3110 if (!view->ops->read(view, line)) {
3111 report("Allocation failure");
3112 end_update(view, TRUE);
3113 return FALSE;
3118 unsigned long lines = view->lines;
3119 int digits;
3121 for (digits = 0; lines; digits++)
3122 lines /= 10;
3124 /* Keep the displayed view in sync with line number scaling. */
3125 if (digits != view->digits) {
3126 view->digits = digits;
3127 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3128 redraw = TRUE;
3132 if (io_error(view->pipe)) {
3133 report("Failed to read: %s", io_strerror(view->pipe));
3134 end_update(view, TRUE);
3136 } else if (io_eof(view->pipe)) {
3137 if (view_is_displayed(view))
3138 report_clear();
3139 end_update(view, FALSE);
3142 if (restore_view_position(view))
3143 redraw = TRUE;
3145 if (!view_is_displayed(view))
3146 return TRUE;
3148 if (redraw)
3149 redraw_view_from(view, 0);
3150 else
3151 redraw_view_dirty(view);
3153 /* Update the title _after_ the redraw so that if the redraw picks up a
3154 * commit reference in view->ref it'll be available here. */
3155 update_view_title(view);
3156 return TRUE;
3159 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3161 static struct line *
3162 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3164 struct line *line;
3166 if (!realloc_lines(&view->line, view->lines, 1))
3167 return NULL;
3169 if (data_size) {
3170 void *alloc_data = calloc(1, data_size);
3172 if (!alloc_data)
3173 return NULL;
3175 if (data)
3176 memcpy(alloc_data, data, data_size);
3177 data = alloc_data;
3180 line = &view->line[view->lines++];
3181 memset(line, 0, sizeof(*line));
3182 line->type = type;
3183 line->data = (void *) data;
3184 line->dirty = 1;
3186 if (custom)
3187 view->custom_lines++;
3188 else
3189 line->lineno = view->lines - view->custom_lines;
3191 return line;
3194 static struct line *
3195 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3197 struct line *line = add_line(view, NULL, type, data_size, custom);
3199 if (line)
3200 *ptr = line->data;
3201 return line;
3204 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3205 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3207 static struct line *
3208 add_line_nodata(struct view *view, enum line_type type)
3210 return add_line(view, NULL, type, 0, FALSE);
3213 static struct line *
3214 add_line_static_data(struct view *view, const void *data, enum line_type type)
3216 struct line *line = add_line(view, data, type, 0, FALSE);
3218 if (line)
3219 line->dont_free = TRUE;
3220 return line;
3223 static struct line *
3224 add_line_text(struct view *view, const char *text, enum line_type type)
3226 return add_line(view, text, type, strlen(text) + 1, FALSE);
3229 static struct line * PRINTF_LIKE(3, 4)
3230 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3232 char buf[SIZEOF_STR];
3233 int retval;
3235 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3236 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3240 * View opening
3243 static void
3244 split_view(struct view *prev, struct view *view)
3246 display[1] = view;
3247 current_view = 1;
3248 view->parent = prev;
3249 resize_display();
3251 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3252 /* Take the title line into account. */
3253 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3255 /* Scroll the view that was split if the current line is
3256 * outside the new limited view. */
3257 do_scroll_view(prev, lines);
3260 if (view != prev && view_is_displayed(prev)) {
3261 /* "Blur" the previous view. */
3262 update_view_title(prev);
3266 static void
3267 maximize_view(struct view *view, bool redraw)
3269 memset(display, 0, sizeof(display));
3270 current_view = 0;
3271 display[current_view] = view;
3272 resize_display();
3273 if (redraw) {
3274 redraw_display(FALSE);
3275 report_clear();
3279 static void
3280 load_view(struct view *view, struct view *prev, enum open_flags flags)
3282 if (view->pipe)
3283 end_update(view, TRUE);
3284 if (view->ops->private_size) {
3285 if (!view->private)
3286 view->private = calloc(1, view->ops->private_size);
3287 else
3288 memset(view->private, 0, view->ops->private_size);
3291 /* When prev == view it means this is the first loaded view. */
3292 if (prev && view != prev) {
3293 view->prev = prev;
3296 if (!view->ops->open(view, flags))
3297 return;
3299 if (prev) {
3300 bool split = !!(flags & OPEN_SPLIT);
3302 if (split) {
3303 split_view(prev, view);
3304 } else {
3305 maximize_view(view, FALSE);
3309 restore_view_position(view);
3311 if (view->pipe && view->lines == 0) {
3312 /* Clear the old view and let the incremental updating refill
3313 * the screen. */
3314 werase(view->win);
3315 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3316 clear_position(&view->prev_pos);
3317 report_clear();
3318 } else if (view_is_displayed(view)) {
3319 redraw_view(view);
3320 report_clear();
3324 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3325 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3327 static void
3328 open_view(struct view *prev, enum request request, enum open_flags flags)
3330 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3331 struct view *view = VIEW(request);
3332 int nviews = displayed_views();
3334 assert(flags ^ OPEN_REFRESH);
3336 if (view == prev && nviews == 1 && !reload) {
3337 report("Already in %s view", view->name);
3338 return;
3341 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3342 report("The %s view is disabled in pager view", view->name);
3343 return;
3346 load_view(view, prev ? prev : view, flags);
3349 static void
3350 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3352 enum request request = view - views + REQ_OFFSET + 1;
3354 if (view->pipe)
3355 end_update(view, TRUE);
3356 view->dir = dir;
3358 if (!argv_copy(&view->argv, argv)) {
3359 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3360 } else {
3361 open_view(prev, request, flags | OPEN_PREPARED);
3365 static void
3366 open_external_viewer(const char *argv[], const char *dir, bool confirm)
3368 def_prog_mode(); /* save current tty modes */
3369 endwin(); /* restore original tty modes */
3370 io_run_fg(argv, dir);
3371 if (confirm) {
3372 fprintf(stderr, "Press Enter to continue");
3373 getc(opt_tty);
3375 reset_prog_mode();
3376 redraw_display(TRUE);
3379 static void
3380 open_mergetool(const char *file)
3382 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3384 open_external_viewer(mergetool_argv, opt_cdup, TRUE);
3387 static void
3388 open_editor(const char *file)
3390 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3391 char editor_cmd[SIZEOF_STR];
3392 const char *editor;
3393 int argc = 0;
3395 editor = getenv("GIT_EDITOR");
3396 if (!editor && *opt_editor)
3397 editor = opt_editor;
3398 if (!editor)
3399 editor = getenv("VISUAL");
3400 if (!editor)
3401 editor = getenv("EDITOR");
3402 if (!editor)
3403 editor = "vi";
3405 string_ncopy(editor_cmd, editor, strlen(editor));
3406 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3407 report("Failed to read editor command");
3408 return;
3411 editor_argv[argc] = file;
3412 open_external_viewer(editor_argv, opt_cdup, TRUE);
3415 static bool
3416 open_run_request(enum request request)
3418 struct run_request *req = get_run_request(request);
3419 const char **argv = NULL;
3421 if (!req) {
3422 report("Unknown run request");
3423 return FALSE;
3426 if (format_argv(&argv, req->argv, FALSE)) {
3427 bool confirmed = !req->confirm;
3429 if (req->confirm) {
3430 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3432 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3433 string_format(prompt, "Run `%s`?", cmd) &&
3434 prompt_yesno(prompt)) {
3435 confirmed = TRUE;
3439 if (confirmed && argv_remove_quotes(argv)) {
3440 if (req->silent)
3441 io_run_bg(argv);
3442 else
3443 open_external_viewer(argv, NULL, !req->exit);
3447 if (argv)
3448 argv_free(argv);
3449 free(argv);
3451 return req->exit;
3455 * User request switch noodle
3458 static int
3459 view_driver(struct view *view, enum request request)
3461 int i;
3463 if (request == REQ_NONE)
3464 return TRUE;
3466 if (request > REQ_NONE) {
3467 if (open_run_request(request))
3468 return FALSE;
3469 if (!view->unrefreshable)
3470 view_request(view, REQ_REFRESH);
3471 return TRUE;
3474 request = view_request(view, request);
3475 if (request == REQ_NONE)
3476 return TRUE;
3478 switch (request) {
3479 case REQ_MOVE_UP:
3480 case REQ_MOVE_DOWN:
3481 case REQ_MOVE_PAGE_UP:
3482 case REQ_MOVE_PAGE_DOWN:
3483 case REQ_MOVE_FIRST_LINE:
3484 case REQ_MOVE_LAST_LINE:
3485 move_view(view, request);
3486 break;
3488 case REQ_SCROLL_FIRST_COL:
3489 case REQ_SCROLL_LEFT:
3490 case REQ_SCROLL_RIGHT:
3491 case REQ_SCROLL_LINE_DOWN:
3492 case REQ_SCROLL_LINE_UP:
3493 case REQ_SCROLL_PAGE_DOWN:
3494 case REQ_SCROLL_PAGE_UP:
3495 scroll_view(view, request);
3496 break;
3498 case REQ_VIEW_MAIN:
3499 case REQ_VIEW_DIFF:
3500 case REQ_VIEW_LOG:
3501 case REQ_VIEW_TREE:
3502 case REQ_VIEW_HELP:
3503 case REQ_VIEW_BRANCH:
3504 case REQ_VIEW_BLAME:
3505 case REQ_VIEW_BLOB:
3506 case REQ_VIEW_STATUS:
3507 case REQ_VIEW_STAGE:
3508 case REQ_VIEW_PAGER:
3509 open_view(view, request, OPEN_DEFAULT);
3510 break;
3512 case REQ_NEXT:
3513 case REQ_PREVIOUS:
3514 if (view->parent) {
3515 int line;
3517 view = view->parent;
3518 line = view->pos.lineno;
3519 move_view(view, request);
3520 if (view_is_displayed(view))
3521 update_view_title(view);
3522 if (line != view->pos.lineno)
3523 view_request(view, REQ_ENTER);
3524 } else {
3525 move_view(view, request);
3527 break;
3529 case REQ_VIEW_NEXT:
3531 int nviews = displayed_views();
3532 int next_view = (current_view + 1) % nviews;
3534 if (next_view == current_view) {
3535 report("Only one view is displayed");
3536 break;
3539 current_view = next_view;
3540 /* Blur out the title of the previous view. */
3541 update_view_title(view);
3542 report_clear();
3543 break;
3545 case REQ_REFRESH:
3546 report("Refreshing is not yet supported for the %s view", view->name);
3547 break;
3549 case REQ_MAXIMIZE:
3550 if (displayed_views() == 2)
3551 maximize_view(view, TRUE);
3552 break;
3554 case REQ_OPTIONS:
3555 case REQ_TOGGLE_LINENO:
3556 case REQ_TOGGLE_DATE:
3557 case REQ_TOGGLE_AUTHOR:
3558 case REQ_TOGGLE_FILENAME:
3559 case REQ_TOGGLE_GRAPHIC:
3560 case REQ_TOGGLE_REV_GRAPH:
3561 case REQ_TOGGLE_REFS:
3562 case REQ_TOGGLE_CHANGES:
3563 case REQ_TOGGLE_IGNORE_SPACE:
3564 case REQ_TOGGLE_ID:
3565 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3566 reload_view(view);
3567 break;
3569 case REQ_TOGGLE_SORT_FIELD:
3570 case REQ_TOGGLE_SORT_ORDER:
3571 report("Sorting is not yet supported for the %s view", view->name);
3572 break;
3574 case REQ_DIFF_CONTEXT_UP:
3575 case REQ_DIFF_CONTEXT_DOWN:
3576 report("Changing the diff context is not yet supported for the %s view", view->name);
3577 break;
3579 case REQ_SEARCH:
3580 case REQ_SEARCH_BACK:
3581 search_view(view, request);
3582 break;
3584 case REQ_FIND_NEXT:
3585 case REQ_FIND_PREV:
3586 find_next(view, request);
3587 break;
3589 case REQ_STOP_LOADING:
3590 foreach_view(view, i) {
3591 if (view->pipe)
3592 report("Stopped loading the %s view", view->name),
3593 end_update(view, TRUE);
3595 break;
3597 case REQ_SHOW_VERSION:
3598 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3599 return TRUE;
3601 case REQ_SCREEN_REDRAW:
3602 redraw_display(TRUE);
3603 break;
3605 case REQ_EDIT:
3606 report("Nothing to edit");
3607 break;
3609 case REQ_ENTER:
3610 report("Nothing to enter");
3611 break;
3613 case REQ_VIEW_CLOSE:
3614 /* XXX: Mark closed views by letting view->prev point to the
3615 * view itself. Parents to closed view should never be
3616 * followed. */
3617 if (view->prev && view->prev != view) {
3618 maximize_view(view->prev, TRUE);
3619 view->prev = view;
3620 break;
3622 /* Fall-through */
3623 case REQ_QUIT:
3624 return FALSE;
3626 default:
3627 report("Unknown key, press %s for help",
3628 get_view_key(view, REQ_VIEW_HELP));
3629 return TRUE;
3632 return TRUE;
3637 * View backend utilities
3640 enum sort_field {
3641 ORDERBY_NAME,
3642 ORDERBY_DATE,
3643 ORDERBY_AUTHOR,
3646 struct sort_state {
3647 const enum sort_field *fields;
3648 size_t size, current;
3649 bool reverse;
3652 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3653 #define get_sort_field(state) ((state).fields[(state).current])
3654 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3656 static void
3657 sort_view(struct view *view, enum request request, struct sort_state *state,
3658 int (*compare)(const void *, const void *))
3660 switch (request) {
3661 case REQ_TOGGLE_SORT_FIELD:
3662 state->current = (state->current + 1) % state->size;
3663 break;
3665 case REQ_TOGGLE_SORT_ORDER:
3666 state->reverse = !state->reverse;
3667 break;
3668 default:
3669 die("Not a sort request");
3672 qsort(view->line, view->lines, sizeof(*view->line), compare);
3673 redraw_view(view);
3676 static bool
3677 update_diff_context(enum request request)
3679 int diff_context = opt_diff_context;
3681 switch (request) {
3682 case REQ_DIFF_CONTEXT_UP:
3683 opt_diff_context += 1;
3684 update_diff_context_arg(opt_diff_context);
3685 break;
3687 case REQ_DIFF_CONTEXT_DOWN:
3688 if (opt_diff_context == 0) {
3689 report("Diff context cannot be less than zero");
3690 break;
3692 opt_diff_context -= 1;
3693 update_diff_context_arg(opt_diff_context);
3694 break;
3696 default:
3697 die("Not a diff context request");
3700 return diff_context != opt_diff_context;
3703 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3705 /* Small author cache to reduce memory consumption. It uses binary
3706 * search to lookup or find place to position new entries. No entries
3707 * are ever freed. */
3708 static const char *
3709 get_author(const char *name)
3711 static const char **authors;
3712 static size_t authors_size;
3713 int from = 0, to = authors_size - 1;
3715 while (from <= to) {
3716 size_t pos = (to + from) / 2;
3717 int cmp = strcmp(name, authors[pos]);
3719 if (!cmp)
3720 return authors[pos];
3722 if (cmp < 0)
3723 to = pos - 1;
3724 else
3725 from = pos + 1;
3728 if (!realloc_authors(&authors, authors_size, 1))
3729 return NULL;
3730 name = strdup(name);
3731 if (!name)
3732 return NULL;
3734 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3735 authors[from] = name;
3736 authors_size++;
3738 return name;
3741 static void
3742 parse_timesec(struct time *time, const char *sec)
3744 time->sec = (time_t) atol(sec);
3747 static void
3748 parse_timezone(struct time *time, const char *zone)
3750 long tz;
3752 tz = ('0' - zone[1]) * 60 * 60 * 10;
3753 tz += ('0' - zone[2]) * 60 * 60;
3754 tz += ('0' - zone[3]) * 60 * 10;
3755 tz += ('0' - zone[4]) * 60;
3757 if (zone[0] == '-')
3758 tz = -tz;
3760 time->tz = tz;
3761 time->sec -= tz;
3764 /* Parse author lines where the name may be empty:
3765 * author <email@address.tld> 1138474660 +0100
3767 static void
3768 parse_author_line(char *ident, const char **author, struct time *time)
3770 char *nameend = strchr(ident, '<');
3771 char *emailend = strchr(ident, '>');
3773 if (nameend && emailend)
3774 *nameend = *emailend = 0;
3775 ident = chomp_string(ident);
3776 if (!*ident) {
3777 if (nameend)
3778 ident = chomp_string(nameend + 1);
3779 if (!*ident)
3780 ident = "Unknown";
3783 *author = get_author(ident);
3785 /* Parse epoch and timezone */
3786 if (emailend && emailend[1] == ' ') {
3787 char *secs = emailend + 2;
3788 char *zone = strchr(secs, ' ');
3790 parse_timesec(time, secs);
3792 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3793 parse_timezone(time, zone + 1);
3797 static struct line *
3798 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
3800 for (; view_has_line(view, line); line += direction)
3801 if (line->type == type)
3802 return line;
3804 return NULL;
3807 #define find_prev_line_by_type(view, line, type) \
3808 find_line_by_type(view, line, type, -1)
3810 #define find_next_line_by_type(view, line, type) \
3811 find_line_by_type(view, line, type, 1)
3814 * Blame
3817 struct blame_commit {
3818 char id[SIZEOF_REV]; /* SHA1 ID. */
3819 char title[128]; /* First line of the commit message. */
3820 const char *author; /* Author of the commit. */
3821 struct time time; /* Date from the author ident. */
3822 char filename[128]; /* Name of file. */
3823 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3824 char parent_filename[128]; /* Parent/previous name of file. */
3827 struct blame_header {
3828 char id[SIZEOF_REV]; /* SHA1 ID. */
3829 size_t orig_lineno;
3830 size_t lineno;
3831 size_t group;
3834 static bool
3835 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3837 const char *pos = *posref;
3839 *posref = NULL;
3840 pos = strchr(pos + 1, ' ');
3841 if (!pos || !isdigit(pos[1]))
3842 return FALSE;
3843 *number = atoi(pos + 1);
3844 if (*number < min || *number > max)
3845 return FALSE;
3847 *posref = pos;
3848 return TRUE;
3851 static bool
3852 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3854 const char *pos = text + SIZEOF_REV - 2;
3856 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3857 return FALSE;
3859 string_ncopy(header->id, text, SIZEOF_REV);
3861 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3862 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3863 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3864 return FALSE;
3866 return TRUE;
3869 static bool
3870 match_blame_header(const char *name, char **line)
3872 size_t namelen = strlen(name);
3873 bool matched = !strncmp(name, *line, namelen);
3875 if (matched)
3876 *line += namelen;
3878 return matched;
3881 static bool
3882 parse_blame_info(struct blame_commit *commit, char *line)
3884 if (match_blame_header("author ", &line)) {
3885 commit->author = get_author(line);
3887 } else if (match_blame_header("author-time ", &line)) {
3888 parse_timesec(&commit->time, line);
3890 } else if (match_blame_header("author-tz ", &line)) {
3891 parse_timezone(&commit->time, line);
3893 } else if (match_blame_header("summary ", &line)) {
3894 string_ncopy(commit->title, line, strlen(line));
3896 } else if (match_blame_header("previous ", &line)) {
3897 if (strlen(line) <= SIZEOF_REV)
3898 return FALSE;
3899 string_copy_rev(commit->parent_id, line);
3900 line += SIZEOF_REV;
3901 string_ncopy(commit->parent_filename, line, strlen(line));
3903 } else if (match_blame_header("filename ", &line)) {
3904 string_ncopy(commit->filename, line, strlen(line));
3905 return TRUE;
3908 return FALSE;
3912 * Pager backend
3915 static bool
3916 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3918 if (draw_lineno(view, lineno))
3919 return TRUE;
3921 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
3922 return TRUE;
3924 draw_text(view, line->type, line->data);
3925 return TRUE;
3928 static bool
3929 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3931 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3932 char ref[SIZEOF_STR];
3934 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3935 return TRUE;
3937 /* This is the only fatal call, since it can "corrupt" the buffer. */
3938 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3939 return FALSE;
3941 return TRUE;
3944 static void
3945 add_pager_refs(struct view *view, const char *commit_id)
3947 char buf[SIZEOF_STR];
3948 struct ref_list *list;
3949 size_t bufpos = 0, i;
3950 const char *sep = "Refs: ";
3951 bool is_tag = FALSE;
3953 list = get_ref_list(commit_id);
3954 if (!list) {
3955 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3956 goto try_add_describe_ref;
3957 return;
3960 for (i = 0; i < list->size; i++) {
3961 struct ref *ref = list->refs[i];
3962 const char *fmt = ref->tag ? "%s[%s]" :
3963 ref->remote ? "%s<%s>" : "%s%s";
3965 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3966 return;
3967 sep = ", ";
3968 if (ref->tag)
3969 is_tag = TRUE;
3972 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3973 try_add_describe_ref:
3974 /* Add <tag>-g<commit_id> "fake" reference. */
3975 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3976 return;
3979 if (bufpos == 0)
3980 return;
3982 add_line_text(view, buf, LINE_PP_REFS);
3985 static struct line *
3986 pager_wrap_line(struct view *view, const char *data, enum line_type type)
3988 size_t first_line = 0;
3989 bool has_first_line = FALSE;
3990 size_t datalen = strlen(data);
3991 size_t lineno = 0;
3993 while (datalen > 0 || !has_first_line) {
3994 bool wrapped = !!first_line;
3995 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
3996 struct line *line;
3997 char *text;
3999 line = add_line(view, NULL, type, linelen + 1, wrapped);
4000 if (!line)
4001 break;
4002 if (!has_first_line) {
4003 first_line = view->lines - 1;
4004 has_first_line = TRUE;
4007 if (!wrapped)
4008 lineno = line->lineno;
4010 line->wrapped = wrapped;
4011 line->lineno = lineno;
4012 text = line->data;
4013 if (linelen)
4014 strncpy(text, data, linelen);
4015 text[linelen] = 0;
4017 datalen -= linelen;
4018 data += linelen;
4021 return has_first_line ? &view->line[first_line] : NULL;
4024 static bool
4025 pager_common_read(struct view *view, const char *data, enum line_type type)
4027 struct line *line;
4029 if (!data)
4030 return TRUE;
4032 if (opt_wrap_lines) {
4033 line = pager_wrap_line(view, data, type);
4034 } else {
4035 line = add_line_text(view, data, type);
4038 if (!line)
4039 return FALSE;
4041 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4042 add_pager_refs(view, data + STRING_SIZE("commit "));
4044 return TRUE;
4047 static bool
4048 pager_read(struct view *view, char *data)
4050 if (!data)
4051 return TRUE;
4053 return pager_common_read(view, data, get_line_type(data));
4056 static enum request
4057 pager_request(struct view *view, enum request request, struct line *line)
4059 int split = 0;
4061 if (request != REQ_ENTER)
4062 return request;
4064 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4065 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4066 split = 1;
4069 /* Always scroll the view even if it was split. That way
4070 * you can use Enter to scroll through the log view and
4071 * split open each commit diff. */
4072 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4074 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4075 * but if we are scrolling a non-current view this won't properly
4076 * update the view title. */
4077 if (split)
4078 update_view_title(view);
4080 return REQ_NONE;
4083 static bool
4084 pager_grep(struct view *view, struct line *line)
4086 const char *text[] = { line->data, NULL };
4088 return grep_text(view, text);
4091 static void
4092 pager_select(struct view *view, struct line *line)
4094 if (line->type == LINE_COMMIT) {
4095 char *text = (char *)line->data + STRING_SIZE("commit ");
4097 if (!view_has_flags(view, VIEW_NO_REF))
4098 string_copy_rev(view->ref, text);
4099 string_copy_rev(ref_commit, text);
4103 static bool
4104 pager_open(struct view *view, enum open_flags flags)
4106 if (display[0] == NULL) {
4107 if (!io_open(&view->io, "%s", ""))
4108 die("Failed to open stdin");
4109 flags = OPEN_PREPARED;
4111 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4112 report("No pager content, press %s to run command from prompt",
4113 get_view_key(view, REQ_PROMPT));
4114 return FALSE;
4117 return begin_update(view, NULL, NULL, flags);
4120 static struct view_ops pager_ops = {
4121 "line",
4122 { "pager" },
4123 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4125 pager_open,
4126 pager_read,
4127 pager_draw,
4128 pager_request,
4129 pager_grep,
4130 pager_select,
4133 static bool
4134 log_open(struct view *view, enum open_flags flags)
4136 static const char *log_argv[] = {
4137 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4140 return begin_update(view, NULL, log_argv, flags);
4143 static enum request
4144 log_request(struct view *view, enum request request, struct line *line)
4146 switch (request) {
4147 case REQ_REFRESH:
4148 load_refs();
4149 refresh_view(view);
4150 return REQ_NONE;
4151 default:
4152 return pager_request(view, request, line);
4156 static struct view_ops log_ops = {
4157 "line",
4158 { "log" },
4159 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
4161 log_open,
4162 pager_read,
4163 pager_draw,
4164 log_request,
4165 pager_grep,
4166 pager_select,
4169 struct diff_state {
4170 bool reading_diff_stat;
4171 bool combined_diff;
4174 static bool
4175 diff_open(struct view *view, enum open_flags flags)
4177 static const char *diff_argv[] = {
4178 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4179 "--patch-with-stat",
4180 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4181 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4184 return begin_update(view, NULL, diff_argv, flags);
4187 static bool
4188 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4190 enum line_type type = get_line_type(data);
4192 if (!view->lines && type != LINE_COMMIT)
4193 state->reading_diff_stat = TRUE;
4195 if (state->reading_diff_stat) {
4196 size_t len = strlen(data);
4197 char *pipe = strchr(data, '|');
4198 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4199 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4200 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4202 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4203 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4204 } else {
4205 state->reading_diff_stat = FALSE;
4208 } else if (!strcmp(data, "---")) {
4209 state->reading_diff_stat = TRUE;
4212 if (type == LINE_DIFF_HEADER) {
4213 const int len = line_info[LINE_DIFF_HEADER].linelen;
4215 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4216 !strncmp(data + len, "cc ", strlen("cc ")))
4217 state->combined_diff = TRUE;
4220 /* ADD2 and DEL2 are only valid in combined diff hunks */
4221 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4222 type = LINE_DEFAULT;
4224 return pager_common_read(view, data, type);
4227 static bool
4228 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4230 struct line *marker = find_next_line_by_type(view, line, type);
4232 return marker &&
4233 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4236 static enum request
4237 diff_common_enter(struct view *view, enum request request, struct line *line)
4239 if (line->type == LINE_DIFF_STAT) {
4240 int file_number = 0;
4242 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4243 file_number++;
4244 line--;
4247 for (line = view->line; view_has_line(view, line); line++) {
4248 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4249 if (!line)
4250 break;
4252 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4253 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4254 if (file_number == 1) {
4255 break;
4257 file_number--;
4261 if (!line) {
4262 report("Failed to find file diff");
4263 return REQ_NONE;
4266 select_view_line(view, line - view->line);
4267 report_clear();
4268 return REQ_NONE;
4270 } else {
4271 return pager_request(view, request, line);
4275 static bool
4276 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4278 char *sep = strchr(*text, c);
4280 if (sep != NULL) {
4281 *sep = 0;
4282 draw_text(view, *type, *text);
4283 *sep = c;
4284 *text = sep;
4285 *type = next_type;
4288 return sep != NULL;
4291 static bool
4292 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4294 char *text = line->data;
4295 enum line_type type = line->type;
4297 if (draw_lineno(view, lineno))
4298 return TRUE;
4300 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4301 return TRUE;
4303 if (type == LINE_DIFF_STAT) {
4304 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4305 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4306 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4307 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4308 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4309 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4310 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4312 } else {
4313 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4314 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4318 draw_text(view, type, text);
4319 return TRUE;
4322 static bool
4323 diff_read(struct view *view, char *data)
4325 struct diff_state *state = view->private;
4327 if (!data) {
4328 /* Fall back to retry if no diff will be shown. */
4329 if (view->lines == 0 && opt_file_argv) {
4330 int pos = argv_size(view->argv)
4331 - argv_size(opt_file_argv) - 1;
4333 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4334 for (; view->argv[pos]; pos++) {
4335 free((void *) view->argv[pos]);
4336 view->argv[pos] = NULL;
4339 if (view->pipe)
4340 io_done(view->pipe);
4341 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4342 return FALSE;
4345 return TRUE;
4348 return diff_common_read(view, data, state);
4351 static bool
4352 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4353 struct blame_header *header, struct blame_commit *commit)
4355 char line_arg[SIZEOF_STR];
4356 const char *blame_argv[] = {
4357 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4359 struct io io;
4360 bool ok = FALSE;
4361 char *buf;
4363 if (!string_format(line_arg, "-L%ld,+1", lineno))
4364 return FALSE;
4366 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4367 return FALSE;
4369 while ((buf = io_get(&io, '\n', TRUE))) {
4370 if (header) {
4371 if (!parse_blame_header(header, buf, 9999999))
4372 break;
4373 header = NULL;
4375 } else if (parse_blame_info(commit, buf)) {
4376 ok = TRUE;
4377 break;
4381 if (io_error(&io))
4382 ok = FALSE;
4384 io_done(&io);
4385 return ok;
4388 static bool
4389 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4391 return prefixcmp(chunk, "@@ -") ||
4392 !(chunk = strchr(chunk, marker)) ||
4393 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4396 static enum request
4397 diff_trace_origin(struct view *view, struct line *line)
4399 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4400 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4401 const char *chunk_data;
4402 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4403 int lineno = 0;
4404 const char *file = NULL;
4405 char ref[SIZEOF_REF];
4406 struct blame_header header;
4407 struct blame_commit commit;
4409 if (!diff || !chunk || chunk == line) {
4410 report("The line to trace must be inside a diff chunk");
4411 return REQ_NONE;
4414 for (; diff < line && !file; diff++) {
4415 const char *data = diff->data;
4417 if (!prefixcmp(data, "--- a/")) {
4418 file = data + STRING_SIZE("--- a/");
4419 break;
4423 if (diff == line || !file) {
4424 report("Failed to read the file name");
4425 return REQ_NONE;
4428 chunk_data = chunk->data;
4430 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4431 report("Failed to read the line number");
4432 return REQ_NONE;
4435 if (lineno == 0) {
4436 report("This is the origin of the line");
4437 return REQ_NONE;
4440 for (chunk += 1; chunk < line; chunk++) {
4441 if (chunk->type == LINE_DIFF_ADD) {
4442 lineno += chunk_marker == '+';
4443 } else if (chunk->type == LINE_DIFF_DEL) {
4444 lineno += chunk_marker == '-';
4445 } else {
4446 lineno++;
4450 if (chunk_marker == '+')
4451 string_copy(ref, view->vid);
4452 else
4453 string_format(ref, "%s^", view->vid);
4455 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4456 report("Failed to read blame data");
4457 return REQ_NONE;
4460 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4461 string_copy(opt_ref, header.id);
4462 opt_goto_line = header.orig_lineno - 1;
4464 return REQ_VIEW_BLAME;
4467 static const char *
4468 diff_get_pathname(struct view *view, struct line *line)
4470 const struct line *header;
4471 const char *dst = NULL;
4472 const char *prefixes[] = { " b/", "cc ", "combined " };
4473 int i;
4475 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4476 if (!header)
4477 return NULL;
4479 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4480 dst = strstr(header->data, prefixes[i]);
4482 return dst ? dst + strlen(prefixes[--i]) : NULL;
4485 static enum request
4486 diff_request(struct view *view, enum request request, struct line *line)
4488 const char *file;
4490 switch (request) {
4491 case REQ_VIEW_BLAME:
4492 return diff_trace_origin(view, line);
4494 case REQ_DIFF_CONTEXT_UP:
4495 case REQ_DIFF_CONTEXT_DOWN:
4496 if (!update_diff_context(request))
4497 return REQ_NONE;
4498 reload_view(view);
4499 return REQ_NONE;
4501 case REQ_EDIT:
4502 file = diff_get_pathname(view, line);
4503 if (!file || access(file, R_OK))
4504 return pager_request(view, request, line);
4505 open_editor(file);
4506 return REQ_NONE;
4508 case REQ_ENTER:
4509 return diff_common_enter(view, request, line);
4511 default:
4512 return pager_request(view, request, line);
4516 static void
4517 diff_select(struct view *view, struct line *line)
4519 const char *s;
4521 if (line->type == LINE_DIFF_STAT) {
4522 s = get_view_key(view, REQ_ENTER);
4523 string_format(view->ref, "Press '%s' to jump to file diff", s);
4524 } else {
4525 s = diff_get_pathname(view, line);
4526 if (s) {
4527 string_format(view->ref, "Changes to '%s'", s);
4528 } else {
4529 string_ncopy(view->ref, view->id, strlen(view->id));
4530 pager_select(view, line);
4535 static struct view_ops diff_ops = {
4536 "line",
4537 { "diff" },
4538 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN,
4539 sizeof(struct diff_state),
4540 diff_open,
4541 diff_read,
4542 diff_common_draw,
4543 diff_request,
4544 pager_grep,
4545 diff_select,
4549 * Help backend
4552 static bool
4553 help_draw(struct view *view, struct line *line, unsigned int lineno)
4555 if (line->type == LINE_HELP_KEYMAP) {
4556 struct keymap *keymap = line->data;
4558 draw_formatted(view, line->type, "[%c] %s bindings",
4559 keymap->hidden ? '+' : '-', keymap->name);
4560 return TRUE;
4561 } else {
4562 return pager_draw(view, line, lineno);
4566 static bool
4567 help_open_keymap_title(struct view *view, struct keymap *keymap)
4569 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4570 return keymap->hidden;
4573 static void
4574 help_open_keymap(struct view *view, struct keymap *keymap)
4576 const char *group = NULL;
4577 char buf[SIZEOF_STR];
4578 bool add_title = TRUE;
4579 int i;
4581 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4582 const char *key = NULL;
4584 if (req_info[i].request == REQ_NONE)
4585 continue;
4587 if (!req_info[i].request) {
4588 group = req_info[i].help;
4589 continue;
4592 key = get_keys(keymap, req_info[i].request, TRUE);
4593 if (!key || !*key)
4594 continue;
4596 if (add_title && help_open_keymap_title(view, keymap))
4597 return;
4598 add_title = FALSE;
4600 if (group) {
4601 add_line_text(view, group, LINE_HELP_GROUP);
4602 group = NULL;
4605 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4606 enum_name(req_info[i]), req_info[i].help);
4609 group = "External commands:";
4611 for (i = 0; i < run_requests; i++) {
4612 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4613 const char *key;
4615 if (!req || req->keymap != keymap)
4616 continue;
4618 key = get_key_name(req->key);
4619 if (!*key)
4620 key = "(no key defined)";
4622 if (add_title && help_open_keymap_title(view, keymap))
4623 return;
4624 add_title = FALSE;
4626 if (group) {
4627 add_line_text(view, group, LINE_HELP_GROUP);
4628 group = NULL;
4631 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4632 return;
4634 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4638 static bool
4639 help_open(struct view *view, enum open_flags flags)
4641 struct keymap *keymap;
4643 reset_view(view);
4644 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4645 add_line_text(view, "", LINE_DEFAULT);
4647 for (keymap = keymaps; keymap; keymap = keymap->next)
4648 help_open_keymap(view, keymap);
4650 return TRUE;
4653 static enum request
4654 help_request(struct view *view, enum request request, struct line *line)
4656 switch (request) {
4657 case REQ_ENTER:
4658 if (line->type == LINE_HELP_KEYMAP) {
4659 struct keymap *keymap = line->data;
4661 keymap->hidden = !keymap->hidden;
4662 refresh_view(view);
4665 return REQ_NONE;
4666 default:
4667 return pager_request(view, request, line);
4671 static struct view_ops help_ops = {
4672 "line",
4673 { "help" },
4674 VIEW_NO_GIT_DIR,
4676 help_open,
4677 NULL,
4678 help_draw,
4679 help_request,
4680 pager_grep,
4681 pager_select,
4686 * Tree backend
4689 struct tree_stack_entry {
4690 struct tree_stack_entry *prev; /* Entry below this in the stack */
4691 unsigned long lineno; /* Line number to restore */
4692 char *name; /* Position of name in opt_path */
4695 /* The top of the path stack. */
4696 static struct tree_stack_entry *tree_stack = NULL;
4697 unsigned long tree_lineno = 0;
4699 static void
4700 pop_tree_stack_entry(void)
4702 struct tree_stack_entry *entry = tree_stack;
4704 tree_lineno = entry->lineno;
4705 entry->name[0] = 0;
4706 tree_stack = entry->prev;
4707 free(entry);
4710 static void
4711 push_tree_stack_entry(const char *name, unsigned long lineno)
4713 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4714 size_t pathlen = strlen(opt_path);
4716 if (!entry)
4717 return;
4719 entry->prev = tree_stack;
4720 entry->name = opt_path + pathlen;
4721 tree_stack = entry;
4723 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4724 pop_tree_stack_entry();
4725 return;
4728 /* Move the current line to the first tree entry. */
4729 tree_lineno = 1;
4730 entry->lineno = lineno;
4733 /* Parse output from git-ls-tree(1):
4735 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4738 #define SIZEOF_TREE_ATTR \
4739 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4741 #define SIZEOF_TREE_MODE \
4742 STRING_SIZE("100644 ")
4744 #define TREE_ID_OFFSET \
4745 STRING_SIZE("100644 blob ")
4747 #define tree_path_is_parent(path) (!strcmp("..", (path)))
4749 struct tree_entry {
4750 char id[SIZEOF_REV];
4751 char commit[SIZEOF_REV];
4752 mode_t mode;
4753 struct time time; /* Date from the author ident. */
4754 const char *author; /* Author of the commit. */
4755 char name[1];
4758 struct tree_state {
4759 char commit[SIZEOF_REV];
4760 const char *author_name;
4761 struct time author_time;
4762 bool read_date;
4765 static const char *
4766 tree_path(const struct line *line)
4768 return ((struct tree_entry *) line->data)->name;
4771 static int
4772 tree_compare_entry(const struct line *line1, const struct line *line2)
4774 if (line1->type != line2->type)
4775 return line1->type == LINE_TREE_DIR ? -1 : 1;
4776 return strcmp(tree_path(line1), tree_path(line2));
4779 static const enum sort_field tree_sort_fields[] = {
4780 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4782 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4784 static int
4785 tree_compare(const void *l1, const void *l2)
4787 const struct line *line1 = (const struct line *) l1;
4788 const struct line *line2 = (const struct line *) l2;
4789 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4790 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4792 if (line1->type == LINE_TREE_HEAD)
4793 return -1;
4794 if (line2->type == LINE_TREE_HEAD)
4795 return 1;
4797 switch (get_sort_field(tree_sort_state)) {
4798 case ORDERBY_DATE:
4799 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4801 case ORDERBY_AUTHOR:
4802 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4804 case ORDERBY_NAME:
4805 default:
4806 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4811 static struct line *
4812 tree_entry(struct view *view, enum line_type type, const char *path,
4813 const char *mode, const char *id)
4815 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
4816 struct tree_entry *entry;
4817 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
4819 if (!line)
4820 return NULL;
4822 strncpy(entry->name, path, strlen(path));
4823 if (mode)
4824 entry->mode = strtoul(mode, NULL, 8);
4825 if (id)
4826 string_copy_rev(entry->id, id);
4828 return line;
4831 static bool
4832 tree_read_date(struct view *view, char *text, struct tree_state *state)
4834 if (!text && state->read_date) {
4835 state->read_date = FALSE;
4836 return TRUE;
4838 } else if (!text) {
4839 /* Find next entry to process */
4840 const char *log_file[] = {
4841 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
4842 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4845 if (!view->lines) {
4846 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4847 report("Tree is empty");
4848 return TRUE;
4851 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4852 report("Failed to load tree data");
4853 return TRUE;
4856 state->read_date = TRUE;
4857 return FALSE;
4859 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
4860 string_copy_rev(state->commit, text + STRING_SIZE("commit "));
4862 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4863 parse_author_line(text + STRING_SIZE("author "),
4864 &state->author_name, &state->author_time);
4866 } else if (*text == ':') {
4867 char *pos;
4868 size_t annotated = 1;
4869 size_t i;
4871 pos = strchr(text, '\t');
4872 if (!pos)
4873 return TRUE;
4874 text = pos + 1;
4875 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4876 text += strlen(opt_path);
4877 pos = strchr(text, '/');
4878 if (pos)
4879 *pos = 0;
4881 for (i = 1; i < view->lines; i++) {
4882 struct line *line = &view->line[i];
4883 struct tree_entry *entry = line->data;
4885 annotated += !!entry->author;
4886 if (entry->author || strcmp(entry->name, text))
4887 continue;
4889 string_copy_rev(entry->commit, state->commit);
4890 entry->author = state->author_name;
4891 entry->time = state->author_time;
4892 line->dirty = 1;
4893 break;
4896 if (annotated == view->lines)
4897 io_kill(view->pipe);
4899 return TRUE;
4902 static bool
4903 tree_read(struct view *view, char *text)
4905 struct tree_state *state = view->private;
4906 struct tree_entry *data;
4907 struct line *entry, *line;
4908 enum line_type type;
4909 size_t textlen = text ? strlen(text) : 0;
4910 char *path = text + SIZEOF_TREE_ATTR;
4912 if (state->read_date || !text)
4913 return tree_read_date(view, text, state);
4915 if (textlen <= SIZEOF_TREE_ATTR)
4916 return FALSE;
4917 if (view->lines == 0 &&
4918 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4919 return FALSE;
4921 /* Strip the path part ... */
4922 if (*opt_path) {
4923 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4924 size_t striplen = strlen(opt_path);
4926 if (pathlen > striplen)
4927 memmove(path, path + striplen,
4928 pathlen - striplen + 1);
4930 /* Insert "link" to parent directory. */
4931 if (view->lines == 1 &&
4932 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4933 return FALSE;
4936 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4937 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4938 if (!entry)
4939 return FALSE;
4940 data = entry->data;
4942 /* Skip "Directory ..." and ".." line. */
4943 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4944 if (tree_compare_entry(line, entry) <= 0)
4945 continue;
4947 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4949 line->data = data;
4950 line->type = type;
4951 for (; line <= entry; line++)
4952 line->dirty = line->cleareol = 1;
4953 return TRUE;
4956 if (tree_lineno <= view->pos.lineno)
4957 tree_lineno = view->custom_lines;
4959 if (tree_lineno > view->pos.lineno) {
4960 view->pos.lineno = tree_lineno;
4961 tree_lineno = 0;
4964 return TRUE;
4967 static bool
4968 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4970 struct tree_entry *entry = line->data;
4972 if (line->type == LINE_TREE_HEAD) {
4973 if (draw_text(view, line->type, "Directory path /"))
4974 return TRUE;
4975 } else {
4976 if (draw_mode(view, entry->mode))
4977 return TRUE;
4979 if (draw_author(view, entry->author))
4980 return TRUE;
4982 if (draw_date(view, &entry->time))
4983 return TRUE;
4985 if (opt_show_id && draw_id(view, LINE_ID, entry->commit))
4986 return TRUE;
4989 draw_text(view, line->type, entry->name);
4990 return TRUE;
4993 static void
4994 open_blob_editor(const char *id)
4996 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4997 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4998 int fd = mkstemp(file);
5000 if (fd == -1)
5001 report("Failed to create temporary file");
5002 else if (!io_run_append(blob_argv, fd))
5003 report("Failed to save blob data to file");
5004 else
5005 open_editor(file);
5006 if (fd != -1)
5007 unlink(file);
5010 static enum request
5011 tree_request(struct view *view, enum request request, struct line *line)
5013 enum open_flags flags;
5014 struct tree_entry *entry = line->data;
5016 switch (request) {
5017 case REQ_VIEW_BLAME:
5018 if (line->type != LINE_TREE_FILE) {
5019 report("Blame only supported for files");
5020 return REQ_NONE;
5023 string_copy(opt_ref, view->vid);
5024 return request;
5026 case REQ_EDIT:
5027 if (line->type != LINE_TREE_FILE) {
5028 report("Edit only supported for files");
5029 } else if (!is_head_commit(view->vid)) {
5030 open_blob_editor(entry->id);
5031 } else {
5032 open_editor(opt_file);
5034 return REQ_NONE;
5036 case REQ_TOGGLE_SORT_FIELD:
5037 case REQ_TOGGLE_SORT_ORDER:
5038 sort_view(view, request, &tree_sort_state, tree_compare);
5039 return REQ_NONE;
5041 case REQ_PARENT:
5042 if (!*opt_path) {
5043 /* quit view if at top of tree */
5044 return REQ_VIEW_CLOSE;
5046 /* fake 'cd ..' */
5047 line = &view->line[1];
5048 break;
5050 case REQ_ENTER:
5051 break;
5053 default:
5054 return request;
5057 /* Cleanup the stack if the tree view is at a different tree. */
5058 while (!*opt_path && tree_stack)
5059 pop_tree_stack_entry();
5061 switch (line->type) {
5062 case LINE_TREE_DIR:
5063 /* Depending on whether it is a subdirectory or parent link
5064 * mangle the path buffer. */
5065 if (line == &view->line[1] && *opt_path) {
5066 pop_tree_stack_entry();
5068 } else {
5069 const char *basename = tree_path(line);
5071 push_tree_stack_entry(basename, view->pos.lineno);
5074 /* Trees and subtrees share the same ID, so they are not not
5075 * unique like blobs. */
5076 flags = OPEN_RELOAD;
5077 request = REQ_VIEW_TREE;
5078 break;
5080 case LINE_TREE_FILE:
5081 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5082 request = REQ_VIEW_BLOB;
5083 break;
5085 default:
5086 return REQ_NONE;
5089 open_view(view, request, flags);
5090 if (request == REQ_VIEW_TREE)
5091 view->pos.lineno = tree_lineno;
5093 return REQ_NONE;
5096 static bool
5097 tree_grep(struct view *view, struct line *line)
5099 struct tree_entry *entry = line->data;
5100 const char *text[] = {
5101 entry->name,
5102 mkauthor(entry->author, opt_author_width, opt_author),
5103 mkdate(&entry->time, opt_date),
5104 NULL
5107 return grep_text(view, text);
5110 static void
5111 tree_select(struct view *view, struct line *line)
5113 struct tree_entry *entry = line->data;
5115 if (line->type == LINE_TREE_HEAD) {
5116 string_format(view->ref, "Files in /%s", opt_path);
5117 return;
5120 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5121 string_copy(view->ref, "Open parent directory");
5122 return;
5125 if (line->type == LINE_TREE_FILE) {
5126 string_copy_rev(ref_blob, entry->id);
5127 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5130 string_copy_rev(view->ref, entry->id);
5133 static bool
5134 tree_open(struct view *view, enum open_flags flags)
5136 static const char *tree_argv[] = {
5137 "git", "ls-tree", "%(commit)", "%(directory)", NULL
5140 if (string_rev_is_null(ref_commit)) {
5141 report("No tree exists for this commit");
5142 return FALSE;
5145 if (view->lines == 0 && opt_prefix[0]) {
5146 char *pos = opt_prefix;
5148 while (pos && *pos) {
5149 char *end = strchr(pos, '/');
5151 if (end)
5152 *end = 0;
5153 push_tree_stack_entry(pos, 0);
5154 pos = end;
5155 if (end) {
5156 *end = '/';
5157 pos++;
5161 } else if (strcmp(view->vid, view->id)) {
5162 opt_path[0] = 0;
5165 return begin_update(view, opt_cdup, tree_argv, flags);
5168 static struct view_ops tree_ops = {
5169 "file",
5170 { "tree" },
5171 VIEW_NO_FLAGS,
5172 sizeof(struct tree_state),
5173 tree_open,
5174 tree_read,
5175 tree_draw,
5176 tree_request,
5177 tree_grep,
5178 tree_select,
5181 static bool
5182 blob_open(struct view *view, enum open_flags flags)
5184 static const char *blob_argv[] = {
5185 "git", "cat-file", "blob", "%(blob)", NULL
5188 if (!ref_blob[0]) {
5189 report("No file chosen, press %s to open tree view",
5190 get_view_key(view, REQ_VIEW_TREE));
5191 return FALSE;
5194 view->encoding = get_path_encoding(opt_file, opt_encoding);
5196 return begin_update(view, NULL, blob_argv, flags);
5199 static bool
5200 blob_read(struct view *view, char *line)
5202 if (!line)
5203 return TRUE;
5204 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5207 static enum request
5208 blob_request(struct view *view, enum request request, struct line *line)
5210 switch (request) {
5211 case REQ_EDIT:
5212 open_blob_editor(view->vid);
5213 return REQ_NONE;
5214 default:
5215 return pager_request(view, request, line);
5219 static struct view_ops blob_ops = {
5220 "line",
5221 { "blob" },
5222 VIEW_NO_FLAGS,
5224 blob_open,
5225 blob_read,
5226 pager_draw,
5227 blob_request,
5228 pager_grep,
5229 pager_select,
5233 * Blame backend
5235 * Loading the blame view is a two phase job:
5237 * 1. File content is read either using opt_file from the
5238 * filesystem or using git-cat-file.
5239 * 2. Then blame information is incrementally added by
5240 * reading output from git-blame.
5243 struct blame {
5244 struct blame_commit *commit;
5245 unsigned long lineno;
5246 char text[1];
5249 struct blame_state {
5250 struct blame_commit *commit;
5251 int blamed;
5252 bool done_reading;
5253 bool auto_filename_display;
5256 static bool
5257 blame_detect_filename_display(struct view *view)
5259 bool show_filenames = FALSE;
5260 const char *filename = NULL;
5261 int i;
5263 if (opt_blame_argv) {
5264 for (i = 0; opt_blame_argv[i]; i++) {
5265 if (prefixcmp(opt_blame_argv[i], "-C"))
5266 continue;
5268 show_filenames = TRUE;
5272 for (i = 0; i < view->lines; i++) {
5273 struct blame *blame = view->line[i].data;
5275 if (blame->commit && blame->commit->id[0]) {
5276 if (!filename)
5277 filename = blame->commit->filename;
5278 else if (strcmp(filename, blame->commit->filename))
5279 show_filenames = TRUE;
5283 return show_filenames;
5286 static bool
5287 blame_open(struct view *view, enum open_flags flags)
5289 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5290 char path[SIZEOF_STR];
5291 size_t i;
5293 if (!opt_file[0]) {
5294 report("No file chosen, press %s to open tree view",
5295 get_view_key(view, REQ_VIEW_TREE));
5296 return FALSE;
5299 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5300 string_copy(path, opt_file);
5301 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5302 report("Failed to setup the blame view");
5303 return FALSE;
5307 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5308 const char *blame_cat_file_argv[] = {
5309 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5312 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5313 return FALSE;
5316 /* First pass: remove multiple references to the same commit. */
5317 for (i = 0; i < view->lines; i++) {
5318 struct blame *blame = view->line[i].data;
5320 if (blame->commit && blame->commit->id[0])
5321 blame->commit->id[0] = 0;
5322 else
5323 blame->commit = NULL;
5326 /* Second pass: free existing references. */
5327 for (i = 0; i < view->lines; i++) {
5328 struct blame *blame = view->line[i].data;
5330 if (blame->commit)
5331 free(blame->commit);
5334 string_format(view->vid, "%s", opt_file);
5335 string_format(view->ref, "%s ...", opt_file);
5337 return TRUE;
5340 static struct blame_commit *
5341 get_blame_commit(struct view *view, const char *id)
5343 size_t i;
5345 for (i = 0; i < view->lines; i++) {
5346 struct blame *blame = view->line[i].data;
5348 if (!blame->commit)
5349 continue;
5351 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5352 return blame->commit;
5356 struct blame_commit *commit = calloc(1, sizeof(*commit));
5358 if (commit)
5359 string_ncopy(commit->id, id, SIZEOF_REV);
5360 return commit;
5364 static struct blame_commit *
5365 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5367 struct blame_header header;
5368 struct blame_commit *commit;
5369 struct blame *blame;
5371 if (!parse_blame_header(&header, text, view->lines))
5372 return NULL;
5374 commit = get_blame_commit(view, text);
5375 if (!commit)
5376 return NULL;
5378 state->blamed += header.group;
5379 while (header.group--) {
5380 struct line *line = &view->line[header.lineno + header.group - 1];
5382 blame = line->data;
5383 blame->commit = commit;
5384 blame->lineno = header.orig_lineno + header.group - 1;
5385 line->dirty = 1;
5388 return commit;
5391 static bool
5392 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5394 if (!text) {
5395 const char *blame_argv[] = {
5396 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5397 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5400 if (view->lines == 0 && !view->prev)
5401 die("No blame exist for %s", view->vid);
5403 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5404 report("Failed to load blame data");
5405 return TRUE;
5408 if (opt_goto_line > 0) {
5409 select_view_line(view, opt_goto_line);
5410 opt_goto_line = 0;
5413 state->done_reading = TRUE;
5414 return FALSE;
5416 } else {
5417 size_t textlen = strlen(text);
5418 struct blame *blame;
5420 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5421 return FALSE;
5423 blame->commit = NULL;
5424 strncpy(blame->text, text, textlen);
5425 blame->text[textlen] = 0;
5426 return TRUE;
5430 static bool
5431 blame_read(struct view *view, char *line)
5433 struct blame_state *state = view->private;
5435 if (!state->done_reading)
5436 return blame_read_file(view, line, state);
5438 if (!line) {
5439 state->auto_filename_display = blame_detect_filename_display(view);
5440 string_format(view->ref, "%s", view->vid);
5441 if (view_is_displayed(view)) {
5442 update_view_title(view);
5443 redraw_view_from(view, 0);
5445 return TRUE;
5448 if (!state->commit) {
5449 state->commit = read_blame_commit(view, line, state);
5450 string_format(view->ref, "%s %2zd%%", view->vid,
5451 view->lines ? state->blamed * 100 / view->lines : 0);
5453 } else if (parse_blame_info(state->commit, line)) {
5454 state->commit = NULL;
5457 return TRUE;
5460 static bool
5461 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5463 struct blame_state *state = view->private;
5464 struct blame *blame = line->data;
5465 struct time *time = NULL;
5466 const char *id = NULL, *author = NULL, *filename = NULL;
5467 enum line_type id_type = LINE_ID;
5468 static const enum line_type blame_colors[] = {
5469 LINE_PALETTE_0,
5470 LINE_PALETTE_1,
5471 LINE_PALETTE_2,
5472 LINE_PALETTE_3,
5473 LINE_PALETTE_4,
5474 LINE_PALETTE_5,
5475 LINE_PALETTE_6,
5478 #define BLAME_COLOR(i) \
5479 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5481 if (blame->commit && *blame->commit->filename) {
5482 id = blame->commit->id;
5483 author = blame->commit->author;
5484 filename = blame->commit->filename;
5485 time = &blame->commit->time;
5486 id_type = BLAME_COLOR((long) blame->commit);
5489 if (draw_date(view, time))
5490 return TRUE;
5492 if (draw_author(view, author))
5493 return TRUE;
5495 if (draw_filename(view, filename, state->auto_filename_display))
5496 return TRUE;
5498 if (draw_id(view, id_type, id))
5499 return TRUE;
5501 if (draw_lineno(view, lineno))
5502 return TRUE;
5504 draw_text(view, LINE_DEFAULT, blame->text);
5505 return TRUE;
5508 static bool
5509 check_blame_commit(struct blame *blame, bool check_null_id)
5511 if (!blame->commit)
5512 report("Commit data not loaded yet");
5513 else if (check_null_id && string_rev_is_null(blame->commit->id))
5514 report("No commit exist for the selected line");
5515 else
5516 return TRUE;
5517 return FALSE;
5520 static void
5521 setup_blame_parent_line(struct view *view, struct blame *blame)
5523 char from[SIZEOF_REF + SIZEOF_STR];
5524 char to[SIZEOF_REF + SIZEOF_STR];
5525 const char *diff_tree_argv[] = {
5526 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
5527 "--no-color", "-U0", from, to, "--", NULL
5529 struct io io;
5530 int parent_lineno = -1;
5531 int blamed_lineno = -1;
5532 char *line;
5534 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5535 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5536 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5537 return;
5539 while ((line = io_get(&io, '\n', TRUE))) {
5540 if (*line == '@') {
5541 char *pos = strchr(line, '+');
5543 parent_lineno = atoi(line + 4);
5544 if (pos)
5545 blamed_lineno = atoi(pos + 1);
5547 } else if (*line == '+' && parent_lineno != -1) {
5548 if (blame->lineno == blamed_lineno - 1 &&
5549 !strcmp(blame->text, line + 1)) {
5550 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5551 break;
5553 blamed_lineno++;
5557 io_done(&io);
5560 static enum request
5561 blame_request(struct view *view, enum request request, struct line *line)
5563 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5564 struct blame *blame = line->data;
5566 switch (request) {
5567 case REQ_VIEW_BLAME:
5568 if (check_blame_commit(blame, TRUE)) {
5569 string_copy(opt_ref, blame->commit->id);
5570 string_copy(opt_file, blame->commit->filename);
5571 if (blame->lineno)
5572 view->pos.lineno = blame->lineno;
5573 reload_view(view);
5575 break;
5577 case REQ_PARENT:
5578 if (!check_blame_commit(blame, TRUE))
5579 break;
5580 if (!*blame->commit->parent_id) {
5581 report("The selected commit has no parents");
5582 } else {
5583 string_copy_rev(opt_ref, blame->commit->parent_id);
5584 string_copy(opt_file, blame->commit->parent_filename);
5585 setup_blame_parent_line(view, blame);
5586 opt_goto_line = blame->lineno;
5587 reload_view(view);
5589 break;
5591 case REQ_ENTER:
5592 if (!check_blame_commit(blame, FALSE))
5593 break;
5595 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5596 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5597 break;
5599 if (string_rev_is_null(blame->commit->id)) {
5600 struct view *diff = VIEW(REQ_VIEW_DIFF);
5601 const char *diff_parent_argv[] = {
5602 GIT_DIFF_BLAME(opt_encoding_arg,
5603 opt_diff_context_arg,
5604 opt_ignore_space_arg, view->vid)
5606 const char *diff_no_parent_argv[] = {
5607 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
5608 opt_diff_context_arg,
5609 opt_ignore_space_arg, view->vid)
5611 const char **diff_index_argv = *blame->commit->parent_id
5612 ? diff_parent_argv : diff_no_parent_argv;
5614 open_argv(view, diff, diff_index_argv, NULL, flags);
5615 if (diff->pipe)
5616 string_copy_rev(diff->ref, NULL_ID);
5617 } else {
5618 open_view(view, REQ_VIEW_DIFF, flags);
5620 break;
5622 default:
5623 return request;
5626 return REQ_NONE;
5629 static bool
5630 blame_grep(struct view *view, struct line *line)
5632 struct blame *blame = line->data;
5633 struct blame_commit *commit = blame->commit;
5634 const char *text[] = {
5635 blame->text,
5636 commit ? commit->title : "",
5637 commit ? commit->id : "",
5638 commit && opt_author ? commit->author : "",
5639 commit ? mkdate(&commit->time, opt_date) : "",
5640 NULL
5643 return grep_text(view, text);
5646 static void
5647 blame_select(struct view *view, struct line *line)
5649 struct blame *blame = line->data;
5650 struct blame_commit *commit = blame->commit;
5652 if (!commit)
5653 return;
5655 if (string_rev_is_null(commit->id))
5656 string_ncopy(ref_commit, "HEAD", 4);
5657 else
5658 string_copy_rev(ref_commit, commit->id);
5661 static struct view_ops blame_ops = {
5662 "line",
5663 { "blame" },
5664 VIEW_ALWAYS_LINENO,
5665 sizeof(struct blame_state),
5666 blame_open,
5667 blame_read,
5668 blame_draw,
5669 blame_request,
5670 blame_grep,
5671 blame_select,
5675 * Branch backend
5678 struct branch {
5679 const char *author; /* Author of the last commit. */
5680 struct time time; /* Date of the last activity. */
5681 char title[128]; /* First line of the commit message. */
5682 const struct ref *ref; /* Name and commit ID information. */
5685 static const struct ref branch_all;
5686 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5688 static const enum sort_field branch_sort_fields[] = {
5689 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5691 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5693 struct branch_state {
5694 char id[SIZEOF_REV];
5695 size_t max_ref_length;
5698 static int
5699 branch_compare(const void *l1, const void *l2)
5701 const struct branch *branch1 = ((const struct line *) l1)->data;
5702 const struct branch *branch2 = ((const struct line *) l2)->data;
5704 if (branch_is_all(branch1))
5705 return -1;
5706 else if (branch_is_all(branch2))
5707 return 1;
5709 switch (get_sort_field(branch_sort_state)) {
5710 case ORDERBY_DATE:
5711 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5713 case ORDERBY_AUTHOR:
5714 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5716 case ORDERBY_NAME:
5717 default:
5718 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5722 static bool
5723 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5725 struct branch_state *state = view->private;
5726 struct branch *branch = line->data;
5727 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5728 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
5730 if (draw_date(view, &branch->time))
5731 return TRUE;
5733 if (draw_author(view, branch->author))
5734 return TRUE;
5736 if (draw_field(view, type, branch_name, state->max_ref_length, FALSE))
5737 return TRUE;
5739 if (opt_show_id && draw_id(view, LINE_ID, branch->ref->id))
5740 return TRUE;
5742 draw_text(view, LINE_DEFAULT, branch->title);
5743 return TRUE;
5746 static enum request
5747 branch_request(struct view *view, enum request request, struct line *line)
5749 struct branch *branch = line->data;
5751 switch (request) {
5752 case REQ_REFRESH:
5753 load_refs();
5754 refresh_view(view);
5755 return REQ_NONE;
5757 case REQ_TOGGLE_SORT_FIELD:
5758 case REQ_TOGGLE_SORT_ORDER:
5759 sort_view(view, request, &branch_sort_state, branch_compare);
5760 return REQ_NONE;
5762 case REQ_ENTER:
5764 const struct ref *ref = branch->ref;
5765 const char *all_branches_argv[] = {
5766 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
5768 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5770 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5771 return REQ_NONE;
5773 case REQ_JUMP_COMMIT:
5775 int lineno;
5777 for (lineno = 0; lineno < view->lines; lineno++) {
5778 struct branch *branch = view->line[lineno].data;
5780 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5781 select_view_line(view, lineno);
5782 report_clear();
5783 return REQ_NONE;
5787 default:
5788 return request;
5792 static bool
5793 branch_read(struct view *view, char *line)
5795 struct branch_state *state = view->private;
5796 const char *title = NULL;
5797 const char *author = NULL;
5798 struct time time = {};
5799 size_t i;
5801 if (!line)
5802 return TRUE;
5804 switch (get_line_type(line)) {
5805 case LINE_COMMIT:
5806 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5807 return TRUE;
5809 case LINE_AUTHOR:
5810 parse_author_line(line + STRING_SIZE("author "), &author, &time);
5812 default:
5813 title = line + STRING_SIZE("title ");
5816 for (i = 0; i < view->lines; i++) {
5817 struct branch *branch = view->line[i].data;
5819 if (strcmp(branch->ref->id, state->id))
5820 continue;
5822 if (author) {
5823 branch->author = author;
5824 branch->time = time;
5827 if (title)
5828 string_expand(branch->title, sizeof(branch->title), title, 1);
5830 view->line[i].dirty = TRUE;
5833 return TRUE;
5836 static bool
5837 branch_open_visitor(void *data, const struct ref *ref)
5839 struct view *view = data;
5840 struct branch_state *state = view->private;
5841 struct branch *branch;
5842 size_t ref_length;
5844 if (ref->tag || ref->ltag)
5845 return TRUE;
5847 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, ref == &branch_all))
5848 return FALSE;
5850 ref_length = strlen(ref->name);
5851 if (ref_length > state->max_ref_length)
5852 state->max_ref_length = ref_length;
5854 branch->ref = ref;
5855 return TRUE;
5858 static bool
5859 branch_open(struct view *view, enum open_flags flags)
5861 const char *branch_log[] = {
5862 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
5863 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
5864 "--all", "--simplify-by-decoration", NULL
5867 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5868 report("Failed to load branch data");
5869 return FALSE;
5872 branch_open_visitor(view, &branch_all);
5873 foreach_ref(branch_open_visitor, view);
5875 return TRUE;
5878 static bool
5879 branch_grep(struct view *view, struct line *line)
5881 struct branch *branch = line->data;
5882 const char *text[] = {
5883 branch->ref->name,
5884 mkauthor(branch->author, opt_author_width, opt_author),
5885 NULL
5888 return grep_text(view, text);
5891 static void
5892 branch_select(struct view *view, struct line *line)
5894 struct branch *branch = line->data;
5896 if (branch_is_all(branch)) {
5897 string_copy(view->ref, "All branches");
5898 return;
5900 string_copy_rev(view->ref, branch->ref->id);
5901 string_copy_rev(ref_commit, branch->ref->id);
5902 string_copy_rev(ref_head, branch->ref->id);
5903 string_copy_rev(ref_branch, branch->ref->name);
5906 static struct view_ops branch_ops = {
5907 "branch",
5908 { "branch" },
5909 VIEW_NO_FLAGS,
5910 sizeof(struct branch_state),
5911 branch_open,
5912 branch_read,
5913 branch_draw,
5914 branch_request,
5915 branch_grep,
5916 branch_select,
5920 * Status backend
5923 struct status {
5924 char status;
5925 struct {
5926 mode_t mode;
5927 char rev[SIZEOF_REV];
5928 char name[SIZEOF_STR];
5929 } old;
5930 struct {
5931 mode_t mode;
5932 char rev[SIZEOF_REV];
5933 char name[SIZEOF_STR];
5934 } new;
5937 static char status_onbranch[SIZEOF_STR];
5938 static struct status stage_status;
5939 static enum line_type stage_line_type;
5941 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5943 /* This should work even for the "On branch" line. */
5944 static inline bool
5945 status_has_none(struct view *view, struct line *line)
5947 return view_has_line(view, line) && !line[1].data;
5950 /* Get fields from the diff line:
5951 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5953 static inline bool
5954 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5956 const char *old_mode = buf + 1;
5957 const char *new_mode = buf + 8;
5958 const char *old_rev = buf + 15;
5959 const char *new_rev = buf + 56;
5960 const char *status = buf + 97;
5962 if (bufsize < 98 ||
5963 old_mode[-1] != ':' ||
5964 new_mode[-1] != ' ' ||
5965 old_rev[-1] != ' ' ||
5966 new_rev[-1] != ' ' ||
5967 status[-1] != ' ')
5968 return FALSE;
5970 file->status = *status;
5972 string_copy_rev(file->old.rev, old_rev);
5973 string_copy_rev(file->new.rev, new_rev);
5975 file->old.mode = strtoul(old_mode, NULL, 8);
5976 file->new.mode = strtoul(new_mode, NULL, 8);
5978 file->old.name[0] = file->new.name[0] = 0;
5980 return TRUE;
5983 static bool
5984 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5986 struct status *unmerged = NULL;
5987 char *buf;
5988 struct io io;
5990 if (!io_run(&io, IO_RD, opt_cdup, argv))
5991 return FALSE;
5993 add_line_nodata(view, type);
5995 while ((buf = io_get(&io, 0, TRUE))) {
5996 struct status *file = unmerged;
5998 if (!file) {
5999 if (!add_line_alloc(view, &file, type, 0, FALSE))
6000 goto error_out;
6003 /* Parse diff info part. */
6004 if (status) {
6005 file->status = status;
6006 if (status == 'A')
6007 string_copy(file->old.rev, NULL_ID);
6009 } else if (!file->status || file == unmerged) {
6010 if (!status_get_diff(file, buf, strlen(buf)))
6011 goto error_out;
6013 buf = io_get(&io, 0, TRUE);
6014 if (!buf)
6015 break;
6017 /* Collapse all modified entries that follow an
6018 * associated unmerged entry. */
6019 if (unmerged == file) {
6020 unmerged->status = 'U';
6021 unmerged = NULL;
6022 } else if (file->status == 'U') {
6023 unmerged = file;
6027 /* Grab the old name for rename/copy. */
6028 if (!*file->old.name &&
6029 (file->status == 'R' || file->status == 'C')) {
6030 string_ncopy(file->old.name, buf, strlen(buf));
6032 buf = io_get(&io, 0, TRUE);
6033 if (!buf)
6034 break;
6037 /* git-ls-files just delivers a NUL separated list of
6038 * file names similar to the second half of the
6039 * git-diff-* output. */
6040 string_ncopy(file->new.name, buf, strlen(buf));
6041 if (!*file->old.name)
6042 string_copy(file->old.name, file->new.name);
6043 file = NULL;
6046 if (io_error(&io)) {
6047 error_out:
6048 io_done(&io);
6049 return FALSE;
6052 if (!view->line[view->lines - 1].data)
6053 add_line_nodata(view, LINE_STAT_NONE);
6055 io_done(&io);
6056 return TRUE;
6059 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6060 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6062 static const char *status_list_other_argv[] = {
6063 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6066 static const char *status_list_no_head_argv[] = {
6067 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6070 static const char *update_index_argv[] = {
6071 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6074 /* Restore the previous line number to stay in the context or select a
6075 * line with something that can be updated. */
6076 static void
6077 status_restore(struct view *view)
6079 if (!check_position(&view->prev_pos))
6080 return;
6082 if (view->prev_pos.lineno >= view->lines)
6083 view->prev_pos.lineno = view->lines - 1;
6084 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6085 view->prev_pos.lineno++;
6086 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6087 view->prev_pos.lineno--;
6089 /* If the above fails, always skip the "On branch" line. */
6090 if (view->prev_pos.lineno < view->lines)
6091 view->pos.lineno = view->prev_pos.lineno;
6092 else
6093 view->pos.lineno = 1;
6095 if (view->prev_pos.offset > view->pos.lineno)
6096 view->pos.offset = view->pos.lineno;
6097 else if (view->prev_pos.offset < view->lines)
6098 view->pos.offset = view->prev_pos.offset;
6100 clear_position(&view->prev_pos);
6103 static void
6104 status_update_onbranch(void)
6106 static const char *paths[][2] = {
6107 { "rebase-apply/rebasing", "Rebasing" },
6108 { "rebase-apply/applying", "Applying mailbox" },
6109 { "rebase-apply/", "Rebasing mailbox" },
6110 { "rebase-merge/interactive", "Interactive rebase" },
6111 { "rebase-merge/", "Rebase merge" },
6112 { "MERGE_HEAD", "Merging" },
6113 { "BISECT_LOG", "Bisecting" },
6114 { "HEAD", "On branch" },
6116 char buf[SIZEOF_STR];
6117 struct stat stat;
6118 int i;
6120 if (is_initial_commit()) {
6121 string_copy(status_onbranch, "Initial commit");
6122 return;
6125 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6126 char *head = opt_head;
6128 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6129 lstat(buf, &stat) < 0)
6130 continue;
6132 if (!*opt_head) {
6133 struct io io;
6135 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6136 io_read_buf(&io, buf, sizeof(buf))) {
6137 head = buf;
6138 if (!prefixcmp(head, "refs/heads/"))
6139 head += STRING_SIZE("refs/heads/");
6143 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6144 string_copy(status_onbranch, opt_head);
6145 return;
6148 string_copy(status_onbranch, "Not currently on any branch");
6151 /* First parse staged info using git-diff-index(1), then parse unstaged
6152 * info using git-diff-files(1), and finally untracked files using
6153 * git-ls-files(1). */
6154 static bool
6155 status_open(struct view *view, enum open_flags flags)
6157 const char **staged_argv = is_initial_commit() ?
6158 status_list_no_head_argv : status_diff_index_argv;
6159 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6161 if (opt_is_inside_work_tree == FALSE) {
6162 report("The status view requires a working tree");
6163 return FALSE;
6166 reset_view(view);
6168 add_line_nodata(view, LINE_STAT_HEAD);
6169 status_update_onbranch();
6171 io_run_bg(update_index_argv);
6173 if (!opt_untracked_dirs_content)
6174 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6176 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6177 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6178 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6179 report("Failed to load status data");
6180 return FALSE;
6183 /* Restore the exact position or use the specialized restore
6184 * mode? */
6185 status_restore(view);
6186 return TRUE;
6189 static bool
6190 status_draw(struct view *view, struct line *line, unsigned int lineno)
6192 struct status *status = line->data;
6193 enum line_type type;
6194 const char *text;
6196 if (!status) {
6197 switch (line->type) {
6198 case LINE_STAT_STAGED:
6199 type = LINE_STAT_SECTION;
6200 text = "Changes to be committed:";
6201 break;
6203 case LINE_STAT_UNSTAGED:
6204 type = LINE_STAT_SECTION;
6205 text = "Changed but not updated:";
6206 break;
6208 case LINE_STAT_UNTRACKED:
6209 type = LINE_STAT_SECTION;
6210 text = "Untracked files:";
6211 break;
6213 case LINE_STAT_NONE:
6214 type = LINE_DEFAULT;
6215 text = " (no files)";
6216 break;
6218 case LINE_STAT_HEAD:
6219 type = LINE_STAT_HEAD;
6220 text = status_onbranch;
6221 break;
6223 default:
6224 return FALSE;
6226 } else {
6227 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6229 buf[0] = status->status;
6230 if (draw_text(view, line->type, buf))
6231 return TRUE;
6232 type = LINE_DEFAULT;
6233 text = status->new.name;
6236 draw_text(view, type, text);
6237 return TRUE;
6240 static enum request
6241 status_enter(struct view *view, struct line *line)
6243 struct status *status = line->data;
6244 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6246 if (line->type == LINE_STAT_NONE ||
6247 (!status && line[1].type == LINE_STAT_NONE)) {
6248 report("No file to diff");
6249 return REQ_NONE;
6252 switch (line->type) {
6253 case LINE_STAT_STAGED:
6254 case LINE_STAT_UNSTAGED:
6255 break;
6257 case LINE_STAT_UNTRACKED:
6258 if (!status) {
6259 report("No file to show");
6260 return REQ_NONE;
6263 if (!suffixcmp(status->new.name, -1, "/")) {
6264 report("Cannot display a directory");
6265 return REQ_NONE;
6267 break;
6269 case LINE_STAT_HEAD:
6270 return REQ_NONE;
6272 default:
6273 die("line type %d not handled in switch", line->type);
6276 if (status) {
6277 stage_status = *status;
6278 } else {
6279 memset(&stage_status, 0, sizeof(stage_status));
6282 stage_line_type = line->type;
6284 open_view(view, REQ_VIEW_STAGE, flags);
6285 return REQ_NONE;
6288 static bool
6289 status_exists(struct view *view, struct status *status, enum line_type type)
6291 unsigned long lineno;
6293 for (lineno = 0; lineno < view->lines; lineno++) {
6294 struct line *line = &view->line[lineno];
6295 struct status *pos = line->data;
6297 if (line->type != type)
6298 continue;
6299 if (!pos && (!status || !status->status) && line[1].data) {
6300 select_view_line(view, lineno);
6301 return TRUE;
6303 if (pos && !strcmp(status->new.name, pos->new.name)) {
6304 select_view_line(view, lineno);
6305 return TRUE;
6309 return FALSE;
6313 static bool
6314 status_update_prepare(struct io *io, enum line_type type)
6316 const char *staged_argv[] = {
6317 "git", "update-index", "-z", "--index-info", NULL
6319 const char *others_argv[] = {
6320 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6323 switch (type) {
6324 case LINE_STAT_STAGED:
6325 return io_run(io, IO_WR, opt_cdup, staged_argv);
6327 case LINE_STAT_UNSTAGED:
6328 case LINE_STAT_UNTRACKED:
6329 return io_run(io, IO_WR, opt_cdup, others_argv);
6331 default:
6332 die("line type %d not handled in switch", type);
6333 return FALSE;
6337 static bool
6338 status_update_write(struct io *io, struct status *status, enum line_type type)
6340 switch (type) {
6341 case LINE_STAT_STAGED:
6342 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6343 status->old.rev, status->old.name, 0);
6345 case LINE_STAT_UNSTAGED:
6346 case LINE_STAT_UNTRACKED:
6347 return io_printf(io, "%s%c", status->new.name, 0);
6349 default:
6350 die("line type %d not handled in switch", type);
6351 return FALSE;
6355 static bool
6356 status_update_file(struct status *status, enum line_type type)
6358 struct io io;
6359 bool result;
6361 if (!status_update_prepare(&io, type))
6362 return FALSE;
6364 result = status_update_write(&io, status, type);
6365 return io_done(&io) && result;
6368 static bool
6369 status_update_files(struct view *view, struct line *line)
6371 char buf[sizeof(view->ref)];
6372 struct io io;
6373 bool result = TRUE;
6374 struct line *pos;
6375 int files = 0;
6376 int file, done;
6377 int cursor_y = -1, cursor_x = -1;
6379 if (!status_update_prepare(&io, line->type))
6380 return FALSE;
6382 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6383 files++;
6385 string_copy(buf, view->ref);
6386 getsyx(cursor_y, cursor_x);
6387 for (file = 0, done = 5; result && file < files; line++, file++) {
6388 int almost_done = file * 100 / files;
6390 if (almost_done > done) {
6391 done = almost_done;
6392 string_format(view->ref, "updating file %u of %u (%d%% done)",
6393 file, files, done);
6394 update_view_title(view);
6395 setsyx(cursor_y, cursor_x);
6396 doupdate();
6398 result = status_update_write(&io, line->data, line->type);
6400 string_copy(view->ref, buf);
6402 return io_done(&io) && result;
6405 static bool
6406 status_update(struct view *view)
6408 struct line *line = &view->line[view->pos.lineno];
6410 assert(view->lines);
6412 if (!line->data) {
6413 if (status_has_none(view, line)) {
6414 report("Nothing to update");
6415 return FALSE;
6418 if (!status_update_files(view, line + 1)) {
6419 report("Failed to update file status");
6420 return FALSE;
6423 } else if (!status_update_file(line->data, line->type)) {
6424 report("Failed to update file status");
6425 return FALSE;
6428 return TRUE;
6431 static bool
6432 status_revert(struct status *status, enum line_type type, bool has_none)
6434 if (!status || type != LINE_STAT_UNSTAGED) {
6435 if (type == LINE_STAT_STAGED) {
6436 report("Cannot revert changes to staged files");
6437 } else if (type == LINE_STAT_UNTRACKED) {
6438 report("Cannot revert changes to untracked files");
6439 } else if (has_none) {
6440 report("Nothing to revert");
6441 } else {
6442 report("Cannot revert changes to multiple files");
6445 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6446 char mode[10] = "100644";
6447 const char *reset_argv[] = {
6448 "git", "update-index", "--cacheinfo", mode,
6449 status->old.rev, status->old.name, NULL
6451 const char *checkout_argv[] = {
6452 "git", "checkout", "--", status->old.name, NULL
6455 if (status->status == 'U') {
6456 string_format(mode, "%5o", status->old.mode);
6458 if (status->old.mode == 0 && status->new.mode == 0) {
6459 reset_argv[2] = "--force-remove";
6460 reset_argv[3] = status->old.name;
6461 reset_argv[4] = NULL;
6464 if (!io_run_fg(reset_argv, opt_cdup))
6465 return FALSE;
6466 if (status->old.mode == 0 && status->new.mode == 0)
6467 return TRUE;
6470 return io_run_fg(checkout_argv, opt_cdup);
6473 return FALSE;
6476 static enum request
6477 status_request(struct view *view, enum request request, struct line *line)
6479 struct status *status = line->data;
6481 switch (request) {
6482 case REQ_STATUS_UPDATE:
6483 if (!status_update(view))
6484 return REQ_NONE;
6485 break;
6487 case REQ_STATUS_REVERT:
6488 if (!status_revert(status, line->type, status_has_none(view, line)))
6489 return REQ_NONE;
6490 break;
6492 case REQ_STATUS_MERGE:
6493 if (!status || status->status != 'U') {
6494 report("Merging only possible for files with unmerged status ('U').");
6495 return REQ_NONE;
6497 open_mergetool(status->new.name);
6498 break;
6500 case REQ_EDIT:
6501 if (!status)
6502 return request;
6503 if (status->status == 'D') {
6504 report("File has been deleted.");
6505 return REQ_NONE;
6508 open_editor(status->new.name);
6509 break;
6511 case REQ_VIEW_BLAME:
6512 if (status)
6513 opt_ref[0] = 0;
6514 return request;
6516 case REQ_ENTER:
6517 /* After returning the status view has been split to
6518 * show the stage view. No further reloading is
6519 * necessary. */
6520 return status_enter(view, line);
6522 case REQ_REFRESH:
6523 /* Simply reload the view. */
6524 break;
6526 default:
6527 return request;
6530 refresh_view(view);
6532 return REQ_NONE;
6535 static void
6536 status_select(struct view *view, struct line *line)
6538 struct status *status = line->data;
6539 char file[SIZEOF_STR] = "all files";
6540 const char *text;
6541 const char *key;
6543 if (status && !string_format(file, "'%s'", status->new.name))
6544 return;
6546 if (!status && line[1].type == LINE_STAT_NONE)
6547 line++;
6549 switch (line->type) {
6550 case LINE_STAT_STAGED:
6551 text = "Press %s to unstage %s for commit";
6552 break;
6554 case LINE_STAT_UNSTAGED:
6555 text = "Press %s to stage %s for commit";
6556 break;
6558 case LINE_STAT_UNTRACKED:
6559 text = "Press %s to stage %s for addition";
6560 break;
6562 case LINE_STAT_HEAD:
6563 case LINE_STAT_NONE:
6564 text = "Nothing to update";
6565 break;
6567 default:
6568 die("line type %d not handled in switch", line->type);
6571 if (status && status->status == 'U') {
6572 text = "Press %s to resolve conflict in %s";
6573 key = get_view_key(view, REQ_STATUS_MERGE);
6575 } else {
6576 key = get_view_key(view, REQ_STATUS_UPDATE);
6579 string_format(view->ref, text, key, file);
6580 if (status)
6581 string_copy(opt_file, status->new.name);
6584 static bool
6585 status_grep(struct view *view, struct line *line)
6587 struct status *status = line->data;
6589 if (status) {
6590 const char buf[2] = { status->status, 0 };
6591 const char *text[] = { status->new.name, buf, NULL };
6593 return grep_text(view, text);
6596 return FALSE;
6599 static struct view_ops status_ops = {
6600 "file",
6601 { "status" },
6602 VIEW_CUSTOM_STATUS,
6604 status_open,
6605 NULL,
6606 status_draw,
6607 status_request,
6608 status_grep,
6609 status_select,
6613 struct stage_state {
6614 struct diff_state diff;
6615 size_t chunks;
6616 int *chunk;
6619 static bool
6620 stage_diff_write(struct io *io, struct line *line, struct line *end)
6622 while (line < end) {
6623 if (!io_write(io, line->data, strlen(line->data)) ||
6624 !io_write(io, "\n", 1))
6625 return FALSE;
6626 line++;
6627 if (line->type == LINE_DIFF_CHUNK ||
6628 line->type == LINE_DIFF_HEADER)
6629 break;
6632 return TRUE;
6635 static bool
6636 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6638 const char *apply_argv[SIZEOF_ARG] = {
6639 "git", "apply", "--whitespace=nowarn", NULL
6641 struct line *diff_hdr;
6642 struct io io;
6643 int argc = 3;
6645 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6646 if (!diff_hdr)
6647 return FALSE;
6649 if (!revert)
6650 apply_argv[argc++] = "--cached";
6651 if (line != NULL)
6652 apply_argv[argc++] = "--unidiff-zero";
6653 if (revert || stage_line_type == LINE_STAT_STAGED)
6654 apply_argv[argc++] = "-R";
6655 apply_argv[argc++] = "-";
6656 apply_argv[argc++] = NULL;
6657 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6658 return FALSE;
6660 if (line != NULL) {
6661 int lineno = 0;
6662 struct line *context = chunk + 1;
6663 const char *markers[] = {
6664 line->type == LINE_DIFF_DEL ? "" : ",0",
6665 line->type == LINE_DIFF_DEL ? ",0" : "",
6668 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6670 while (context < line) {
6671 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6672 break;
6673 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6674 lineno++;
6676 context++;
6679 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6680 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6681 lineno, markers[0], lineno, markers[1]) ||
6682 !stage_diff_write(&io, line, line + 1)) {
6683 chunk = NULL;
6685 } else {
6686 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6687 !stage_diff_write(&io, chunk, view->line + view->lines))
6688 chunk = NULL;
6691 io_done(&io);
6692 io_run_bg(update_index_argv);
6694 return chunk ? TRUE : FALSE;
6697 static bool
6698 stage_update(struct view *view, struct line *line, bool single)
6700 struct line *chunk = NULL;
6702 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6703 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6705 if (chunk) {
6706 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6707 report("Failed to apply chunk");
6708 return FALSE;
6711 } else if (!stage_status.status) {
6712 view = view->parent;
6714 for (line = view->line; view_has_line(view, line); line++)
6715 if (line->type == stage_line_type)
6716 break;
6718 if (!status_update_files(view, line + 1)) {
6719 report("Failed to update files");
6720 return FALSE;
6723 } else if (!status_update_file(&stage_status, stage_line_type)) {
6724 report("Failed to update file");
6725 return FALSE;
6728 return TRUE;
6731 static bool
6732 stage_revert(struct view *view, struct line *line)
6734 struct line *chunk = NULL;
6736 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6737 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6739 if (chunk) {
6740 if (!prompt_yesno("Are you sure you want to revert changes?"))
6741 return FALSE;
6743 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6744 report("Failed to revert chunk");
6745 return FALSE;
6747 return TRUE;
6749 } else {
6750 return status_revert(stage_status.status ? &stage_status : NULL,
6751 stage_line_type, FALSE);
6756 static void
6757 stage_next(struct view *view, struct line *line)
6759 struct stage_state *state = view->private;
6760 int i;
6762 if (!state->chunks) {
6763 for (line = view->line; view_has_line(view, line); line++) {
6764 if (line->type != LINE_DIFF_CHUNK)
6765 continue;
6767 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6768 report("Allocation failure");
6769 return;
6772 state->chunk[state->chunks++] = line - view->line;
6776 for (i = 0; i < state->chunks; i++) {
6777 if (state->chunk[i] > view->pos.lineno) {
6778 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6779 report("Chunk %d of %zd", i + 1, state->chunks);
6780 return;
6784 report("No next chunk found");
6787 static enum request
6788 stage_request(struct view *view, enum request request, struct line *line)
6790 switch (request) {
6791 case REQ_STATUS_UPDATE:
6792 if (!stage_update(view, line, FALSE))
6793 return REQ_NONE;
6794 break;
6796 case REQ_STATUS_REVERT:
6797 if (!stage_revert(view, line))
6798 return REQ_NONE;
6799 break;
6801 case REQ_STAGE_UPDATE_LINE:
6802 if (stage_line_type == LINE_STAT_UNTRACKED ||
6803 stage_status.status == 'A') {
6804 report("Staging single lines is not supported for new files");
6805 return REQ_NONE;
6807 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6808 report("Please select a change to stage");
6809 return REQ_NONE;
6811 if (!stage_update(view, line, TRUE))
6812 return REQ_NONE;
6813 break;
6815 case REQ_STAGE_NEXT:
6816 if (stage_line_type == LINE_STAT_UNTRACKED) {
6817 report("File is untracked; press %s to add",
6818 get_view_key(view, REQ_STATUS_UPDATE));
6819 return REQ_NONE;
6821 stage_next(view, line);
6822 return REQ_NONE;
6824 case REQ_EDIT:
6825 if (!stage_status.new.name[0])
6826 return request;
6827 if (stage_status.status == 'D') {
6828 report("File has been deleted.");
6829 return REQ_NONE;
6832 open_editor(stage_status.new.name);
6833 break;
6835 case REQ_REFRESH:
6836 /* Reload everything ... */
6837 break;
6839 case REQ_VIEW_BLAME:
6840 if (stage_status.new.name[0]) {
6841 string_copy(opt_file, stage_status.new.name);
6842 opt_ref[0] = 0;
6844 return request;
6846 case REQ_ENTER:
6847 return diff_common_enter(view, request, line);
6849 case REQ_DIFF_CONTEXT_UP:
6850 case REQ_DIFF_CONTEXT_DOWN:
6851 if (!update_diff_context(request))
6852 return REQ_NONE;
6853 break;
6855 default:
6856 return request;
6859 refresh_view(view->parent);
6861 /* Check whether the staged entry still exists, and close the
6862 * stage view if it doesn't. */
6863 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6864 status_restore(view->parent);
6865 return REQ_VIEW_CLOSE;
6868 refresh_view(view);
6870 return REQ_NONE;
6873 static bool
6874 stage_open(struct view *view, enum open_flags flags)
6876 static const char *no_head_diff_argv[] = {
6877 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6878 stage_status.new.name)
6880 static const char *index_show_argv[] = {
6881 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6882 stage_status.old.name, stage_status.new.name)
6884 static const char *files_show_argv[] = {
6885 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
6886 stage_status.old.name, stage_status.new.name)
6888 /* Diffs for unmerged entries are empty when passing the new
6889 * path, so leave out the new path. */
6890 static const char *files_unmerged_argv[] = {
6891 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
6892 opt_diff_context_arg, opt_ignore_space_arg, "--",
6893 stage_status.old.name, NULL
6895 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6896 const char **argv = NULL;
6897 const char *info;
6899 if (!stage_line_type) {
6900 report("No stage content, press %s to open the status view and choose file",
6901 get_view_key(view, REQ_VIEW_STATUS));
6902 return FALSE;
6905 view->encoding = NULL;
6907 switch (stage_line_type) {
6908 case LINE_STAT_STAGED:
6909 if (is_initial_commit()) {
6910 argv = no_head_diff_argv;
6911 } else {
6912 argv = index_show_argv;
6914 if (stage_status.status)
6915 info = "Staged changes to %s";
6916 else
6917 info = "Staged changes";
6918 break;
6920 case LINE_STAT_UNSTAGED:
6921 if (stage_status.status != 'U')
6922 argv = files_show_argv;
6923 else
6924 argv = files_unmerged_argv;
6925 if (stage_status.status)
6926 info = "Unstaged changes to %s";
6927 else
6928 info = "Unstaged changes";
6929 break;
6931 case LINE_STAT_UNTRACKED:
6932 info = "Untracked file %s";
6933 argv = file_argv;
6934 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6935 break;
6937 case LINE_STAT_HEAD:
6938 default:
6939 die("line type %d not handled in switch", stage_line_type);
6942 if (!string_format(view->ref, info, stage_status.new.name)
6943 || !argv_copy(&view->argv, argv)) {
6944 report("Failed to open staged view");
6945 return FALSE;
6948 view->vid[0] = 0;
6949 view->dir = opt_cdup;
6950 return begin_update(view, NULL, NULL, flags);
6953 static bool
6954 stage_read(struct view *view, char *data)
6956 struct stage_state *state = view->private;
6958 if (data && diff_common_read(view, data, &state->diff))
6959 return TRUE;
6961 return pager_read(view, data);
6964 static struct view_ops stage_ops = {
6965 "line",
6966 { "stage" },
6967 VIEW_DIFF_LIKE,
6968 sizeof(struct stage_state),
6969 stage_open,
6970 stage_read,
6971 diff_common_draw,
6972 stage_request,
6973 pager_grep,
6974 pager_select,
6979 * Revision graph
6982 static const enum line_type graph_colors[] = {
6983 LINE_PALETTE_0,
6984 LINE_PALETTE_1,
6985 LINE_PALETTE_2,
6986 LINE_PALETTE_3,
6987 LINE_PALETTE_4,
6988 LINE_PALETTE_5,
6989 LINE_PALETTE_6,
6992 static enum line_type get_graph_color(struct graph_symbol *symbol)
6994 if (symbol->commit)
6995 return LINE_GRAPH_COMMIT;
6996 assert(symbol->color < ARRAY_SIZE(graph_colors));
6997 return graph_colors[symbol->color];
7000 static bool
7001 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7003 const char *chars = graph_symbol_to_utf8(symbol);
7005 return draw_text(view, color, chars + !!first);
7008 static bool
7009 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7011 const char *chars = graph_symbol_to_ascii(symbol);
7013 return draw_text(view, color, chars + !!first);
7016 static bool
7017 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7019 const chtype *chars = graph_symbol_to_chtype(symbol);
7021 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7024 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7026 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7028 static const draw_graph_fn fns[] = {
7029 draw_graph_ascii,
7030 draw_graph_chtype,
7031 draw_graph_utf8
7033 draw_graph_fn fn = fns[opt_line_graphics];
7034 int i;
7036 for (i = 0; i < canvas->size; i++) {
7037 struct graph_symbol *symbol = &canvas->symbols[i];
7038 enum line_type color = get_graph_color(symbol);
7040 if (fn(view, symbol, color, i == 0))
7041 return TRUE;
7044 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7048 * Main view backend
7051 struct commit {
7052 char id[SIZEOF_REV]; /* SHA1 ID. */
7053 char title[128]; /* First line of the commit message. */
7054 const char *author; /* Author of the commit. */
7055 struct time time; /* Date from the author ident. */
7056 struct ref_list *refs; /* Repository references. */
7057 struct graph_canvas graph; /* Ancestry chain graphics. */
7060 struct main_state {
7061 struct graph graph;
7062 struct commit *current;
7063 bool in_header;
7064 bool added_changes_commits;
7067 static struct commit *
7068 main_add_commit(struct view *view, enum line_type type, const char *ids,
7069 bool is_boundary, bool custom)
7071 struct main_state *state = view->private;
7072 struct commit *commit;
7074 if (!add_line_alloc(view, &commit, type, 0, custom))
7075 return NULL;
7077 string_copy_rev(commit->id, ids);
7078 commit->refs = get_ref_list(commit->id);
7079 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7080 return commit;
7083 bool
7084 main_has_changes(const char *argv[])
7086 struct io io;
7088 if (!io_run(&io, IO_BG, NULL, argv, -1))
7089 return FALSE;
7090 io_done(&io);
7091 return io.status == 1;
7094 static void
7095 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7097 char ids[SIZEOF_STR] = NULL_ID " ";
7098 struct main_state *state = view->private;
7099 struct commit *commit;
7100 struct timeval now;
7101 struct timezone tz;
7103 if (!parent)
7104 return;
7106 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7108 commit = main_add_commit(view, type, ids, FALSE, TRUE);
7109 if (!commit)
7110 return;
7112 if (!gettimeofday(&now, &tz)) {
7113 commit->time.tz = tz.tz_minuteswest * 60;
7114 commit->time.sec = now.tv_sec - commit->time.tz;
7117 commit->author = "";
7118 string_ncopy(commit->title, title, strlen(title));
7119 graph_render_parents(&state->graph);
7122 static void
7123 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7125 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7126 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7127 const char *staged_parent = NULL_ID;
7128 const char *unstaged_parent = parent;
7130 if (!is_head_commit(parent))
7131 return;
7133 state->added_changes_commits = TRUE;
7135 io_run_bg(update_index_argv);
7137 if (!main_has_changes(unstaged_argv)) {
7138 unstaged_parent = NULL;
7139 staged_parent = parent;
7142 if (!main_has_changes(staged_argv)) {
7143 staged_parent = NULL;
7146 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7147 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7150 static bool
7151 main_open(struct view *view, enum open_flags flags)
7153 static const char *main_argv[] = {
7154 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7157 return begin_update(view, NULL, main_argv, flags);
7160 static bool
7161 main_draw(struct view *view, struct line *line, unsigned int lineno)
7163 struct commit *commit = line->data;
7165 if (!commit->author)
7166 return FALSE;
7168 if (draw_lineno(view, lineno))
7169 return TRUE;
7171 if (opt_show_id && draw_id(view, LINE_ID, commit->id))
7172 return TRUE;
7174 if (draw_date(view, &commit->time))
7175 return TRUE;
7177 if (draw_author(view, commit->author))
7178 return TRUE;
7180 if (opt_rev_graph && draw_graph(view, &commit->graph))
7181 return TRUE;
7183 if (draw_refs(view, commit->refs))
7184 return TRUE;
7186 draw_text(view, LINE_DEFAULT, commit->title);
7187 return TRUE;
7190 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7191 static bool
7192 main_read(struct view *view, char *line)
7194 struct main_state *state = view->private;
7195 struct graph *graph = &state->graph;
7196 enum line_type type;
7197 struct commit *commit = state->current;
7199 if (!line) {
7200 if (!view->lines && !view->prev)
7201 die("No revisions match the given arguments.");
7202 if (view->lines > 0) {
7203 commit = view->line[view->lines - 1].data;
7204 view->line[view->lines - 1].dirty = 1;
7205 if (!commit->author) {
7206 view->lines--;
7207 free(commit);
7211 done_graph(graph);
7212 return TRUE;
7215 type = get_line_type(line);
7216 if (type == LINE_COMMIT) {
7217 bool is_boundary;
7219 state->in_header = TRUE;
7220 line += STRING_SIZE("commit ");
7221 is_boundary = *line == '-';
7222 if (is_boundary || !isalnum(*line))
7223 line++;
7225 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7226 main_add_changes_commits(view, state, line);
7228 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7229 return state->current != NULL;
7232 if (!view->lines || !commit)
7233 return TRUE;
7235 /* Empty line separates the commit header from the log itself. */
7236 if (*line == '\0')
7237 state->in_header = FALSE;
7239 switch (type) {
7240 case LINE_PARENT:
7241 if (!graph->has_parents)
7242 graph_add_parent(graph, line + STRING_SIZE("parent "));
7243 break;
7245 case LINE_AUTHOR:
7246 parse_author_line(line + STRING_SIZE("author "),
7247 &commit->author, &commit->time);
7248 graph_render_parents(graph);
7249 break;
7251 default:
7252 /* Fill in the commit title if it has not already been set. */
7253 if (commit->title[0])
7254 break;
7256 /* Skip lines in the commit header. */
7257 if (state->in_header)
7258 break;
7260 /* Require titles to start with a non-space character at the
7261 * offset used by git log. */
7262 if (strncmp(line, " ", 4))
7263 break;
7264 line += 4;
7265 /* Well, if the title starts with a whitespace character,
7266 * try to be forgiving. Otherwise we end up with no title. */
7267 while (isspace(*line))
7268 line++;
7269 if (*line == '\0')
7270 break;
7271 /* FIXME: More graceful handling of titles; append "..." to
7272 * shortened titles, etc. */
7274 string_expand(commit->title, sizeof(commit->title), line, 1);
7275 view->line[view->lines - 1].dirty = 1;
7278 return TRUE;
7281 static enum request
7282 main_request(struct view *view, enum request request, struct line *line)
7284 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
7286 switch (request) {
7287 case REQ_NEXT:
7288 case REQ_PREVIOUS:
7289 if (view_is_displayed(view) && display[0] != view)
7290 return request;
7291 /* Do not pass navigation requests to the branch view
7292 * when the main view is maximized. (GH #38) */
7293 move_view(view, request);
7294 break;
7296 case REQ_ENTER:
7297 if (view_is_displayed(view) && display[0] != view)
7298 maximize_view(view, TRUE);
7300 if (line->type == LINE_STAT_UNSTAGED
7301 || line->type == LINE_STAT_STAGED) {
7302 struct view *diff = VIEW(REQ_VIEW_DIFF);
7303 const char *diff_staged_argv[] = {
7304 GIT_DIFF_STAGED(opt_encoding_arg,
7305 opt_diff_context_arg,
7306 opt_ignore_space_arg, NULL, NULL)
7308 const char *diff_unstaged_argv[] = {
7309 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7310 opt_diff_context_arg,
7311 opt_ignore_space_arg, NULL, NULL)
7313 const char **diff_argv = line->type == LINE_STAT_STAGED
7314 ? diff_staged_argv : diff_unstaged_argv;
7316 open_argv(view, diff, diff_argv, NULL, flags);
7317 break;
7320 open_view(view, REQ_VIEW_DIFF, flags);
7321 break;
7322 case REQ_REFRESH:
7323 load_refs();
7324 refresh_view(view);
7325 break;
7327 case REQ_JUMP_COMMIT:
7329 int lineno;
7331 for (lineno = 0; lineno < view->lines; lineno++) {
7332 struct commit *commit = view->line[lineno].data;
7334 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7335 select_view_line(view, lineno);
7336 report_clear();
7337 return REQ_NONE;
7341 report("Unable to find commit '%s'", opt_search);
7342 break;
7344 default:
7345 return request;
7348 return REQ_NONE;
7351 static bool
7352 grep_refs(struct ref_list *list, regex_t *regex)
7354 regmatch_t pmatch;
7355 size_t i;
7357 if (!opt_show_refs || !list)
7358 return FALSE;
7360 for (i = 0; i < list->size; i++) {
7361 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7362 return TRUE;
7365 return FALSE;
7368 static bool
7369 main_grep(struct view *view, struct line *line)
7371 struct commit *commit = line->data;
7372 const char *text[] = {
7373 commit->id,
7374 commit->title,
7375 mkauthor(commit->author, opt_author_width, opt_author),
7376 mkdate(&commit->time, opt_date),
7377 NULL
7380 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7383 static void
7384 main_select(struct view *view, struct line *line)
7386 struct commit *commit = line->data;
7388 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7389 string_copy(view->ref, commit->title);
7390 else
7391 string_copy_rev(view->ref, commit->id);
7392 string_copy_rev(ref_commit, commit->id);
7395 static struct view_ops main_ops = {
7396 "commit",
7397 { "main" },
7398 VIEW_STDIN,
7399 sizeof(struct main_state),
7400 main_open,
7401 main_read,
7402 main_draw,
7403 main_request,
7404 main_grep,
7405 main_select,
7410 * Status management
7413 /* Whether or not the curses interface has been initialized. */
7414 static bool cursed = FALSE;
7416 /* Terminal hacks and workarounds. */
7417 static bool use_scroll_redrawwin;
7418 static bool use_scroll_status_wclear;
7420 /* The status window is used for polling keystrokes. */
7421 static WINDOW *status_win;
7423 /* Reading from the prompt? */
7424 static bool input_mode = FALSE;
7426 static bool status_empty = FALSE;
7428 /* Update status and title window. */
7429 static void
7430 report(const char *msg, ...)
7432 struct view *view = display[current_view];
7434 if (input_mode)
7435 return;
7437 if (!view) {
7438 char buf[SIZEOF_STR];
7439 int retval;
7441 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7442 die("%s", buf);
7445 if (!status_empty || *msg) {
7446 va_list args;
7448 va_start(args, msg);
7450 wmove(status_win, 0, 0);
7451 if (view->has_scrolled && use_scroll_status_wclear)
7452 wclear(status_win);
7453 if (*msg) {
7454 vwprintw(status_win, msg, args);
7455 status_empty = FALSE;
7456 } else {
7457 status_empty = TRUE;
7459 wclrtoeol(status_win);
7460 wnoutrefresh(status_win);
7462 va_end(args);
7465 update_view_title(view);
7468 static void
7469 init_display(void)
7471 const char *term;
7472 int x, y;
7474 /* Initialize the curses library */
7475 if (isatty(STDIN_FILENO)) {
7476 cursed = !!initscr();
7477 opt_tty = stdin;
7478 } else {
7479 /* Leave stdin and stdout alone when acting as a pager. */
7480 opt_tty = fopen("/dev/tty", "r+");
7481 if (!opt_tty)
7482 die("Failed to open /dev/tty");
7483 cursed = !!newterm(NULL, opt_tty, opt_tty);
7486 if (!cursed)
7487 die("Failed to initialize curses");
7489 nonl(); /* Disable conversion and detect newlines from input. */
7490 cbreak(); /* Take input chars one at a time, no wait for \n */
7491 noecho(); /* Don't echo input */
7492 leaveok(stdscr, FALSE);
7494 if (has_colors())
7495 init_colors();
7497 getmaxyx(stdscr, y, x);
7498 status_win = newwin(1, x, y - 1, 0);
7499 if (!status_win)
7500 die("Failed to create status window");
7502 /* Enable keyboard mapping */
7503 keypad(status_win, TRUE);
7504 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7506 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7507 set_tabsize(opt_tab_size);
7508 #else
7509 TABSIZE = opt_tab_size;
7510 #endif
7512 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7513 if (term && !strcmp(term, "gnome-terminal")) {
7514 /* In the gnome-terminal-emulator, the message from
7515 * scrolling up one line when impossible followed by
7516 * scrolling down one line causes corruption of the
7517 * status line. This is fixed by calling wclear. */
7518 use_scroll_status_wclear = TRUE;
7519 use_scroll_redrawwin = FALSE;
7521 } else if (term && !strcmp(term, "xrvt-xpm")) {
7522 /* No problems with full optimizations in xrvt-(unicode)
7523 * and aterm. */
7524 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7526 } else {
7527 /* When scrolling in (u)xterm the last line in the
7528 * scrolling direction will update slowly. */
7529 use_scroll_redrawwin = TRUE;
7530 use_scroll_status_wclear = FALSE;
7534 static int
7535 get_input(int prompt_position)
7537 struct view *view;
7538 int i, key, cursor_y, cursor_x;
7540 if (prompt_position)
7541 input_mode = TRUE;
7543 while (TRUE) {
7544 bool loading = FALSE;
7546 foreach_view (view, i) {
7547 update_view(view);
7548 if (view_is_displayed(view) && view->has_scrolled &&
7549 use_scroll_redrawwin)
7550 redrawwin(view->win);
7551 view->has_scrolled = FALSE;
7552 if (view->pipe)
7553 loading = TRUE;
7556 /* Update the cursor position. */
7557 if (prompt_position) {
7558 getbegyx(status_win, cursor_y, cursor_x);
7559 cursor_x = prompt_position;
7560 } else {
7561 view = display[current_view];
7562 getbegyx(view->win, cursor_y, cursor_x);
7563 cursor_x = view->width - 1;
7564 cursor_y += view->pos.lineno - view->pos.offset;
7566 setsyx(cursor_y, cursor_x);
7568 /* Refresh, accept single keystroke of input */
7569 doupdate();
7570 nodelay(status_win, loading);
7571 key = wgetch(status_win);
7573 /* wgetch() with nodelay() enabled returns ERR when
7574 * there's no input. */
7575 if (key == ERR) {
7577 } else if (key == KEY_RESIZE) {
7578 int height, width;
7580 getmaxyx(stdscr, height, width);
7582 wresize(status_win, 1, width);
7583 mvwin(status_win, height - 1, 0);
7584 wnoutrefresh(status_win);
7585 resize_display();
7586 redraw_display(TRUE);
7588 } else {
7589 input_mode = FALSE;
7590 if (key == erasechar())
7591 key = KEY_BACKSPACE;
7592 return key;
7597 static char *
7598 prompt_input(const char *prompt, input_handler handler, void *data)
7600 enum input_status status = INPUT_OK;
7601 static char buf[SIZEOF_STR];
7602 size_t pos = 0;
7604 buf[pos] = 0;
7606 while (status == INPUT_OK || status == INPUT_SKIP) {
7607 int key;
7609 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7610 wclrtoeol(status_win);
7612 key = get_input(pos + 1);
7613 switch (key) {
7614 case KEY_RETURN:
7615 case KEY_ENTER:
7616 case '\n':
7617 status = pos ? INPUT_STOP : INPUT_CANCEL;
7618 break;
7620 case KEY_BACKSPACE:
7621 if (pos > 0)
7622 buf[--pos] = 0;
7623 else
7624 status = INPUT_CANCEL;
7625 break;
7627 case KEY_ESC:
7628 status = INPUT_CANCEL;
7629 break;
7631 default:
7632 if (pos >= sizeof(buf)) {
7633 report("Input string too long");
7634 return NULL;
7637 status = handler(data, buf, key);
7638 if (status == INPUT_OK)
7639 buf[pos++] = (char) key;
7643 /* Clear the status window */
7644 status_empty = FALSE;
7645 report_clear();
7647 if (status == INPUT_CANCEL)
7648 return NULL;
7650 buf[pos++] = 0;
7652 return buf;
7655 static enum input_status
7656 prompt_yesno_handler(void *data, char *buf, int c)
7658 if (c == 'y' || c == 'Y')
7659 return INPUT_STOP;
7660 if (c == 'n' || c == 'N')
7661 return INPUT_CANCEL;
7662 return INPUT_SKIP;
7665 static bool
7666 prompt_yesno(const char *prompt)
7668 char prompt2[SIZEOF_STR];
7670 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7671 return FALSE;
7673 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7676 static enum input_status
7677 read_prompt_handler(void *data, char *buf, int c)
7679 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7682 static char *
7683 read_prompt(const char *prompt)
7685 return prompt_input(prompt, read_prompt_handler, NULL);
7688 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7690 enum input_status status = INPUT_OK;
7691 int size = 0;
7693 while (items[size].text)
7694 size++;
7696 assert(size > 0);
7698 while (status == INPUT_OK) {
7699 const struct menu_item *item = &items[*selected];
7700 int key;
7701 int i;
7703 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7704 prompt, *selected + 1, size);
7705 if (item->hotkey)
7706 wprintw(status_win, "[%c] ", (char) item->hotkey);
7707 wprintw(status_win, "%s", item->text);
7708 wclrtoeol(status_win);
7710 key = get_input(COLS - 1);
7711 switch (key) {
7712 case KEY_RETURN:
7713 case KEY_ENTER:
7714 case '\n':
7715 status = INPUT_STOP;
7716 break;
7718 case KEY_LEFT:
7719 case KEY_UP:
7720 *selected = *selected - 1;
7721 if (*selected < 0)
7722 *selected = size - 1;
7723 break;
7725 case KEY_RIGHT:
7726 case KEY_DOWN:
7727 *selected = (*selected + 1) % size;
7728 break;
7730 case KEY_ESC:
7731 status = INPUT_CANCEL;
7732 break;
7734 default:
7735 for (i = 0; items[i].text; i++)
7736 if (items[i].hotkey == key) {
7737 *selected = i;
7738 status = INPUT_STOP;
7739 break;
7744 /* Clear the status window */
7745 status_empty = FALSE;
7746 report_clear();
7748 return status != INPUT_CANCEL;
7752 * Repository properties
7756 static void
7757 set_remote_branch(const char *name, const char *value, size_t valuelen)
7759 if (!strcmp(name, ".remote")) {
7760 string_ncopy(opt_remote, value, valuelen);
7762 } else if (*opt_remote && !strcmp(name, ".merge")) {
7763 size_t from = strlen(opt_remote);
7765 if (!prefixcmp(value, "refs/heads/"))
7766 value += STRING_SIZE("refs/heads/");
7768 if (!string_format_from(opt_remote, &from, "/%s", value))
7769 opt_remote[0] = 0;
7773 static void
7774 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7776 const char *argv[SIZEOF_ARG] = { name, "=" };
7777 int argc = 1 + (cmd == option_set_command);
7778 enum option_code error;
7780 if (!argv_from_string(argv, &argc, value))
7781 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7782 else
7783 error = cmd(argc, argv);
7785 if (error != OPT_OK)
7786 warn("Option 'tig.%s': %s", name, option_errors[error]);
7789 static bool
7790 set_environment_variable(const char *name, const char *value)
7792 size_t len = strlen(name) + 1 + strlen(value) + 1;
7793 char *env = malloc(len);
7795 if (env &&
7796 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7797 putenv(env) == 0)
7798 return TRUE;
7799 free(env);
7800 return FALSE;
7803 static void
7804 set_work_tree(const char *value)
7806 char cwd[SIZEOF_STR];
7808 if (!getcwd(cwd, sizeof(cwd)))
7809 die("Failed to get cwd path: %s", strerror(errno));
7810 if (chdir(cwd) < 0)
7811 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7812 if (chdir(opt_git_dir) < 0)
7813 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
7814 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7815 die("Failed to get git path: %s", strerror(errno));
7816 if (chdir(value) < 0)
7817 die("Failed to chdir(%s): %s", value, strerror(errno));
7818 if (!getcwd(cwd, sizeof(cwd)))
7819 die("Failed to get cwd path: %s", strerror(errno));
7820 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7821 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7822 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7823 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7824 opt_is_inside_work_tree = TRUE;
7827 static void
7828 parse_git_color_option(enum line_type type, char *value)
7830 struct line_info *info = &line_info[type];
7831 const char *argv[SIZEOF_ARG];
7832 int argc = 0;
7833 bool first_color = TRUE;
7834 int i;
7836 if (!argv_from_string(argv, &argc, value))
7837 return;
7839 info->fg = COLOR_DEFAULT;
7840 info->bg = COLOR_DEFAULT;
7841 info->attr = 0;
7843 for (i = 0; i < argc; i++) {
7844 int attr = 0;
7846 if (set_attribute(&attr, argv[i])) {
7847 info->attr |= attr;
7849 } else if (set_color(&attr, argv[i])) {
7850 if (first_color)
7851 info->fg = attr;
7852 else
7853 info->bg = attr;
7854 first_color = FALSE;
7859 static void
7860 set_git_color_option(const char *name, char *value)
7862 static const struct enum_map color_option_map[] = {
7863 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7864 ENUM_MAP("branch.local", LINE_MAIN_REF),
7865 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7866 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7868 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7869 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7870 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7871 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7872 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7873 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7874 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7876 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7878 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7879 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7880 ENUM_MAP("status.added", LINE_STAT_STAGED),
7881 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7882 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7883 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7886 int type = LINE_NONE;
7888 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7889 parse_git_color_option(type, value);
7893 static void
7894 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
7896 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
7897 opt_encoding_arg[0] = 0;
7900 static int
7901 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7903 if (!strcmp(name, "i18n.commitencoding"))
7904 set_encoding(&opt_encoding, value, FALSE);
7906 else if (!strcmp(name, "gui.encoding"))
7907 set_encoding(&opt_encoding, value, TRUE);
7909 else if (!strcmp(name, "core.editor"))
7910 string_ncopy(opt_editor, value, valuelen);
7912 else if (!strcmp(name, "core.worktree"))
7913 set_work_tree(value);
7915 else if (!strcmp(name, "core.abbrev"))
7916 parse_id(&opt_id_cols, value);
7918 else if (!prefixcmp(name, "tig.color."))
7919 set_repo_config_option(name + 10, value, option_color_command);
7921 else if (!prefixcmp(name, "tig.bind."))
7922 set_repo_config_option(name + 9, value, option_bind_command);
7924 else if (!prefixcmp(name, "tig."))
7925 set_repo_config_option(name + 4, value, option_set_command);
7927 else if (!prefixcmp(name, "color."))
7928 set_git_color_option(name + STRING_SIZE("color."), value);
7930 else if (*opt_head && !prefixcmp(name, "branch.") &&
7931 !strncmp(name + 7, opt_head, strlen(opt_head)))
7932 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7934 return OK;
7937 static int
7938 load_git_config(void)
7940 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7942 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7945 static int
7946 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7948 if (!opt_git_dir[0]) {
7949 string_ncopy(opt_git_dir, name, namelen);
7951 } else if (opt_is_inside_work_tree == -1) {
7952 /* This can be 3 different values depending on the
7953 * version of git being used. If git-rev-parse does not
7954 * understand --is-inside-work-tree it will simply echo
7955 * the option else either "true" or "false" is printed.
7956 * Default to true for the unknown case. */
7957 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7959 } else if (*name == '.') {
7960 string_ncopy(opt_cdup, name, namelen);
7962 } else {
7963 string_ncopy(opt_prefix, name, namelen);
7966 return OK;
7969 static int
7970 load_repo_info(void)
7972 const char *rev_parse_argv[] = {
7973 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7974 "--show-cdup", "--show-prefix", NULL
7977 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7982 * Main
7985 static const char usage[] =
7986 "tig " TIG_VERSION " (" __DATE__ ")\n"
7987 "\n"
7988 "Usage: tig [options] [revs] [--] [paths]\n"
7989 " or: tig show [options] [revs] [--] [paths]\n"
7990 " or: tig blame [options] [rev] [--] path\n"
7991 " or: tig status\n"
7992 " or: tig < [git command output]\n"
7993 "\n"
7994 "Options:\n"
7995 " +<number> Select line <number> in the first view\n"
7996 " -v, --version Show version and exit\n"
7997 " -h, --help Show help message and exit";
7999 static void __NORETURN
8000 quit(int sig)
8002 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8003 if (cursed)
8004 endwin();
8005 exit(0);
8008 static void __NORETURN
8009 die(const char *err, ...)
8011 va_list args;
8013 endwin();
8015 va_start(args, err);
8016 fputs("tig: ", stderr);
8017 vfprintf(stderr, err, args);
8018 fputs("\n", stderr);
8019 va_end(args);
8021 exit(1);
8024 static void
8025 warn(const char *msg, ...)
8027 va_list args;
8029 va_start(args, msg);
8030 fputs("tig warning: ", stderr);
8031 vfprintf(stderr, msg, args);
8032 fputs("\n", stderr);
8033 va_end(args);
8036 static int
8037 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8039 const char ***filter_args = data;
8041 return argv_append(filter_args, name) ? OK : ERR;
8044 static void
8045 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8047 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8048 const char **all_argv = NULL;
8050 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8051 !argv_append_array(&all_argv, argv) ||
8052 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8053 die("Failed to split arguments");
8054 argv_free(all_argv);
8055 free(all_argv);
8058 static bool
8059 is_rev_flag(const char *flag)
8061 static const char *rev_flags[] = { GIT_REV_FLAGS };
8062 int i;
8064 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8065 if (!strcmp(flag, rev_flags[i]))
8066 return TRUE;
8068 return FALSE;
8071 static void
8072 filter_options(const char *argv[], bool blame)
8074 const char **flags = NULL;
8076 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8077 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8079 if (flags) {
8080 int next, flags_pos;
8082 for (next = flags_pos = 0; flags && flags[next]; next++) {
8083 const char *flag = flags[next];
8085 if (is_rev_flag(flag))
8086 argv_append(&opt_rev_argv, flag);
8087 else
8088 flags[flags_pos++] = flag;
8091 flags[flags_pos] = NULL;
8093 if (blame)
8094 opt_blame_argv = flags;
8095 else
8096 opt_diff_argv = flags;
8099 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8102 static enum request
8103 parse_options(int argc, const char *argv[])
8105 enum request request;
8106 const char *subcommand;
8107 bool seen_dashdash = FALSE;
8108 const char **filter_argv = NULL;
8109 int i;
8111 opt_stdin = !isatty(STDIN_FILENO);
8112 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8114 if (argc <= 1)
8115 return request;
8117 subcommand = argv[1];
8118 if (!strcmp(subcommand, "status")) {
8119 request = REQ_VIEW_STATUS;
8121 } else if (!strcmp(subcommand, "blame")) {
8122 request = REQ_VIEW_BLAME;
8124 } else if (!strcmp(subcommand, "show")) {
8125 request = REQ_VIEW_DIFF;
8127 } else {
8128 subcommand = NULL;
8131 for (i = 1 + !!subcommand; i < argc; i++) {
8132 const char *opt = argv[i];
8134 // stop parsing our options after -- and let rev-parse handle the rest
8135 if (!seen_dashdash) {
8136 if (!strcmp(opt, "--")) {
8137 seen_dashdash = TRUE;
8138 continue;
8140 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8141 printf("tig version %s\n", TIG_VERSION);
8142 quit(0);
8144 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8145 printf("%s\n", usage);
8146 quit(0);
8148 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8149 opt_lineno = atoi(opt + 1);
8150 continue;
8155 if (!argv_append(&filter_argv, opt))
8156 die("command too long");
8159 if (filter_argv)
8160 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8162 /* Finish validating and setting up blame options */
8163 if (request == REQ_VIEW_BLAME) {
8164 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8165 die("invalid number of options to blame\n\n%s", usage);
8167 if (opt_rev_argv) {
8168 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8171 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8173 } else if (request == REQ_VIEW_PAGER) {
8174 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8175 if (!strcmp("--stdin", opt_rev_argv[i])) {
8176 request = REQ_VIEW_MAIN;
8177 break;
8182 return request;
8186 main(int argc, const char *argv[])
8188 const char *codeset = ENCODING_UTF8;
8189 enum request request = parse_options(argc, argv);
8190 struct view *view;
8191 int i;
8193 signal(SIGINT, quit);
8194 signal(SIGPIPE, SIG_IGN);
8196 if (setlocale(LC_ALL, "")) {
8197 codeset = nl_langinfo(CODESET);
8200 foreach_view(view, i) {
8201 add_keymap(&view->ops->keymap);
8204 if (load_repo_info() == ERR)
8205 die("Failed to load repo info.");
8207 if (load_options() == ERR)
8208 die("Failed to load user config.");
8210 if (load_git_config() == ERR)
8211 die("Failed to load repo config.");
8213 /* Require a git repository unless when running in pager mode. */
8214 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8215 die("Not a git repository");
8217 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8218 char translit[SIZEOF_STR];
8220 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8221 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8222 else
8223 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8224 if (opt_iconv_out == ICONV_NONE)
8225 die("Failed to initialize character set conversion");
8228 if (load_refs() == ERR)
8229 die("Failed to load refs.");
8231 init_display();
8233 while (view_driver(display[current_view], request)) {
8234 int key = get_input(0);
8236 view = display[current_view];
8237 request = get_keybinding(&view->ops->keymap, key);
8239 /* Some low-level request handling. This keeps access to
8240 * status_win restricted. */
8241 switch (request) {
8242 case REQ_NONE:
8243 report("Unknown key, press %s for help",
8244 get_view_key(view, REQ_VIEW_HELP));
8245 break;
8246 case REQ_PROMPT:
8248 char *cmd = read_prompt(":");
8250 if (cmd && string_isnumber(cmd)) {
8251 int lineno = view->pos.lineno + 1;
8253 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8254 select_view_line(view, lineno - 1);
8255 report_clear();
8256 } else {
8257 report("Unable to parse '%s' as a line number", cmd);
8259 } else if (cmd && iscommit(cmd)) {
8260 string_ncopy(opt_search, cmd, strlen(cmd));
8262 request = view_request(view, REQ_JUMP_COMMIT);
8263 if (request == REQ_JUMP_COMMIT) {
8264 report("Jumping to commits is not supported by the '%s' view", view->name);
8267 } else if (cmd && strlen(cmd) == 1) {
8268 request = get_keybinding(&view->ops->keymap, cmd[0]);
8269 break;
8271 } else if (cmd && cmd[0] == '!') {
8272 struct view *next = VIEW(REQ_VIEW_PAGER);
8273 const char *argv[SIZEOF_ARG];
8274 int argc = 0;
8276 cmd++;
8277 /* When running random commands, initially show the
8278 * command in the title. However, it maybe later be
8279 * overwritten if a commit line is selected. */
8280 string_ncopy(next->ref, cmd, strlen(cmd));
8282 if (!argv_from_string(argv, &argc, cmd)) {
8283 report("Too many arguments");
8284 } else if (!format_argv(&next->argv, argv, FALSE)) {
8285 report("Argument formatting failed");
8286 } else {
8287 next->dir = NULL;
8288 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8291 } else if (cmd) {
8292 request = get_request(cmd);
8293 if (request != REQ_UNKNOWN)
8294 break;
8296 char *args = strchr(cmd, ' ');
8297 if (args) {
8298 *args++ = 0;
8299 if (set_option(cmd, args) == OPT_OK) {
8300 request = REQ_SCREEN_REDRAW;
8301 if (!strcmp(cmd, "color"))
8302 init_colors();
8305 break;
8308 request = REQ_NONE;
8309 break;
8311 case REQ_SEARCH:
8312 case REQ_SEARCH_BACK:
8314 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8315 char *search = read_prompt(prompt);
8317 if (search)
8318 string_ncopy(opt_search, search, strlen(search));
8319 else if (*opt_search)
8320 request = request == REQ_SEARCH ?
8321 REQ_FIND_NEXT :
8322 REQ_FIND_PREV;
8323 else
8324 request = REQ_NONE;
8325 break;
8327 default:
8328 break;
8332 quit(0);
8334 return 0;