Limit the number of allocated color pairs
[tig.git] / tig.c
blobb1bacf3a3b73c6de7197ae40eae7ee9e734bcb57
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 "graph.h"
17 #include "git.h"
19 static void __NORETURN die(const char *err, ...);
20 static void warn(const char *msg, ...);
21 static void report(const char *msg, ...);
24 struct ref {
25 char id[SIZEOF_REV]; /* Commit SHA1 ID */
26 unsigned int head:1; /* Is it the current HEAD? */
27 unsigned int tag:1; /* Is it a tag? */
28 unsigned int ltag:1; /* If so, is the tag local? */
29 unsigned int remote:1; /* Is it a remote ref? */
30 unsigned int replace:1; /* Is it a replace ref? */
31 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
32 char name[1]; /* Ref name; tag or head names are shortened. */
35 struct ref_list {
36 char id[SIZEOF_REV]; /* Commit SHA1 ID */
37 size_t size; /* Number of refs. */
38 struct ref **refs; /* References for this ID. */
41 static struct ref *get_ref_head();
42 static struct ref_list *get_ref_list(const char *id);
43 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
44 static int load_refs(void);
46 enum input_status {
47 INPUT_OK,
48 INPUT_SKIP,
49 INPUT_STOP,
50 INPUT_CANCEL
53 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
55 static char *prompt_input(const char *prompt, input_handler handler, void *data);
56 static bool prompt_yesno(const char *prompt);
58 struct menu_item {
59 int hotkey;
60 const char *text;
61 void *data;
64 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
66 #define GRAPHIC_ENUM(_) \
67 _(GRAPHIC, ASCII), \
68 _(GRAPHIC, DEFAULT), \
69 _(GRAPHIC, UTF_8)
71 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
73 #define DATE_ENUM(_) \
74 _(DATE, NO), \
75 _(DATE, DEFAULT), \
76 _(DATE, LOCAL), \
77 _(DATE, RELATIVE), \
78 _(DATE, SHORT)
80 DEFINE_ENUM(date, DATE_ENUM);
82 struct time {
83 time_t sec;
84 int tz;
87 static inline int timecmp(const struct time *t1, const struct time *t2)
89 return t1->sec - t2->sec;
92 static const char *
93 mkdate(const struct time *time, enum date date)
95 static char buf[DATE_COLS + 1];
96 static const struct enum_map reldate[] = {
97 { "second", 1, 60 * 2 },
98 { "minute", 60, 60 * 60 * 2 },
99 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
100 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
101 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
102 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
104 struct tm tm;
106 if (!date || !time || !time->sec)
107 return "";
109 if (date == DATE_RELATIVE) {
110 struct timeval now;
111 time_t date = time->sec + time->tz;
112 time_t seconds;
113 int i;
115 gettimeofday(&now, NULL);
116 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
117 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
118 if (seconds >= reldate[i].value)
119 continue;
121 seconds /= reldate[i].namelen;
122 if (!string_format(buf, "%ld %s%s %s",
123 seconds, reldate[i].name,
124 seconds > 1 ? "s" : "",
125 now.tv_sec >= date ? "ago" : "ahead"))
126 break;
127 return buf;
131 if (date == DATE_LOCAL) {
132 time_t date = time->sec + time->tz;
133 localtime_r(&date, &tm);
135 else {
136 gmtime_r(&time->sec, &tm);
138 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
142 #define AUTHOR_ENUM(_) \
143 _(AUTHOR, NO), \
144 _(AUTHOR, FULL), \
145 _(AUTHOR, ABBREVIATED)
147 DEFINE_ENUM(author, AUTHOR_ENUM);
149 static const char *
150 get_author_initials(const char *author)
152 static char initials[AUTHOR_COLS * 6 + 1];
153 size_t pos = 0;
154 const char *end = strchr(author, '\0');
156 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
158 memset(initials, 0, sizeof(initials));
159 while (author < end) {
160 unsigned char bytes;
161 size_t i;
163 while (author < end && is_initial_sep(*author))
164 author++;
166 bytes = utf8_char_length(author, end);
167 if (bytes >= sizeof(initials) - 1 - pos)
168 break;
169 while (bytes--) {
170 initials[pos++] = *author++;
173 i = pos;
174 while (author < end && !is_initial_sep(*author)) {
175 bytes = utf8_char_length(author, end);
176 if (bytes >= sizeof(initials) - 1 - i) {
177 while (author < end && !is_initial_sep(*author))
178 author++;
179 break;
181 while (bytes--) {
182 initials[i++] = *author++;
186 initials[i++] = 0;
189 return initials;
192 #define author_trim(cols) (cols == 0 || cols > 5)
194 static const char *
195 mkauthor(const char *text, int cols, enum author author)
197 bool trim = author_trim(cols);
198 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
200 if (author == AUTHOR_NO)
201 return "";
202 if (abbreviate && text)
203 return get_author_initials(text);
204 return text;
207 static const char *
208 mkmode(mode_t mode)
210 if (S_ISDIR(mode))
211 return "drwxr-xr-x";
212 else if (S_ISLNK(mode))
213 return "lrwxrwxrwx";
214 else if (S_ISGITLINK(mode))
215 return "m---------";
216 else if (S_ISREG(mode) && mode & S_IXUSR)
217 return "-rwxr-xr-x";
218 else if (S_ISREG(mode))
219 return "-rw-r--r--";
220 else
221 return "----------";
224 #define FILENAME_ENUM(_) \
225 _(FILENAME, NO), \
226 _(FILENAME, ALWAYS), \
227 _(FILENAME, AUTO)
229 DEFINE_ENUM(filename, FILENAME_ENUM);
231 #define IGNORE_SPACE_ENUM(_) \
232 _(IGNORE_SPACE, NO), \
233 _(IGNORE_SPACE, ALL), \
234 _(IGNORE_SPACE, SOME), \
235 _(IGNORE_SPACE, AT_EOL)
237 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
239 #define VIEW_INFO(_) \
240 _(MAIN, main, ref_head), \
241 _(DIFF, diff, ref_commit), \
242 _(LOG, log, ref_head), \
243 _(TREE, tree, ref_commit), \
244 _(BLOB, blob, ref_blob), \
245 _(BLAME, blame, ref_commit), \
246 _(BRANCH, branch, ref_head), \
247 _(HELP, help, ""), \
248 _(PAGER, pager, ""), \
249 _(STATUS, status, "status"), \
250 _(STAGE, stage, "stage")
252 static struct encoding *
253 get_path_encoding(const char *path, struct encoding *default_encoding)
255 const char *check_attr_argv[] = {
256 "git", "check-attr", "encoding", "--", path, NULL
258 char buf[SIZEOF_STR];
259 char *encoding;
261 /* <path>: encoding: <encoding> */
263 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
264 || !(encoding = strstr(buf, ENCODING_SEP)))
265 return default_encoding;
267 encoding += STRING_SIZE(ENCODING_SEP);
268 if (!strcmp(encoding, ENCODING_UTF8)
269 || !strcmp(encoding, "unspecified")
270 || !strcmp(encoding, "set"))
271 return default_encoding;
273 return encoding_open(encoding);
277 * User requests
280 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
282 #define REQ_INFO \
283 REQ_GROUP("View switching") \
284 VIEW_INFO(VIEW_REQ), \
286 REQ_GROUP("View manipulation") \
287 REQ_(ENTER, "Enter current line and scroll"), \
288 REQ_(NEXT, "Move to next"), \
289 REQ_(PREVIOUS, "Move to previous"), \
290 REQ_(PARENT, "Move to parent"), \
291 REQ_(VIEW_NEXT, "Move focus to next view"), \
292 REQ_(REFRESH, "Reload and refresh"), \
293 REQ_(MAXIMIZE, "Maximize the current view"), \
294 REQ_(VIEW_CLOSE, "Close the current view"), \
295 REQ_(QUIT, "Close all views and quit"), \
297 REQ_GROUP("View specific requests") \
298 REQ_(STATUS_UPDATE, "Update file status"), \
299 REQ_(STATUS_REVERT, "Revert file changes"), \
300 REQ_(STATUS_MERGE, "Merge file using external tool"), \
301 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
302 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
303 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
304 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
306 REQ_GROUP("Cursor navigation") \
307 REQ_(MOVE_UP, "Move cursor one line up"), \
308 REQ_(MOVE_DOWN, "Move cursor one line down"), \
309 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
310 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
311 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
312 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
314 REQ_GROUP("Scrolling") \
315 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
316 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
317 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
318 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
319 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
320 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
321 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
323 REQ_GROUP("Searching") \
324 REQ_(SEARCH, "Search the view"), \
325 REQ_(SEARCH_BACK, "Search backwards in the view"), \
326 REQ_(FIND_NEXT, "Find next search match"), \
327 REQ_(FIND_PREV, "Find previous search match"), \
329 REQ_GROUP("Option manipulation") \
330 REQ_(OPTIONS, "Open option menu"), \
331 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
332 REQ_(TOGGLE_DATE, "Toggle date display"), \
333 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
334 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
335 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
336 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
337 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
338 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
339 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
340 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
341 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
343 REQ_GROUP("Misc") \
344 REQ_(PROMPT, "Bring up the prompt"), \
345 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
346 REQ_(SHOW_VERSION, "Show version information"), \
347 REQ_(STOP_LOADING, "Stop all loading views"), \
348 REQ_(EDIT, "Open in editor"), \
349 REQ_(NONE, "Do nothing")
352 /* User action requests. */
353 enum request {
354 #define REQ_GROUP(help)
355 #define REQ_(req, help) REQ_##req
357 /* Offset all requests to avoid conflicts with ncurses getch values. */
358 REQ_UNKNOWN = KEY_MAX + 1,
359 REQ_OFFSET,
360 REQ_INFO,
362 /* Internal requests. */
363 REQ_JUMP_COMMIT,
365 #undef REQ_GROUP
366 #undef REQ_
369 struct request_info {
370 enum request request;
371 const char *name;
372 int namelen;
373 const char *help;
376 static const struct request_info req_info[] = {
377 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
378 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
379 REQ_INFO
380 #undef REQ_GROUP
381 #undef REQ_
384 static enum request
385 get_request(const char *name)
387 int namelen = strlen(name);
388 int i;
390 for (i = 0; i < ARRAY_SIZE(req_info); i++)
391 if (enum_equals(req_info[i], name, namelen))
392 return req_info[i].request;
394 return REQ_UNKNOWN;
399 * Options
402 /* Option and state variables. */
403 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
404 static enum date opt_date = DATE_DEFAULT;
405 static enum author opt_author = AUTHOR_FULL;
406 static enum filename opt_filename = FILENAME_AUTO;
407 static bool opt_rev_graph = TRUE;
408 static bool opt_line_number = FALSE;
409 static bool opt_show_refs = TRUE;
410 static bool opt_show_changes = TRUE;
411 static bool opt_untracked_dirs_content = TRUE;
412 static bool opt_read_git_colors = TRUE;
413 static int opt_diff_context = 3;
414 static char opt_diff_context_arg[9] = "";
415 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
416 static char opt_ignore_space_arg[22] = "";
417 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
418 static int opt_num_interval = 5;
419 static double opt_hscroll = 0.50;
420 static double opt_scale_split_view = 2.0 / 3.0;
421 static int opt_tab_size = 8;
422 static int opt_author_cols = AUTHOR_COLS;
423 static int opt_filename_cols = FILENAME_COLS;
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 iconv_t opt_iconv_out = ICONV_NONE;
432 static char opt_search[SIZEOF_STR] = "";
433 static char opt_cdup[SIZEOF_STR] = "";
434 static char opt_prefix[SIZEOF_STR] = "";
435 static char opt_git_dir[SIZEOF_STR] = "";
436 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
437 static char opt_editor[SIZEOF_STR] = "";
438 static FILE *opt_tty = NULL;
439 static const char **opt_diff_argv = NULL;
440 static const char **opt_rev_argv = NULL;
441 static const char **opt_file_argv = NULL;
442 static const char **opt_blame_argv = NULL;
443 static int opt_lineno = 0;
445 #define is_initial_commit() (!get_ref_head())
446 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
448 static inline void
449 update_diff_context_arg(int diff_context)
451 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
452 string_ncopy(opt_diff_context_arg, "-U3", 3);
455 static inline void
456 update_ignore_space_arg()
458 if (opt_ignore_space == IGNORE_SPACE_ALL) {
459 string_copy(opt_ignore_space_arg, "--ignore-all-space");
460 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
461 string_copy(opt_ignore_space_arg, "--ignore-space-change");
462 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
463 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
464 } else {
465 string_copy(opt_ignore_space_arg, "");
470 * Line-oriented content detection.
473 #define LINE_INFO \
474 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
475 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
476 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
477 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
478 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
479 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
480 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
481 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
482 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
483 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
484 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
485 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
486 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
487 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
488 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
489 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
490 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
491 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
492 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
493 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
494 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
495 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
496 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
497 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
498 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
499 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
500 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
501 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
502 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
503 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
504 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
505 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
506 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
507 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
508 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
509 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
510 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
511 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
512 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
513 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
514 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
515 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
516 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
517 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
518 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
519 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
520 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
521 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
522 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
523 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
524 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
525 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
526 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
527 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
528 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
529 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
530 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
531 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
532 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
533 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
534 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
535 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
536 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
537 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
538 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
539 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
540 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
541 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
542 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
543 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
544 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
545 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
547 enum line_type {
548 #define LINE(type, line, fg, bg, attr) \
549 LINE_##type
550 LINE_INFO,
551 LINE_NONE
552 #undef LINE
555 struct line_info {
556 const char *name; /* Option name. */
557 int namelen; /* Size of option name. */
558 const char *line; /* The start of line to match. */
559 int linelen; /* Size of string to match. */
560 int fg, bg, attr; /* Color and text attributes for the lines. */
561 int color_pair;
564 static struct line_info line_info[] = {
565 #define LINE(type, line, fg, bg, attr) \
566 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
567 LINE_INFO
568 #undef LINE
571 static struct line_info **color_pair;
572 static size_t color_pairs;
574 static struct line_info *custom_color;
575 static size_t custom_colors;
577 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
578 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
580 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
581 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
583 /* Color IDs must be 1 or higher. [GH #15] */
584 #define COLOR_ID(line_type) ((line_type) + 1)
586 static enum line_type
587 get_line_type(const char *line)
589 int linelen = strlen(line);
590 enum line_type type;
592 for (type = 0; type < custom_colors; type++)
593 /* Case insensitive search matches Signed-off-by lines better. */
594 if (linelen >= custom_color[type].linelen &&
595 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
596 return TO_CUSTOM_COLOR_TYPE(type);
598 for (type = 0; type < ARRAY_SIZE(line_info); type++)
599 /* Case insensitive search matches Signed-off-by lines better. */
600 if (linelen >= line_info[type].linelen &&
601 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
602 return type;
604 return LINE_DEFAULT;
607 static enum line_type
608 get_line_type_from_ref(const struct ref *ref)
610 if (ref->head)
611 return LINE_MAIN_HEAD;
612 else if (ref->ltag)
613 return LINE_MAIN_LOCAL_TAG;
614 else if (ref->tag)
615 return LINE_MAIN_TAG;
616 else if (ref->tracked)
617 return LINE_MAIN_TRACKED;
618 else if (ref->remote)
619 return LINE_MAIN_REMOTE;
620 else if (ref->replace)
621 return LINE_MAIN_REPLACE;
623 return LINE_MAIN_REF;
626 static inline struct line_info *
627 get_line(enum line_type type)
629 struct line_info *info;
631 if (type > LINE_NONE) {
632 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
633 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
634 } else {
635 assert(type < ARRAY_SIZE(line_info));
636 return &line_info[type];
640 static inline int
641 get_line_color(enum line_type type)
643 return COLOR_ID(get_line(type)->color_pair);
646 static inline int
647 get_line_attr(enum line_type type)
649 struct line_info *info = get_line(type);
651 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
654 static struct line_info *
655 get_line_info(const char *name)
657 size_t namelen = strlen(name);
658 enum line_type type;
660 for (type = 0; type < ARRAY_SIZE(line_info); type++)
661 if (enum_equals(line_info[type], name, namelen))
662 return &line_info[type];
664 return NULL;
667 static struct line_info *
668 add_custom_color(const char *quoted_line)
670 struct line_info *info;
671 char *line;
672 size_t linelen;
674 if (!realloc_custom_color(&custom_color, custom_colors, 1))
675 die("Failed to alloc custom line info");
677 linelen = strlen(quoted_line) - 1;
678 line = malloc(linelen);
679 if (!line)
680 return NULL;
682 strncpy(line, quoted_line + 1, linelen);
683 line[linelen - 1] = 0;
685 info = &custom_color[custom_colors++];
686 info->name = info->line = line;
687 info->namelen = info->linelen = strlen(line);
689 return info;
692 static void
693 init_line_info_color_pair(struct line_info *info, enum line_type type,
694 int default_bg, int default_fg)
696 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
697 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
698 int i;
700 for (i = 0; i < color_pairs; i++) {
701 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
702 info->color_pair = i;
703 return;
707 if (!realloc_color_pair(&color_pair, color_pairs, 1))
708 die("Failed to alloc color pair");
710 color_pair[color_pairs] = info;
711 info->color_pair = color_pairs++;
712 init_pair(COLOR_ID(info->color_pair), fg, bg);
715 static void
716 init_colors(void)
718 int default_bg = line_info[LINE_DEFAULT].bg;
719 int default_fg = line_info[LINE_DEFAULT].fg;
720 enum line_type type;
722 start_color();
724 if (assume_default_colors(default_fg, default_bg) == ERR) {
725 default_bg = COLOR_BLACK;
726 default_fg = COLOR_WHITE;
729 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
730 struct line_info *info = &line_info[type];
732 init_line_info_color_pair(info, type, default_bg, default_fg);
735 for (type = 0; type < custom_colors; type++) {
736 struct line_info *info = &custom_color[type];
738 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
739 default_bg, default_fg);
743 struct line {
744 enum line_type type;
746 /* State flags */
747 unsigned int selected:1;
748 unsigned int dirty:1;
749 unsigned int cleareol:1;
750 unsigned int other:16;
752 void *data; /* User data */
757 * Keys
760 struct keybinding {
761 int alias;
762 enum request request;
765 static struct keybinding default_keybindings[] = {
766 /* View switching */
767 { 'm', REQ_VIEW_MAIN },
768 { 'd', REQ_VIEW_DIFF },
769 { 'l', REQ_VIEW_LOG },
770 { 't', REQ_VIEW_TREE },
771 { 'f', REQ_VIEW_BLOB },
772 { 'B', REQ_VIEW_BLAME },
773 { 'H', REQ_VIEW_BRANCH },
774 { 'p', REQ_VIEW_PAGER },
775 { 'h', REQ_VIEW_HELP },
776 { 'S', REQ_VIEW_STATUS },
777 { 'c', REQ_VIEW_STAGE },
779 /* View manipulation */
780 { 'q', REQ_VIEW_CLOSE },
781 { KEY_TAB, REQ_VIEW_NEXT },
782 { KEY_RETURN, REQ_ENTER },
783 { KEY_UP, REQ_PREVIOUS },
784 { KEY_CTL('P'), REQ_PREVIOUS },
785 { KEY_DOWN, REQ_NEXT },
786 { KEY_CTL('N'), REQ_NEXT },
787 { 'R', REQ_REFRESH },
788 { KEY_F(5), REQ_REFRESH },
789 { 'O', REQ_MAXIMIZE },
790 { ',', REQ_PARENT },
792 /* View specific */
793 { 'u', REQ_STATUS_UPDATE },
794 { '!', REQ_STATUS_REVERT },
795 { 'M', REQ_STATUS_MERGE },
796 { '1', REQ_STAGE_UPDATE_LINE },
797 { '@', REQ_STAGE_NEXT },
798 { '[', REQ_DIFF_CONTEXT_DOWN },
799 { ']', REQ_DIFF_CONTEXT_UP },
801 /* Cursor navigation */
802 { 'k', REQ_MOVE_UP },
803 { 'j', REQ_MOVE_DOWN },
804 { KEY_HOME, REQ_MOVE_FIRST_LINE },
805 { KEY_END, REQ_MOVE_LAST_LINE },
806 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
807 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
808 { ' ', REQ_MOVE_PAGE_DOWN },
809 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
810 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
811 { 'b', REQ_MOVE_PAGE_UP },
812 { '-', REQ_MOVE_PAGE_UP },
814 /* Scrolling */
815 { '|', REQ_SCROLL_FIRST_COL },
816 { KEY_LEFT, REQ_SCROLL_LEFT },
817 { KEY_RIGHT, REQ_SCROLL_RIGHT },
818 { KEY_IC, REQ_SCROLL_LINE_UP },
819 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
820 { KEY_DC, REQ_SCROLL_LINE_DOWN },
821 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
822 { 'w', REQ_SCROLL_PAGE_UP },
823 { 's', REQ_SCROLL_PAGE_DOWN },
825 /* Searching */
826 { '/', REQ_SEARCH },
827 { '?', REQ_SEARCH_BACK },
828 { 'n', REQ_FIND_NEXT },
829 { 'N', REQ_FIND_PREV },
831 /* Misc */
832 { 'Q', REQ_QUIT },
833 { 'z', REQ_STOP_LOADING },
834 { 'v', REQ_SHOW_VERSION },
835 { 'r', REQ_SCREEN_REDRAW },
836 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
837 { 'o', REQ_OPTIONS },
838 { '.', REQ_TOGGLE_LINENO },
839 { 'D', REQ_TOGGLE_DATE },
840 { 'A', REQ_TOGGLE_AUTHOR },
841 { 'g', REQ_TOGGLE_REV_GRAPH },
842 { '~', REQ_TOGGLE_GRAPHIC },
843 { '#', REQ_TOGGLE_FILENAME },
844 { 'F', REQ_TOGGLE_REFS },
845 { 'I', REQ_TOGGLE_SORT_ORDER },
846 { 'i', REQ_TOGGLE_SORT_FIELD },
847 { 'W', REQ_TOGGLE_IGNORE_SPACE },
848 { ':', REQ_PROMPT },
849 { 'e', REQ_EDIT },
852 #define KEYMAP_ENUM(_) \
853 _(KEYMAP, GENERIC), \
854 _(KEYMAP, MAIN), \
855 _(KEYMAP, DIFF), \
856 _(KEYMAP, LOG), \
857 _(KEYMAP, TREE), \
858 _(KEYMAP, BLOB), \
859 _(KEYMAP, BLAME), \
860 _(KEYMAP, BRANCH), \
861 _(KEYMAP, PAGER), \
862 _(KEYMAP, HELP), \
863 _(KEYMAP, STATUS), \
864 _(KEYMAP, STAGE)
866 DEFINE_ENUM(keymap, KEYMAP_ENUM);
868 #define set_keymap(map, name) map_enum(map, keymap_map, name)
870 struct keybinding_table {
871 struct keybinding *data;
872 size_t size;
875 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
877 static void
878 add_keybinding(enum keymap keymap, enum request request, int key)
880 struct keybinding_table *table = &keybindings[keymap];
881 size_t i;
883 for (i = 0; i < table->size; i++) {
884 if (table->data[i].alias == key) {
885 table->data[i].request = request;
886 return;
890 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
891 if (!table->data)
892 die("Failed to allocate keybinding");
893 table->data[table->size].alias = key;
894 table->data[table->size++].request = request;
896 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
897 int i;
899 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
900 if (default_keybindings[i].alias == key)
901 default_keybindings[i].request = REQ_NONE;
905 /* Looks for a key binding first in the given map, then in the generic map, and
906 * lastly in the default keybindings. */
907 static enum request
908 get_keybinding(enum keymap keymap, int key)
910 size_t i;
912 for (i = 0; i < keybindings[keymap].size; i++)
913 if (keybindings[keymap].data[i].alias == key)
914 return keybindings[keymap].data[i].request;
916 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
917 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
918 return keybindings[KEYMAP_GENERIC].data[i].request;
920 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
921 if (default_keybindings[i].alias == key)
922 return default_keybindings[i].request;
924 return (enum request) key;
928 struct key {
929 const char *name;
930 int value;
933 static const struct key key_table[] = {
934 { "Enter", KEY_RETURN },
935 { "Space", ' ' },
936 { "Backspace", KEY_BACKSPACE },
937 { "Tab", KEY_TAB },
938 { "Escape", KEY_ESC },
939 { "Left", KEY_LEFT },
940 { "Right", KEY_RIGHT },
941 { "Up", KEY_UP },
942 { "Down", KEY_DOWN },
943 { "Insert", KEY_IC },
944 { "Delete", KEY_DC },
945 { "Hash", '#' },
946 { "Home", KEY_HOME },
947 { "End", KEY_END },
948 { "PageUp", KEY_PPAGE },
949 { "PageDown", KEY_NPAGE },
950 { "F1", KEY_F(1) },
951 { "F2", KEY_F(2) },
952 { "F3", KEY_F(3) },
953 { "F4", KEY_F(4) },
954 { "F5", KEY_F(5) },
955 { "F6", KEY_F(6) },
956 { "F7", KEY_F(7) },
957 { "F8", KEY_F(8) },
958 { "F9", KEY_F(9) },
959 { "F10", KEY_F(10) },
960 { "F11", KEY_F(11) },
961 { "F12", KEY_F(12) },
964 static int
965 get_key_value(const char *name)
967 int i;
969 for (i = 0; i < ARRAY_SIZE(key_table); i++)
970 if (!strcasecmp(key_table[i].name, name))
971 return key_table[i].value;
973 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
974 return (int)name[1] & 0x1f;
975 if (strlen(name) == 1 && isprint(*name))
976 return (int) *name;
977 return ERR;
980 static const char *
981 get_key_name(int key_value)
983 static char key_char[] = "'X'\0";
984 const char *seq = NULL;
985 int key;
987 for (key = 0; key < ARRAY_SIZE(key_table); key++)
988 if (key_table[key].value == key_value)
989 seq = key_table[key].name;
991 if (seq == NULL && key_value < 0x7f) {
992 char *s = key_char + 1;
994 if (key_value >= 0x20) {
995 *s++ = key_value;
996 } else {
997 *s++ = '^';
998 *s++ = 0x40 | (key_value & 0x1f);
1000 *s++ = '\'';
1001 *s++ = '\0';
1002 seq = key_char;
1005 return seq ? seq : "(no key)";
1008 static bool
1009 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1011 const char *sep = *pos > 0 ? ", " : "";
1012 const char *keyname = get_key_name(keybinding->alias);
1014 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1017 static bool
1018 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1019 enum keymap keymap, bool all)
1021 int i;
1023 for (i = 0; i < keybindings[keymap].size; i++) {
1024 if (keybindings[keymap].data[i].request == request) {
1025 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
1026 return FALSE;
1027 if (!all)
1028 break;
1032 return TRUE;
1035 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
1037 static const char *
1038 get_keys(enum keymap keymap, enum request request, bool all)
1040 static char buf[BUFSIZ];
1041 size_t pos = 0;
1042 int i;
1044 buf[pos] = 0;
1046 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1047 return "Too many keybindings!";
1048 if (pos > 0 && !all)
1049 return buf;
1051 if (keymap != KEYMAP_GENERIC) {
1052 /* Only the generic keymap includes the default keybindings when
1053 * listing all keys. */
1054 if (all)
1055 return buf;
1057 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
1058 return "Too many keybindings!";
1059 if (pos)
1060 return buf;
1063 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1064 if (default_keybindings[i].request == request) {
1065 if (!append_key(buf, &pos, &default_keybindings[i]))
1066 return "Too many keybindings!";
1067 if (!all)
1068 return buf;
1072 return buf;
1075 struct run_request {
1076 enum keymap keymap;
1077 int key;
1078 const char **argv;
1079 bool silent;
1082 static struct run_request *run_request;
1083 static size_t run_requests;
1085 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1087 static enum request
1088 add_run_request(enum keymap keymap, int key, const char **argv, bool silent)
1090 struct run_request *req;
1092 if (!realloc_run_requests(&run_request, run_requests, 1))
1093 return REQ_NONE;
1095 req = &run_request[run_requests];
1096 req->silent = silent;
1097 req->keymap = keymap;
1098 req->key = key;
1099 req->argv = NULL;
1101 if (!argv_copy(&req->argv, argv))
1102 return REQ_NONE;
1104 return REQ_NONE + ++run_requests;
1107 static struct run_request *
1108 get_run_request(enum request request)
1110 if (request <= REQ_NONE)
1111 return NULL;
1112 return &run_request[request - REQ_NONE - 1];
1115 static void
1116 add_builtin_run_requests(void)
1118 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1119 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1120 const char *commit[] = { "git", "commit", NULL };
1121 const char *gc[] = { "git", "gc", NULL };
1122 struct run_request reqs[] = {
1123 { KEYMAP_MAIN, 'C', cherry_pick },
1124 { KEYMAP_STATUS, 'C', commit },
1125 { KEYMAP_BRANCH, 'C', checkout },
1126 { KEYMAP_GENERIC, 'G', gc },
1128 int i;
1130 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1131 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1133 if (req != reqs[i].key)
1134 continue;
1135 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv, FALSE);
1136 if (req != REQ_NONE)
1137 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1142 * User config file handling.
1145 #define OPT_ERR_INFO \
1146 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1147 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1148 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1149 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1150 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1151 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1152 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1153 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1154 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1155 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1156 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1157 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1158 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1159 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1160 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1161 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1162 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1163 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1164 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1166 enum option_code {
1167 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1168 OPT_ERR_INFO
1169 #undef OPT_ERR_
1170 OPT_OK
1173 static const char *option_errors[] = {
1174 #define OPT_ERR_(name, msg) msg
1175 OPT_ERR_INFO
1176 #undef OPT_ERR_
1179 static const struct enum_map color_map[] = {
1180 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1181 COLOR_MAP(DEFAULT),
1182 COLOR_MAP(BLACK),
1183 COLOR_MAP(BLUE),
1184 COLOR_MAP(CYAN),
1185 COLOR_MAP(GREEN),
1186 COLOR_MAP(MAGENTA),
1187 COLOR_MAP(RED),
1188 COLOR_MAP(WHITE),
1189 COLOR_MAP(YELLOW),
1192 static const struct enum_map attr_map[] = {
1193 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1194 ATTR_MAP(NORMAL),
1195 ATTR_MAP(BLINK),
1196 ATTR_MAP(BOLD),
1197 ATTR_MAP(DIM),
1198 ATTR_MAP(REVERSE),
1199 ATTR_MAP(STANDOUT),
1200 ATTR_MAP(UNDERLINE),
1203 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1205 static enum option_code
1206 parse_step(double *opt, const char *arg)
1208 *opt = atoi(arg);
1209 if (!strchr(arg, '%'))
1210 return OPT_OK;
1212 /* "Shift down" so 100% and 1 does not conflict. */
1213 *opt = (*opt - 1) / 100;
1214 if (*opt >= 1.0) {
1215 *opt = 0.99;
1216 return OPT_ERR_INVALID_STEP_VALUE;
1218 if (*opt < 0.0) {
1219 *opt = 1;
1220 return OPT_ERR_INVALID_STEP_VALUE;
1222 return OPT_OK;
1225 static enum option_code
1226 parse_int(int *opt, const char *arg, int min, int max)
1228 int value = atoi(arg);
1230 if (min <= value && value <= max) {
1231 *opt = value;
1232 return OPT_OK;
1235 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1238 static bool
1239 set_color(int *color, const char *name)
1241 if (map_enum(color, color_map, name))
1242 return TRUE;
1243 if (!prefixcmp(name, "color"))
1244 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1245 return FALSE;
1248 /* Wants: object fgcolor bgcolor [attribute] */
1249 static enum option_code
1250 option_color_command(int argc, const char *argv[])
1252 struct line_info *info;
1254 if (argc < 3)
1255 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1257 if (*argv[0] == '"' || *argv[0] == '\'') {
1258 info = add_custom_color(argv[0]);
1259 } else {
1260 info = get_line_info(argv[0]);
1262 if (!info) {
1263 static const struct enum_map obsolete[] = {
1264 ENUM_MAP("main-delim", LINE_DELIMITER),
1265 ENUM_MAP("main-date", LINE_DATE),
1266 ENUM_MAP("main-author", LINE_AUTHOR),
1268 int index;
1270 if (!map_enum(&index, obsolete, argv[0]))
1271 return OPT_ERR_UNKNOWN_COLOR_NAME;
1272 info = &line_info[index];
1275 if (!set_color(&info->fg, argv[1]) ||
1276 !set_color(&info->bg, argv[2]))
1277 return OPT_ERR_UNKNOWN_COLOR;
1279 info->attr = 0;
1280 while (argc-- > 3) {
1281 int attr;
1283 if (!set_attribute(&attr, argv[argc]))
1284 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1285 info->attr |= attr;
1288 return OPT_OK;
1291 static enum option_code
1292 parse_bool(bool *opt, const char *arg)
1294 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1295 ? TRUE : FALSE;
1296 return OPT_OK;
1299 static enum option_code
1300 parse_enum_do(unsigned int *opt, const char *arg,
1301 const struct enum_map *map, size_t map_size)
1303 bool is_true;
1305 assert(map_size > 1);
1307 if (map_enum_do(map, map_size, (int *) opt, arg))
1308 return OPT_OK;
1310 parse_bool(&is_true, arg);
1311 *opt = is_true ? map[1].value : map[0].value;
1312 return OPT_OK;
1315 #define parse_enum(opt, arg, map) \
1316 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1318 static enum option_code
1319 parse_string(char *opt, const char *arg, size_t optsize)
1321 int arglen = strlen(arg);
1323 switch (arg[0]) {
1324 case '\"':
1325 case '\'':
1326 if (arglen == 1 || arg[arglen - 1] != arg[0])
1327 return OPT_ERR_UNMATCHED_QUOTATION;
1328 arg += 1; arglen -= 2;
1329 default:
1330 string_ncopy_do(opt, optsize, arg, arglen);
1331 return OPT_OK;
1335 static enum option_code
1336 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1338 char buf[SIZEOF_STR];
1339 enum option_code code = parse_string(buf, arg, sizeof(buf));
1341 if (code == OPT_OK) {
1342 struct encoding *encoding = *encoding_ref;
1344 if (encoding && !priority)
1345 return code;
1346 encoding = encoding_open(buf);
1347 if (encoding)
1348 *encoding_ref = encoding;
1351 return code;
1354 static enum option_code
1355 parse_args(const char ***args, const char *argv[])
1357 if (*args == NULL && !argv_copy(args, argv))
1358 return OPT_ERR_OUT_OF_MEMORY;
1359 return OPT_OK;
1362 /* Wants: name = value */
1363 static enum option_code
1364 option_set_command(int argc, const char *argv[])
1366 if (argc < 3)
1367 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1369 if (strcmp(argv[1], "="))
1370 return OPT_ERR_NO_VALUE_ASSIGNED;
1372 if (!strcmp(argv[0], "blame-options"))
1373 return parse_args(&opt_blame_argv, argv + 2);
1375 if (argc != 3)
1376 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1378 if (!strcmp(argv[0], "show-author"))
1379 return parse_enum(&opt_author, argv[2], author_map);
1381 if (!strcmp(argv[0], "show-date"))
1382 return parse_enum(&opt_date, argv[2], date_map);
1384 if (!strcmp(argv[0], "show-rev-graph"))
1385 return parse_bool(&opt_rev_graph, argv[2]);
1387 if (!strcmp(argv[0], "show-refs"))
1388 return parse_bool(&opt_show_refs, argv[2]);
1390 if (!strcmp(argv[0], "show-changes"))
1391 return parse_bool(&opt_show_changes, argv[2]);
1393 if (!strcmp(argv[0], "show-notes")) {
1394 int res;
1396 strcpy(opt_notes_arg, "--notes=");
1397 res = parse_string(opt_notes_arg + 8, argv[2],
1398 sizeof(opt_notes_arg) - 8);
1399 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1400 opt_notes_arg[7] = '\0';
1401 return res;
1404 if (!strcmp(argv[0], "show-line-numbers"))
1405 return parse_bool(&opt_line_number, argv[2]);
1407 if (!strcmp(argv[0], "line-graphics"))
1408 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1410 if (!strcmp(argv[0], "line-number-interval"))
1411 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1413 if (!strcmp(argv[0], "author-width"))
1414 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1416 if (!strcmp(argv[0], "filename-width"))
1417 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1419 if (!strcmp(argv[0], "show-filename"))
1420 return parse_enum(&opt_filename, argv[2], filename_map);
1422 if (!strcmp(argv[0], "horizontal-scroll"))
1423 return parse_step(&opt_hscroll, argv[2]);
1425 if (!strcmp(argv[0], "split-view-height"))
1426 return parse_step(&opt_scale_split_view, argv[2]);
1428 if (!strcmp(argv[0], "tab-size"))
1429 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1431 if (!strcmp(argv[0], "diff-context")) {
1432 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1434 if (code == OPT_OK)
1435 update_diff_context_arg(opt_diff_context);
1436 return code;
1439 if (!strcmp(argv[0], "ignore-space")) {
1440 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1442 if (code == OPT_OK)
1443 update_ignore_space_arg();
1444 return code;
1447 if (!strcmp(argv[0], "status-untracked-dirs"))
1448 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1450 if (!strcmp(argv[0], "use-git-colors"))
1451 return parse_bool(&opt_read_git_colors, argv[2]);
1453 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1456 /* Wants: mode request key */
1457 static enum option_code
1458 option_bind_command(int argc, const char *argv[])
1460 enum request request;
1461 int keymap = -1;
1462 int key;
1464 if (argc < 3)
1465 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1467 if (!set_keymap(&keymap, argv[0]))
1468 return OPT_ERR_UNKNOWN_KEY_MAP;
1470 key = get_key_value(argv[1]);
1471 if (key == ERR)
1472 return OPT_ERR_UNKNOWN_KEY;
1474 request = get_request(argv[2]);
1475 if (request == REQ_UNKNOWN) {
1476 static const struct enum_map obsolete[] = {
1477 ENUM_MAP("cherry-pick", REQ_NONE),
1478 ENUM_MAP("screen-resize", REQ_NONE),
1479 ENUM_MAP("tree-parent", REQ_PARENT),
1481 int alias;
1483 if (map_enum(&alias, obsolete, argv[2])) {
1484 if (alias != REQ_NONE)
1485 add_keybinding(keymap, alias, key);
1486 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1489 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1490 bool silent = *argv[2] == '@';
1492 if (silent)
1493 argv[2]++;
1494 request = add_run_request(keymap, key, argv + 2, silent);
1496 if (request == REQ_UNKNOWN)
1497 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1499 add_keybinding(keymap, request, key);
1501 return OPT_OK;
1505 static enum option_code load_option_file(const char *path);
1507 static enum option_code
1508 option_source_command(int argc, const char *argv[])
1510 if (argc < 1)
1511 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1513 return load_option_file(argv[0]);
1516 static enum option_code
1517 set_option(const char *opt, char *value)
1519 const char *argv[SIZEOF_ARG];
1520 int argc = 0;
1522 if (!argv_from_string(argv, &argc, value))
1523 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1525 if (!strcmp(opt, "color"))
1526 return option_color_command(argc, argv);
1528 if (!strcmp(opt, "set"))
1529 return option_set_command(argc, argv);
1531 if (!strcmp(opt, "bind"))
1532 return option_bind_command(argc, argv);
1534 if (!strcmp(opt, "source"))
1535 return option_source_command(argc, argv);
1537 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1540 struct config_state {
1541 const char *path;
1542 int lineno;
1543 bool errors;
1546 static int
1547 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1549 struct config_state *config = data;
1550 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1552 config->lineno++;
1554 /* Check for comment markers, since read_properties() will
1555 * only ensure opt and value are split at first " \t". */
1556 optlen = strcspn(opt, "#");
1557 if (optlen == 0)
1558 return OK;
1560 if (opt[optlen] == 0) {
1561 /* Look for comment endings in the value. */
1562 size_t len = strcspn(value, "#");
1564 if (len < valuelen) {
1565 valuelen = len;
1566 value[valuelen] = 0;
1569 status = set_option(opt, value);
1572 if (status != OPT_OK) {
1573 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1574 option_errors[status], (int) optlen, opt);
1575 config->errors = TRUE;
1578 /* Always keep going if errors are encountered. */
1579 return OK;
1582 static enum option_code
1583 load_option_file(const char *path)
1585 struct config_state config = { path, 0, FALSE };
1586 struct io io;
1588 /* Do not read configuration from stdin if set to "" */
1589 if (!path || !strlen(path))
1590 return OPT_OK;
1592 /* It's OK that the file doesn't exist. */
1593 if (!io_open(&io, "%s", path))
1594 return OPT_ERR_FILE_DOES_NOT_EXIST;
1596 if (io_load(&io, " \t", read_option, &config) == ERR ||
1597 config.errors == TRUE)
1598 warn("Errors while loading %s.", path);
1599 return OPT_OK;
1602 static int
1603 load_options(void)
1605 const char *home = getenv("HOME");
1606 const char *tigrc_user = getenv("TIGRC_USER");
1607 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1608 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1609 char buf[SIZEOF_STR];
1611 if (!tigrc_system)
1612 tigrc_system = SYSCONFDIR "/tigrc";
1613 load_option_file(tigrc_system);
1615 if (!tigrc_user) {
1616 if (!home || !string_format(buf, "%s/.tigrc", home))
1617 return ERR;
1618 tigrc_user = buf;
1620 load_option_file(tigrc_user);
1622 /* Add _after_ loading config files to avoid adding run requests
1623 * that conflict with keybindings. */
1624 add_builtin_run_requests();
1626 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1627 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1628 int argc = 0;
1630 if (!string_format(buf, "%s", tig_diff_opts) ||
1631 !argv_from_string(diff_opts, &argc, buf))
1632 die("TIG_DIFF_OPTS contains too many arguments");
1633 else if (!argv_copy(&opt_diff_argv, diff_opts))
1634 die("Failed to format TIG_DIFF_OPTS arguments");
1637 return OK;
1642 * The viewer
1645 struct view;
1646 struct view_ops;
1648 /* The display array of active views and the index of the current view. */
1649 static struct view *display[2];
1650 static WINDOW *display_win[2];
1651 static WINDOW *display_title[2];
1652 static unsigned int current_view;
1654 #define foreach_displayed_view(view, i) \
1655 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1657 #define displayed_views() (display[1] != NULL ? 2 : 1)
1659 /* Current head and commit ID */
1660 static char ref_blob[SIZEOF_REF] = "";
1661 static char ref_commit[SIZEOF_REF] = "HEAD";
1662 static char ref_head[SIZEOF_REF] = "HEAD";
1663 static char ref_branch[SIZEOF_REF] = "";
1665 enum view_flag {
1666 VIEW_NO_FLAGS = 0,
1667 VIEW_ALWAYS_LINENO = 1 << 0,
1668 VIEW_CUSTOM_STATUS = 1 << 1,
1669 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1670 VIEW_ADD_PAGER_REFS = 1 << 3,
1671 VIEW_OPEN_DIFF = 1 << 4,
1672 VIEW_NO_REF = 1 << 5,
1673 VIEW_NO_GIT_DIR = 1 << 6,
1674 VIEW_DIFF_LIKE = 1 << 7,
1677 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1679 struct view {
1680 const char *name; /* View name */
1681 const char *id; /* Points to either of ref_{head,commit,blob} */
1683 struct view_ops *ops; /* View operations */
1685 enum keymap keymap; /* What keymap does this view have */
1687 char ref[SIZEOF_REF]; /* Hovered commit reference */
1688 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1690 int height, width; /* The width and height of the main window */
1691 WINDOW *win; /* The main window */
1693 /* Navigation */
1694 unsigned long offset; /* Offset of the window top */
1695 unsigned long yoffset; /* Offset from the window side. */
1696 unsigned long lineno; /* Current line number */
1697 unsigned long p_offset; /* Previous offset of the window top */
1698 unsigned long p_yoffset;/* Previous offset from the window side */
1699 unsigned long p_lineno; /* Previous current line number */
1700 bool p_restore; /* Should the previous position be restored. */
1702 /* Searching */
1703 char grep[SIZEOF_STR]; /* Search string */
1704 regex_t *regex; /* Pre-compiled regexp */
1706 /* If non-NULL, points to the view that opened this view. If this view
1707 * is closed tig will switch back to the parent view. */
1708 struct view *parent;
1709 struct view *prev;
1711 /* Buffering */
1712 size_t lines; /* Total number of lines */
1713 struct line *line; /* Line index */
1714 unsigned int digits; /* Number of digits in the lines member. */
1716 /* Drawing */
1717 struct line *curline; /* Line currently being drawn. */
1718 enum line_type curtype; /* Attribute currently used for drawing. */
1719 unsigned long col; /* Column when drawing. */
1720 bool has_scrolled; /* View was scrolled. */
1722 /* Loading */
1723 const char **argv; /* Shell command arguments. */
1724 const char *dir; /* Directory from which to execute. */
1725 struct io io;
1726 struct io *pipe;
1727 time_t start_time;
1728 time_t update_secs;
1729 struct encoding *encoding;
1731 /* Private data */
1732 void *private;
1735 enum open_flags {
1736 OPEN_DEFAULT = 0, /* Use default view switching. */
1737 OPEN_SPLIT = 1, /* Split current view. */
1738 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1739 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1740 OPEN_PREPARED = 32, /* Open already prepared command. */
1741 OPEN_EXTRA = 64, /* Open extra data from command. */
1744 struct view_ops {
1745 /* What type of content being displayed. Used in the title bar. */
1746 const char *type;
1747 /* Flags to control the view behavior. */
1748 enum view_flag flags;
1749 /* Size of private data. */
1750 size_t private_size;
1751 /* Open and reads in all view content. */
1752 bool (*open)(struct view *view, enum open_flags flags);
1753 /* Read one line; updates view->line. */
1754 bool (*read)(struct view *view, char *data);
1755 /* Draw one line; @lineno must be < view->height. */
1756 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1757 /* Depending on view handle a special requests. */
1758 enum request (*request)(struct view *view, enum request request, struct line *line);
1759 /* Search for regexp in a line. */
1760 bool (*grep)(struct view *view, struct line *line);
1761 /* Select line */
1762 void (*select)(struct view *view, struct line *line);
1765 #define VIEW_OPS(id, name, ref) name##_ops
1766 static struct view_ops VIEW_INFO(VIEW_OPS);
1768 static struct view views[] = {
1769 #define VIEW_DATA(id, name, ref) \
1770 { #name, ref, &name##_ops, KEYMAP_##id }
1771 VIEW_INFO(VIEW_DATA)
1774 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1776 #define foreach_view(view, i) \
1777 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1779 #define view_is_displayed(view) \
1780 (view == display[0] || view == display[1])
1782 static enum request
1783 view_request(struct view *view, enum request request)
1785 if (!view || !view->lines)
1786 return request;
1787 return view->ops->request(view, request, &view->line[view->lineno]);
1792 * View drawing.
1795 static inline void
1796 set_view_attr(struct view *view, enum line_type type)
1798 if (!view->curline->selected && view->curtype != type) {
1799 (void) wattrset(view->win, get_line_attr(type));
1800 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1801 view->curtype = type;
1805 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1807 static bool
1808 draw_chars(struct view *view, enum line_type type, const char *string,
1809 int max_len, bool use_tilde)
1811 static char out_buffer[BUFSIZ * 2];
1812 int len = 0;
1813 int col = 0;
1814 int trimmed = FALSE;
1815 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1817 if (max_len <= 0)
1818 return VIEW_MAX_LEN(view) <= 0;
1820 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1822 set_view_attr(view, type);
1823 if (len > 0) {
1824 if (opt_iconv_out != ICONV_NONE) {
1825 size_t inlen = len + 1;
1826 char *instr = calloc(1, inlen);
1827 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1828 if (!instr)
1829 return VIEW_MAX_LEN(view) <= 0;
1831 strncpy(instr, string, len);
1833 char *outbuf = out_buffer;
1834 size_t outlen = sizeof(out_buffer);
1836 size_t ret;
1838 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1839 if (ret != (size_t) -1) {
1840 string = out_buffer;
1841 len = sizeof(out_buffer) - outlen;
1843 free(instr);
1846 waddnstr(view->win, string, len);
1848 if (trimmed && use_tilde) {
1849 set_view_attr(view, LINE_DELIMITER);
1850 waddch(view->win, '~');
1851 col++;
1855 view->col += col;
1856 return VIEW_MAX_LEN(view) <= 0;
1859 static bool
1860 draw_space(struct view *view, enum line_type type, int max, int spaces)
1862 static char space[] = " ";
1864 spaces = MIN(max, spaces);
1866 while (spaces > 0) {
1867 int len = MIN(spaces, sizeof(space) - 1);
1869 if (draw_chars(view, type, space, len, FALSE))
1870 return TRUE;
1871 spaces -= len;
1874 return VIEW_MAX_LEN(view) <= 0;
1877 static bool
1878 draw_text(struct view *view, enum line_type type, const char *string)
1880 char text[SIZEOF_STR];
1882 do {
1883 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1885 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1886 return TRUE;
1887 string += pos;
1888 } while (*string);
1890 return VIEW_MAX_LEN(view) <= 0;
1893 static bool
1894 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1896 char text[SIZEOF_STR];
1897 int retval;
1899 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1900 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1903 static bool
1904 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1906 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1907 int max = VIEW_MAX_LEN(view);
1908 int i;
1910 if (max < size)
1911 size = max;
1913 set_view_attr(view, type);
1914 /* Using waddch() instead of waddnstr() ensures that
1915 * they'll be rendered correctly for the cursor line. */
1916 for (i = skip; i < size; i++)
1917 waddch(view->win, graphic[i]);
1919 view->col += size;
1920 if (separator) {
1921 if (size < max && skip <= size)
1922 waddch(view->win, ' ');
1923 view->col++;
1926 return VIEW_MAX_LEN(view) <= 0;
1929 static bool
1930 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1932 int max = MIN(VIEW_MAX_LEN(view), len);
1933 int col = view->col;
1935 if (!text)
1936 return draw_space(view, type, max, max);
1938 return draw_chars(view, type, text, max - 1, trim)
1939 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1942 static bool
1943 draw_date(struct view *view, struct time *time)
1945 const char *date = mkdate(time, opt_date);
1946 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1948 if (opt_date == DATE_NO)
1949 return FALSE;
1951 return draw_field(view, LINE_DATE, date, cols, FALSE);
1954 static bool
1955 draw_author(struct view *view, const char *author)
1957 bool trim = author_trim(opt_author_cols);
1958 const char *text = mkauthor(author, opt_author_cols, opt_author);
1960 if (opt_author == AUTHOR_NO)
1961 return FALSE;
1963 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1966 static bool
1967 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1969 bool trim = filename && strlen(filename) >= opt_filename_cols;
1971 if (opt_filename == FILENAME_NO)
1972 return FALSE;
1974 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1975 return FALSE;
1977 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1980 static bool
1981 draw_mode(struct view *view, mode_t mode)
1983 const char *str = mkmode(mode);
1985 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1988 static bool
1989 draw_lineno(struct view *view, unsigned int lineno)
1991 char number[10];
1992 int digits3 = view->digits < 3 ? 3 : view->digits;
1993 int max = MIN(VIEW_MAX_LEN(view), digits3);
1994 char *text = NULL;
1995 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1997 if (!opt_line_number)
1998 return FALSE;
2000 lineno += view->offset + 1;
2001 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2002 static char fmt[] = "%1ld";
2004 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2005 if (string_format(number, fmt, lineno))
2006 text = number;
2008 if (text)
2009 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2010 else
2011 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2012 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2015 static bool
2016 draw_refs(struct view *view, struct ref_list *refs)
2018 size_t i;
2020 if (!opt_show_refs || !refs)
2021 return FALSE;
2023 for (i = 0; i < refs->size; i++) {
2024 struct ref *ref = refs->refs[i];
2025 enum line_type type = get_line_type_from_ref(ref);
2027 if (draw_formatted(view, type, "[%s]", ref->name))
2028 return TRUE;
2030 if (draw_text(view, LINE_DEFAULT, " "))
2031 return TRUE;
2034 return FALSE;
2037 static bool
2038 draw_view_line(struct view *view, unsigned int lineno)
2040 struct line *line;
2041 bool selected = (view->offset + lineno == view->lineno);
2043 assert(view_is_displayed(view));
2045 if (view->offset + lineno >= view->lines)
2046 return FALSE;
2048 line = &view->line[view->offset + lineno];
2050 wmove(view->win, lineno, 0);
2051 if (line->cleareol)
2052 wclrtoeol(view->win);
2053 view->col = 0;
2054 view->curline = line;
2055 view->curtype = LINE_NONE;
2056 line->selected = FALSE;
2057 line->dirty = line->cleareol = 0;
2059 if (selected) {
2060 set_view_attr(view, LINE_CURSOR);
2061 line->selected = TRUE;
2062 view->ops->select(view, line);
2065 return view->ops->draw(view, line, lineno);
2068 static void
2069 redraw_view_dirty(struct view *view)
2071 bool dirty = FALSE;
2072 int lineno;
2074 for (lineno = 0; lineno < view->height; lineno++) {
2075 if (view->offset + lineno >= view->lines)
2076 break;
2077 if (!view->line[view->offset + lineno].dirty)
2078 continue;
2079 dirty = TRUE;
2080 if (!draw_view_line(view, lineno))
2081 break;
2084 if (!dirty)
2085 return;
2086 wnoutrefresh(view->win);
2089 static void
2090 redraw_view_from(struct view *view, int lineno)
2092 assert(0 <= lineno && lineno < view->height);
2094 for (; lineno < view->height; lineno++) {
2095 if (!draw_view_line(view, lineno))
2096 break;
2099 wnoutrefresh(view->win);
2102 static void
2103 redraw_view(struct view *view)
2105 werase(view->win);
2106 redraw_view_from(view, 0);
2110 static void
2111 update_view_title(struct view *view)
2113 char buf[SIZEOF_STR];
2114 char state[SIZEOF_STR];
2115 size_t bufpos = 0, statelen = 0;
2116 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2118 assert(view_is_displayed(view));
2120 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2121 unsigned int view_lines = view->offset + view->height;
2122 unsigned int lines = view->lines
2123 ? MIN(view_lines, view->lines) * 100 / view->lines
2124 : 0;
2126 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2127 view->ops->type,
2128 view->lineno + 1,
2129 view->lines,
2130 lines);
2134 if (view->pipe) {
2135 time_t secs = time(NULL) - view->start_time;
2137 /* Three git seconds are a long time ... */
2138 if (secs > 2)
2139 string_format_from(state, &statelen, " loading %lds", secs);
2142 string_format_from(buf, &bufpos, "[%s]", view->name);
2143 if (*view->ref && bufpos < view->width) {
2144 size_t refsize = strlen(view->ref);
2145 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2147 if (minsize < view->width)
2148 refsize = view->width - minsize + 7;
2149 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2152 if (statelen && bufpos < view->width) {
2153 string_format_from(buf, &bufpos, "%s", state);
2156 if (view == display[current_view])
2157 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2158 else
2159 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2161 mvwaddnstr(window, 0, 0, buf, bufpos);
2162 wclrtoeol(window);
2163 wnoutrefresh(window);
2166 static int
2167 apply_step(double step, int value)
2169 if (step >= 1)
2170 return (int) step;
2171 value *= step + 0.01;
2172 return value ? value : 1;
2175 static void
2176 resize_display(void)
2178 int offset, i;
2179 struct view *base = display[0];
2180 struct view *view = display[1] ? display[1] : display[0];
2182 /* Setup window dimensions */
2184 getmaxyx(stdscr, base->height, base->width);
2186 /* Make room for the status window. */
2187 base->height -= 1;
2189 if (view != base) {
2190 /* Horizontal split. */
2191 view->width = base->width;
2192 view->height = apply_step(opt_scale_split_view, base->height);
2193 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2194 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2195 base->height -= view->height;
2197 /* Make room for the title bar. */
2198 view->height -= 1;
2201 /* Make room for the title bar. */
2202 base->height -= 1;
2204 offset = 0;
2206 foreach_displayed_view (view, i) {
2207 if (!display_win[i]) {
2208 display_win[i] = newwin(view->height, view->width, offset, 0);
2209 if (!display_win[i])
2210 die("Failed to create %s view", view->name);
2212 scrollok(display_win[i], FALSE);
2214 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2215 if (!display_title[i])
2216 die("Failed to create title window");
2218 } else {
2219 wresize(display_win[i], view->height, view->width);
2220 mvwin(display_win[i], offset, 0);
2221 mvwin(display_title[i], offset + view->height, 0);
2224 view->win = display_win[i];
2226 offset += view->height + 1;
2230 static void
2231 redraw_display(bool clear)
2233 struct view *view;
2234 int i;
2236 foreach_displayed_view (view, i) {
2237 if (clear)
2238 wclear(view->win);
2239 redraw_view(view);
2240 update_view_title(view);
2246 * Option management
2249 #define TOGGLE_MENU \
2250 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2251 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2252 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2253 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2254 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2255 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2256 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2257 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2258 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2260 static bool
2261 toggle_option(enum request request)
2263 const struct {
2264 enum request request;
2265 const struct enum_map *map;
2266 size_t map_size;
2267 } data[] = {
2268 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2269 TOGGLE_MENU
2270 #undef TOGGLE_
2272 const struct menu_item menu[] = {
2273 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2274 TOGGLE_MENU
2275 #undef TOGGLE_
2276 { 0 }
2278 int i = 0;
2280 if (request == REQ_OPTIONS) {
2281 if (!prompt_menu("Toggle option", menu, &i))
2282 return FALSE;
2283 } else {
2284 while (i < ARRAY_SIZE(data) && data[i].request != request)
2285 i++;
2286 if (i >= ARRAY_SIZE(data))
2287 die("Invalid request (%d)", request);
2290 if (data[i].map != NULL) {
2291 unsigned int *opt = menu[i].data;
2293 *opt = (*opt + 1) % data[i].map_size;
2294 if (data[i].map == ignore_space_map) {
2295 update_ignore_space_arg();
2296 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2297 return TRUE;
2300 redraw_display(FALSE);
2301 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2303 } else {
2304 bool *option = menu[i].data;
2306 *option = !*option;
2307 redraw_display(FALSE);
2308 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2311 return FALSE;
2314 static void
2315 maximize_view(struct view *view, bool redraw)
2317 memset(display, 0, sizeof(display));
2318 current_view = 0;
2319 display[current_view] = view;
2320 resize_display();
2321 if (redraw) {
2322 redraw_display(FALSE);
2323 report("");
2329 * Navigation
2332 static bool
2333 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2335 if (lineno >= view->lines)
2336 lineno = view->lines > 0 ? view->lines - 1 : 0;
2338 if (offset > lineno || offset + view->height <= lineno) {
2339 unsigned long half = view->height / 2;
2341 if (lineno > half)
2342 offset = lineno - half;
2343 else
2344 offset = 0;
2347 if (offset != view->offset || lineno != view->lineno) {
2348 view->offset = offset;
2349 view->lineno = lineno;
2350 return TRUE;
2353 return FALSE;
2356 /* Scrolling backend */
2357 static void
2358 do_scroll_view(struct view *view, int lines)
2360 bool redraw_current_line = FALSE;
2362 /* The rendering expects the new offset. */
2363 view->offset += lines;
2365 assert(0 <= view->offset && view->offset < view->lines);
2366 assert(lines);
2368 /* Move current line into the view. */
2369 if (view->lineno < view->offset) {
2370 view->lineno = view->offset;
2371 redraw_current_line = TRUE;
2372 } else if (view->lineno >= view->offset + view->height) {
2373 view->lineno = view->offset + view->height - 1;
2374 redraw_current_line = TRUE;
2377 assert(view->offset <= view->lineno && view->lineno < view->lines);
2379 /* Redraw the whole screen if scrolling is pointless. */
2380 if (view->height < ABS(lines)) {
2381 redraw_view(view);
2383 } else {
2384 int line = lines > 0 ? view->height - lines : 0;
2385 int end = line + ABS(lines);
2387 scrollok(view->win, TRUE);
2388 wscrl(view->win, lines);
2389 scrollok(view->win, FALSE);
2391 while (line < end && draw_view_line(view, line))
2392 line++;
2394 if (redraw_current_line)
2395 draw_view_line(view, view->lineno - view->offset);
2396 wnoutrefresh(view->win);
2399 view->has_scrolled = TRUE;
2400 report("");
2403 /* Scroll frontend */
2404 static void
2405 scroll_view(struct view *view, enum request request)
2407 int lines = 1;
2409 assert(view_is_displayed(view));
2411 switch (request) {
2412 case REQ_SCROLL_FIRST_COL:
2413 view->yoffset = 0;
2414 redraw_view_from(view, 0);
2415 report("");
2416 return;
2417 case REQ_SCROLL_LEFT:
2418 if (view->yoffset == 0) {
2419 report("Cannot scroll beyond the first column");
2420 return;
2422 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2423 view->yoffset = 0;
2424 else
2425 view->yoffset -= apply_step(opt_hscroll, view->width);
2426 redraw_view_from(view, 0);
2427 report("");
2428 return;
2429 case REQ_SCROLL_RIGHT:
2430 view->yoffset += apply_step(opt_hscroll, view->width);
2431 redraw_view(view);
2432 report("");
2433 return;
2434 case REQ_SCROLL_PAGE_DOWN:
2435 lines = view->height;
2436 case REQ_SCROLL_LINE_DOWN:
2437 if (view->offset + lines > view->lines)
2438 lines = view->lines - view->offset;
2440 if (lines == 0 || view->offset + view->height >= view->lines) {
2441 report("Cannot scroll beyond the last line");
2442 return;
2444 break;
2446 case REQ_SCROLL_PAGE_UP:
2447 lines = view->height;
2448 case REQ_SCROLL_LINE_UP:
2449 if (lines > view->offset)
2450 lines = view->offset;
2452 if (lines == 0) {
2453 report("Cannot scroll beyond the first line");
2454 return;
2457 lines = -lines;
2458 break;
2460 default:
2461 die("request %d not handled in switch", request);
2464 do_scroll_view(view, lines);
2467 /* Cursor moving */
2468 static void
2469 move_view(struct view *view, enum request request)
2471 int scroll_steps = 0;
2472 int steps;
2474 switch (request) {
2475 case REQ_MOVE_FIRST_LINE:
2476 steps = -view->lineno;
2477 break;
2479 case REQ_MOVE_LAST_LINE:
2480 steps = view->lines - view->lineno - 1;
2481 break;
2483 case REQ_MOVE_PAGE_UP:
2484 steps = view->height > view->lineno
2485 ? -view->lineno : -view->height;
2486 break;
2488 case REQ_MOVE_PAGE_DOWN:
2489 steps = view->lineno + view->height >= view->lines
2490 ? view->lines - view->lineno - 1 : view->height;
2491 break;
2493 case REQ_MOVE_UP:
2494 steps = -1;
2495 break;
2497 case REQ_MOVE_DOWN:
2498 steps = 1;
2499 break;
2501 default:
2502 die("request %d not handled in switch", request);
2505 if (steps <= 0 && view->lineno == 0) {
2506 report("Cannot move beyond the first line");
2507 return;
2509 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2510 report("Cannot move beyond the last line");
2511 return;
2514 /* Move the current line */
2515 view->lineno += steps;
2516 assert(0 <= view->lineno && view->lineno < view->lines);
2518 /* Check whether the view needs to be scrolled */
2519 if (view->lineno < view->offset ||
2520 view->lineno >= view->offset + view->height) {
2521 scroll_steps = steps;
2522 if (steps < 0 && -steps > view->offset) {
2523 scroll_steps = -view->offset;
2525 } else if (steps > 0) {
2526 if (view->lineno == view->lines - 1 &&
2527 view->lines > view->height) {
2528 scroll_steps = view->lines - view->offset - 1;
2529 if (scroll_steps >= view->height)
2530 scroll_steps -= view->height - 1;
2535 if (!view_is_displayed(view)) {
2536 view->offset += scroll_steps;
2537 assert(0 <= view->offset && view->offset < view->lines);
2538 view->ops->select(view, &view->line[view->lineno]);
2539 return;
2542 /* Repaint the old "current" line if we be scrolling */
2543 if (ABS(steps) < view->height)
2544 draw_view_line(view, view->lineno - steps - view->offset);
2546 if (scroll_steps) {
2547 do_scroll_view(view, scroll_steps);
2548 return;
2551 /* Draw the current line */
2552 draw_view_line(view, view->lineno - view->offset);
2554 wnoutrefresh(view->win);
2555 report("");
2560 * Searching
2563 static void search_view(struct view *view, enum request request);
2565 static bool
2566 grep_text(struct view *view, const char *text[])
2568 regmatch_t pmatch;
2569 size_t i;
2571 for (i = 0; text[i]; i++)
2572 if (*text[i] &&
2573 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2574 return TRUE;
2575 return FALSE;
2578 static void
2579 select_view_line(struct view *view, unsigned long lineno)
2581 unsigned long old_lineno = view->lineno;
2582 unsigned long old_offset = view->offset;
2584 if (goto_view_line(view, view->offset, lineno)) {
2585 if (view_is_displayed(view)) {
2586 if (old_offset != view->offset) {
2587 redraw_view(view);
2588 } else {
2589 draw_view_line(view, old_lineno - view->offset);
2590 draw_view_line(view, view->lineno - view->offset);
2591 wnoutrefresh(view->win);
2593 } else {
2594 view->ops->select(view, &view->line[view->lineno]);
2599 static void
2600 find_next(struct view *view, enum request request)
2602 unsigned long lineno = view->lineno;
2603 int direction;
2605 if (!*view->grep) {
2606 if (!*opt_search)
2607 report("No previous search");
2608 else
2609 search_view(view, request);
2610 return;
2613 switch (request) {
2614 case REQ_SEARCH:
2615 case REQ_FIND_NEXT:
2616 direction = 1;
2617 break;
2619 case REQ_SEARCH_BACK:
2620 case REQ_FIND_PREV:
2621 direction = -1;
2622 break;
2624 default:
2625 return;
2628 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2629 lineno += direction;
2631 /* Note, lineno is unsigned long so will wrap around in which case it
2632 * will become bigger than view->lines. */
2633 for (; lineno < view->lines; lineno += direction) {
2634 if (view->ops->grep(view, &view->line[lineno])) {
2635 select_view_line(view, lineno);
2636 report("Line %ld matches '%s'", lineno + 1, view->grep);
2637 return;
2641 report("No match found for '%s'", view->grep);
2644 static void
2645 search_view(struct view *view, enum request request)
2647 int regex_err;
2649 if (view->regex) {
2650 regfree(view->regex);
2651 *view->grep = 0;
2652 } else {
2653 view->regex = calloc(1, sizeof(*view->regex));
2654 if (!view->regex)
2655 return;
2658 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2659 if (regex_err != 0) {
2660 char buf[SIZEOF_STR] = "unknown error";
2662 regerror(regex_err, view->regex, buf, sizeof(buf));
2663 report("Search failed: %s", buf);
2664 return;
2667 string_copy(view->grep, opt_search);
2669 find_next(view, request);
2673 * Incremental updating
2676 static void
2677 reset_view(struct view *view)
2679 int i;
2681 for (i = 0; i < view->lines; i++)
2682 free(view->line[i].data);
2683 free(view->line);
2685 view->p_offset = view->offset;
2686 view->p_yoffset = view->yoffset;
2687 view->p_lineno = view->lineno;
2689 view->line = NULL;
2690 view->offset = 0;
2691 view->yoffset = 0;
2692 view->lines = 0;
2693 view->lineno = 0;
2694 view->vid[0] = 0;
2695 view->update_secs = 0;
2698 static const char *
2699 format_arg(const char *name)
2701 static struct {
2702 const char *name;
2703 size_t namelen;
2704 const char *value;
2705 const char *value_if_empty;
2706 } vars[] = {
2707 #define FORMAT_VAR(name, value, value_if_empty) \
2708 { name, STRING_SIZE(name), value, value_if_empty }
2709 FORMAT_VAR("%(directory)", opt_path, "."),
2710 FORMAT_VAR("%(file)", opt_file, ""),
2711 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2712 FORMAT_VAR("%(head)", ref_head, ""),
2713 FORMAT_VAR("%(commit)", ref_commit, ""),
2714 FORMAT_VAR("%(blob)", ref_blob, ""),
2715 FORMAT_VAR("%(branch)", ref_branch, ""),
2717 int i;
2719 for (i = 0; i < ARRAY_SIZE(vars); i++)
2720 if (!strncmp(name, vars[i].name, vars[i].namelen))
2721 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2723 report("Unknown replacement: `%s`", name);
2724 return NULL;
2727 static bool
2728 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2730 char buf[SIZEOF_STR];
2731 int argc;
2733 argv_free(*dst_argv);
2735 for (argc = 0; src_argv[argc]; argc++) {
2736 const char *arg = src_argv[argc];
2737 size_t bufpos = 0;
2739 if (!strcmp(arg, "%(fileargs)")) {
2740 if (!argv_append_array(dst_argv, opt_file_argv))
2741 break;
2742 continue;
2744 } else if (!strcmp(arg, "%(diffargs)")) {
2745 if (!argv_append_array(dst_argv, opt_diff_argv))
2746 break;
2747 continue;
2749 } else if (!strcmp(arg, "%(blameargs)")) {
2750 if (!argv_append_array(dst_argv, opt_blame_argv))
2751 break;
2752 continue;
2754 } else if (!strcmp(arg, "%(revargs)") ||
2755 (first && !strcmp(arg, "%(commit)"))) {
2756 if (!argv_append_array(dst_argv, opt_rev_argv))
2757 break;
2758 continue;
2761 while (arg) {
2762 char *next = strstr(arg, "%(");
2763 int len = next - arg;
2764 const char *value;
2766 if (!next) {
2767 len = strlen(arg);
2768 value = "";
2770 } else {
2771 value = format_arg(next);
2773 if (!value) {
2774 return FALSE;
2778 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2779 return FALSE;
2781 arg = next ? strchr(next, ')') + 1 : NULL;
2784 if (!argv_append(dst_argv, buf))
2785 break;
2788 return src_argv[argc] == NULL;
2791 static bool
2792 restore_view_position(struct view *view)
2794 /* A view without a previous view is the first view */
2795 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2796 select_view_line(view, opt_lineno - 1);
2797 opt_lineno = 0;
2800 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2801 return FALSE;
2803 /* Changing the view position cancels the restoring. */
2804 /* FIXME: Changing back to the first line is not detected. */
2805 if (view->offset != 0 || view->lineno != 0) {
2806 view->p_restore = FALSE;
2807 return FALSE;
2810 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2811 view_is_displayed(view))
2812 werase(view->win);
2814 view->yoffset = view->p_yoffset;
2815 view->p_restore = FALSE;
2817 return TRUE;
2820 static void
2821 end_update(struct view *view, bool force)
2823 if (!view->pipe)
2824 return;
2825 while (!view->ops->read(view, NULL))
2826 if (!force)
2827 return;
2828 if (force)
2829 io_kill(view->pipe);
2830 io_done(view->pipe);
2831 view->pipe = NULL;
2834 static void
2835 setup_update(struct view *view, const char *vid)
2837 reset_view(view);
2838 string_copy_rev(view->vid, vid);
2839 view->pipe = &view->io;
2840 view->start_time = time(NULL);
2843 static bool
2844 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2846 bool extra = !!(flags & (OPEN_EXTRA));
2847 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2848 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2850 if (!reload && !strcmp(view->vid, view->id))
2851 return TRUE;
2853 if (view->pipe) {
2854 if (extra)
2855 io_done(view->pipe);
2856 else
2857 end_update(view, TRUE);
2860 if (!refresh && argv) {
2861 view->dir = dir;
2862 if (!format_argv(&view->argv, argv, !view->prev))
2863 return FALSE;
2865 /* Put the current ref_* value to the view title ref
2866 * member. This is needed by the blob view. Most other
2867 * views sets it automatically after loading because the
2868 * first line is a commit line. */
2869 string_copy_rev(view->ref, view->id);
2872 if (view->argv && view->argv[0] &&
2873 !io_run(&view->io, IO_RD, view->dir, view->argv))
2874 return FALSE;
2876 if (!extra)
2877 setup_update(view, view->id);
2879 return TRUE;
2882 static bool
2883 update_view(struct view *view)
2885 char *line;
2886 /* Clear the view and redraw everything since the tree sorting
2887 * might have rearranged things. */
2888 bool redraw = view->lines == 0;
2889 bool can_read = TRUE;
2891 if (!view->pipe)
2892 return TRUE;
2894 if (!io_can_read(view->pipe, FALSE)) {
2895 if (view->lines == 0 && view_is_displayed(view)) {
2896 time_t secs = time(NULL) - view->start_time;
2898 if (secs > 1 && secs > view->update_secs) {
2899 if (view->update_secs == 0)
2900 redraw_view(view);
2901 update_view_title(view);
2902 view->update_secs = secs;
2905 return TRUE;
2908 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2909 if (view->encoding) {
2910 line = encoding_convert(view->encoding, line);
2913 if (!view->ops->read(view, line)) {
2914 report("Allocation failure");
2915 end_update(view, TRUE);
2916 return FALSE;
2921 unsigned long lines = view->lines;
2922 int digits;
2924 for (digits = 0; lines; digits++)
2925 lines /= 10;
2927 /* Keep the displayed view in sync with line number scaling. */
2928 if (digits != view->digits) {
2929 view->digits = digits;
2930 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2931 redraw = TRUE;
2935 if (io_error(view->pipe)) {
2936 report("Failed to read: %s", io_strerror(view->pipe));
2937 end_update(view, TRUE);
2939 } else if (io_eof(view->pipe)) {
2940 if (view_is_displayed(view))
2941 report("");
2942 end_update(view, FALSE);
2945 if (restore_view_position(view))
2946 redraw = TRUE;
2948 if (!view_is_displayed(view))
2949 return TRUE;
2951 if (redraw)
2952 redraw_view_from(view, 0);
2953 else
2954 redraw_view_dirty(view);
2956 /* Update the title _after_ the redraw so that if the redraw picks up a
2957 * commit reference in view->ref it'll be available here. */
2958 update_view_title(view);
2959 return TRUE;
2962 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2964 static struct line *
2965 add_line_data(struct view *view, void *data, enum line_type type)
2967 struct line *line;
2969 if (!realloc_lines(&view->line, view->lines, 1))
2970 return NULL;
2972 line = &view->line[view->lines++];
2973 memset(line, 0, sizeof(*line));
2974 line->type = type;
2975 line->data = data;
2976 line->dirty = 1;
2978 return line;
2981 static struct line *
2982 add_line_text(struct view *view, const char *text, enum line_type type)
2984 char *data = text ? strdup(text) : NULL;
2986 return data ? add_line_data(view, data, type) : NULL;
2989 static struct line *
2990 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2992 char buf[SIZEOF_STR];
2993 int retval;
2995 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2996 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3000 * View opening
3003 static void
3004 load_view(struct view *view, enum open_flags flags)
3006 if (view->pipe)
3007 end_update(view, TRUE);
3008 if (view->ops->private_size) {
3009 if (!view->private)
3010 view->private = calloc(1, view->ops->private_size);
3011 else
3012 memset(view->private, 0, view->ops->private_size);
3014 if (!view->ops->open(view, flags)) {
3015 report("Failed to load %s view", view->name);
3016 return;
3018 restore_view_position(view);
3020 if (view->pipe && view->lines == 0) {
3021 /* Clear the old view and let the incremental updating refill
3022 * the screen. */
3023 werase(view->win);
3024 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
3025 report("");
3026 } else if (view_is_displayed(view)) {
3027 redraw_view(view);
3028 report("");
3032 #define refresh_view(view) load_view(view, OPEN_REFRESH)
3033 #define reload_view(view) load_view(view, OPEN_RELOAD)
3035 static void
3036 split_view(struct view *prev, struct view *view)
3038 display[1] = view;
3039 current_view = 1;
3040 view->parent = prev;
3041 resize_display();
3043 if (prev->lineno - prev->offset >= prev->height) {
3044 /* Take the title line into account. */
3045 int lines = prev->lineno - prev->offset - prev->height + 1;
3047 /* Scroll the view that was split if the current line is
3048 * outside the new limited view. */
3049 do_scroll_view(prev, lines);
3052 if (view != prev && view_is_displayed(prev)) {
3053 /* "Blur" the previous view. */
3054 update_view_title(prev);
3058 static void
3059 open_view(struct view *prev, enum request request, enum open_flags flags)
3061 bool split = !!(flags & OPEN_SPLIT);
3062 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3063 struct view *view = VIEW(request);
3064 int nviews = displayed_views();
3066 assert(flags ^ OPEN_REFRESH);
3068 if (view == prev && nviews == 1 && !reload) {
3069 report("Already in %s view", view->name);
3070 return;
3073 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3074 report("The %s view is disabled in pager view", view->name);
3075 return;
3078 if (split) {
3079 split_view(prev, view);
3080 } else {
3081 maximize_view(view, FALSE);
3084 /* No prev signals that this is the first loaded view. */
3085 if (prev && view != prev) {
3086 view->prev = prev;
3089 load_view(view, flags);
3092 static void
3093 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3095 enum request request = view - views + REQ_OFFSET + 1;
3097 if (view->pipe)
3098 end_update(view, TRUE);
3099 view->dir = dir;
3101 if (!argv_copy(&view->argv, argv)) {
3102 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3103 } else {
3104 open_view(prev, request, flags | OPEN_PREPARED);
3108 static void
3109 open_external_viewer(const char *argv[], const char *dir)
3111 def_prog_mode(); /* save current tty modes */
3112 endwin(); /* restore original tty modes */
3113 io_run_fg(argv, dir);
3114 fprintf(stderr, "Press Enter to continue");
3115 getc(opt_tty);
3116 reset_prog_mode();
3117 redraw_display(TRUE);
3120 static void
3121 open_mergetool(const char *file)
3123 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3125 open_external_viewer(mergetool_argv, opt_cdup);
3128 static void
3129 open_editor(const char *file)
3131 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3132 char editor_cmd[SIZEOF_STR];
3133 const char *editor;
3134 int argc = 0;
3136 editor = getenv("GIT_EDITOR");
3137 if (!editor && *opt_editor)
3138 editor = opt_editor;
3139 if (!editor)
3140 editor = getenv("VISUAL");
3141 if (!editor)
3142 editor = getenv("EDITOR");
3143 if (!editor)
3144 editor = "vi";
3146 string_ncopy(editor_cmd, editor, strlen(editor));
3147 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3148 report("Failed to read editor command");
3149 return;
3152 editor_argv[argc] = file;
3153 open_external_viewer(editor_argv, opt_cdup);
3156 static void
3157 open_run_request(enum request request)
3159 struct run_request *req = get_run_request(request);
3160 const char **argv = NULL;
3162 if (!req) {
3163 report("Unknown run request");
3164 return;
3167 if (format_argv(&argv, req->argv, FALSE)) {
3168 if (req->silent)
3169 io_run_bg(argv);
3170 else
3171 open_external_viewer(argv, NULL);
3173 if (argv)
3174 argv_free(argv);
3175 free(argv);
3179 * User request switch noodle
3182 static int
3183 view_driver(struct view *view, enum request request)
3185 int i;
3187 if (request == REQ_NONE)
3188 return TRUE;
3190 if (request > REQ_NONE) {
3191 open_run_request(request);
3192 view_request(view, REQ_REFRESH);
3193 return TRUE;
3196 request = view_request(view, request);
3197 if (request == REQ_NONE)
3198 return TRUE;
3200 switch (request) {
3201 case REQ_MOVE_UP:
3202 case REQ_MOVE_DOWN:
3203 case REQ_MOVE_PAGE_UP:
3204 case REQ_MOVE_PAGE_DOWN:
3205 case REQ_MOVE_FIRST_LINE:
3206 case REQ_MOVE_LAST_LINE:
3207 move_view(view, request);
3208 break;
3210 case REQ_SCROLL_FIRST_COL:
3211 case REQ_SCROLL_LEFT:
3212 case REQ_SCROLL_RIGHT:
3213 case REQ_SCROLL_LINE_DOWN:
3214 case REQ_SCROLL_LINE_UP:
3215 case REQ_SCROLL_PAGE_DOWN:
3216 case REQ_SCROLL_PAGE_UP:
3217 scroll_view(view, request);
3218 break;
3220 case REQ_VIEW_BLAME:
3221 if (!opt_file[0]) {
3222 report("No file chosen, press %s to open tree view",
3223 get_view_key(view, REQ_VIEW_TREE));
3224 break;
3226 open_view(view, request, OPEN_DEFAULT);
3227 break;
3229 case REQ_VIEW_BLOB:
3230 if (!ref_blob[0]) {
3231 report("No file chosen, press %s to open tree view",
3232 get_view_key(view, REQ_VIEW_TREE));
3233 break;
3235 open_view(view, request, OPEN_DEFAULT);
3236 break;
3238 case REQ_VIEW_PAGER:
3239 if (view == NULL) {
3240 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3241 die("Failed to open stdin");
3242 open_view(view, request, OPEN_PREPARED);
3243 break;
3246 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3247 report("No pager content, press %s to run command from prompt",
3248 get_view_key(view, REQ_PROMPT));
3249 break;
3251 open_view(view, request, OPEN_DEFAULT);
3252 break;
3254 case REQ_VIEW_STAGE:
3255 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3256 report("No stage content, press %s to open the status view and choose file",
3257 get_view_key(view, REQ_VIEW_STATUS));
3258 break;
3260 open_view(view, request, OPEN_DEFAULT);
3261 break;
3263 case REQ_VIEW_STATUS:
3264 if (opt_is_inside_work_tree == FALSE) {
3265 report("The status view requires a working tree");
3266 break;
3268 open_view(view, request, OPEN_DEFAULT);
3269 break;
3271 case REQ_VIEW_MAIN:
3272 case REQ_VIEW_DIFF:
3273 case REQ_VIEW_LOG:
3274 case REQ_VIEW_TREE:
3275 case REQ_VIEW_HELP:
3276 case REQ_VIEW_BRANCH:
3277 open_view(view, request, OPEN_DEFAULT);
3278 break;
3280 case REQ_NEXT:
3281 case REQ_PREVIOUS:
3282 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3284 if (view->parent) {
3285 int line;
3287 view = view->parent;
3288 line = view->lineno;
3289 move_view(view, request);
3290 if (view_is_displayed(view))
3291 update_view_title(view);
3292 if (line != view->lineno)
3293 view_request(view, REQ_ENTER);
3294 } else {
3295 move_view(view, request);
3297 break;
3299 case REQ_VIEW_NEXT:
3301 int nviews = displayed_views();
3302 int next_view = (current_view + 1) % nviews;
3304 if (next_view == current_view) {
3305 report("Only one view is displayed");
3306 break;
3309 current_view = next_view;
3310 /* Blur out the title of the previous view. */
3311 update_view_title(view);
3312 report("");
3313 break;
3315 case REQ_REFRESH:
3316 report("Refreshing is not yet supported for the %s view", view->name);
3317 break;
3319 case REQ_MAXIMIZE:
3320 if (displayed_views() == 2)
3321 maximize_view(view, TRUE);
3322 break;
3324 case REQ_OPTIONS:
3325 case REQ_TOGGLE_LINENO:
3326 case REQ_TOGGLE_DATE:
3327 case REQ_TOGGLE_AUTHOR:
3328 case REQ_TOGGLE_FILENAME:
3329 case REQ_TOGGLE_GRAPHIC:
3330 case REQ_TOGGLE_REV_GRAPH:
3331 case REQ_TOGGLE_REFS:
3332 case REQ_TOGGLE_CHANGES:
3333 case REQ_TOGGLE_IGNORE_SPACE:
3334 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3335 reload_view(view);
3336 break;
3338 case REQ_TOGGLE_SORT_FIELD:
3339 case REQ_TOGGLE_SORT_ORDER:
3340 report("Sorting is not yet supported for the %s view", view->name);
3341 break;
3343 case REQ_DIFF_CONTEXT_UP:
3344 case REQ_DIFF_CONTEXT_DOWN:
3345 report("Changing the diff context is not yet supported for the %s view", view->name);
3346 break;
3348 case REQ_SEARCH:
3349 case REQ_SEARCH_BACK:
3350 search_view(view, request);
3351 break;
3353 case REQ_FIND_NEXT:
3354 case REQ_FIND_PREV:
3355 find_next(view, request);
3356 break;
3358 case REQ_STOP_LOADING:
3359 foreach_view(view, i) {
3360 if (view->pipe)
3361 report("Stopped loading the %s view", view->name),
3362 end_update(view, TRUE);
3364 break;
3366 case REQ_SHOW_VERSION:
3367 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3368 return TRUE;
3370 case REQ_SCREEN_REDRAW:
3371 redraw_display(TRUE);
3372 break;
3374 case REQ_EDIT:
3375 report("Nothing to edit");
3376 break;
3378 case REQ_ENTER:
3379 report("Nothing to enter");
3380 break;
3382 case REQ_VIEW_CLOSE:
3383 /* XXX: Mark closed views by letting view->prev point to the
3384 * view itself. Parents to closed view should never be
3385 * followed. */
3386 if (view->prev && view->prev != view) {
3387 maximize_view(view->prev, TRUE);
3388 view->prev = view;
3389 break;
3391 /* Fall-through */
3392 case REQ_QUIT:
3393 return FALSE;
3395 default:
3396 report("Unknown key, press %s for help",
3397 get_view_key(view, REQ_VIEW_HELP));
3398 return TRUE;
3401 return TRUE;
3406 * View backend utilities
3409 enum sort_field {
3410 ORDERBY_NAME,
3411 ORDERBY_DATE,
3412 ORDERBY_AUTHOR,
3415 struct sort_state {
3416 const enum sort_field *fields;
3417 size_t size, current;
3418 bool reverse;
3421 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3422 #define get_sort_field(state) ((state).fields[(state).current])
3423 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3425 static void
3426 sort_view(struct view *view, enum request request, struct sort_state *state,
3427 int (*compare)(const void *, const void *))
3429 switch (request) {
3430 case REQ_TOGGLE_SORT_FIELD:
3431 state->current = (state->current + 1) % state->size;
3432 break;
3434 case REQ_TOGGLE_SORT_ORDER:
3435 state->reverse = !state->reverse;
3436 break;
3437 default:
3438 die("Not a sort request");
3441 qsort(view->line, view->lines, sizeof(*view->line), compare);
3442 redraw_view(view);
3445 static bool
3446 update_diff_context(enum request request)
3448 int diff_context = opt_diff_context;
3450 switch (request) {
3451 case REQ_DIFF_CONTEXT_UP:
3452 opt_diff_context += 1;
3453 update_diff_context_arg(opt_diff_context);
3454 break;
3456 case REQ_DIFF_CONTEXT_DOWN:
3457 if (opt_diff_context == 0) {
3458 report("Diff context cannot be less than zero");
3459 break;
3461 opt_diff_context -= 1;
3462 update_diff_context_arg(opt_diff_context);
3463 break;
3465 default:
3466 die("Not a diff context request");
3469 return diff_context != opt_diff_context;
3472 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3474 /* Small author cache to reduce memory consumption. It uses binary
3475 * search to lookup or find place to position new entries. No entries
3476 * are ever freed. */
3477 static const char *
3478 get_author(const char *name)
3480 static const char **authors;
3481 static size_t authors_size;
3482 int from = 0, to = authors_size - 1;
3484 while (from <= to) {
3485 size_t pos = (to + from) / 2;
3486 int cmp = strcmp(name, authors[pos]);
3488 if (!cmp)
3489 return authors[pos];
3491 if (cmp < 0)
3492 to = pos - 1;
3493 else
3494 from = pos + 1;
3497 if (!realloc_authors(&authors, authors_size, 1))
3498 return NULL;
3499 name = strdup(name);
3500 if (!name)
3501 return NULL;
3503 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3504 authors[from] = name;
3505 authors_size++;
3507 return name;
3510 static void
3511 parse_timesec(struct time *time, const char *sec)
3513 time->sec = (time_t) atol(sec);
3516 static void
3517 parse_timezone(struct time *time, const char *zone)
3519 long tz;
3521 tz = ('0' - zone[1]) * 60 * 60 * 10;
3522 tz += ('0' - zone[2]) * 60 * 60;
3523 tz += ('0' - zone[3]) * 60 * 10;
3524 tz += ('0' - zone[4]) * 60;
3526 if (zone[0] == '-')
3527 tz = -tz;
3529 time->tz = tz;
3530 time->sec -= tz;
3533 /* Parse author lines where the name may be empty:
3534 * author <email@address.tld> 1138474660 +0100
3536 static void
3537 parse_author_line(char *ident, const char **author, struct time *time)
3539 char *nameend = strchr(ident, '<');
3540 char *emailend = strchr(ident, '>');
3542 if (nameend && emailend)
3543 *nameend = *emailend = 0;
3544 ident = chomp_string(ident);
3545 if (!*ident) {
3546 if (nameend)
3547 ident = chomp_string(nameend + 1);
3548 if (!*ident)
3549 ident = "Unknown";
3552 *author = get_author(ident);
3554 /* Parse epoch and timezone */
3555 if (emailend && emailend[1] == ' ') {
3556 char *secs = emailend + 2;
3557 char *zone = strchr(secs, ' ');
3559 parse_timesec(time, secs);
3561 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3562 parse_timezone(time, zone + 1);
3566 static struct line *
3567 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3569 for (; view->line < line; line--)
3570 if (line->type == type)
3571 return line;
3573 return NULL;
3577 * Blame
3580 struct blame_commit {
3581 char id[SIZEOF_REV]; /* SHA1 ID. */
3582 char title[128]; /* First line of the commit message. */
3583 const char *author; /* Author of the commit. */
3584 struct time time; /* Date from the author ident. */
3585 char filename[128]; /* Name of file. */
3586 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3587 char parent_filename[128]; /* Parent/previous name of file. */
3590 struct blame_header {
3591 char id[SIZEOF_REV]; /* SHA1 ID. */
3592 size_t orig_lineno;
3593 size_t lineno;
3594 size_t group;
3597 static bool
3598 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3600 const char *pos = *posref;
3602 *posref = NULL;
3603 pos = strchr(pos + 1, ' ');
3604 if (!pos || !isdigit(pos[1]))
3605 return FALSE;
3606 *number = atoi(pos + 1);
3607 if (*number < min || *number > max)
3608 return FALSE;
3610 *posref = pos;
3611 return TRUE;
3614 static bool
3615 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3617 const char *pos = text + SIZEOF_REV - 2;
3619 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3620 return FALSE;
3622 string_ncopy(header->id, text, SIZEOF_REV);
3624 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3625 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3626 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3627 return FALSE;
3629 return TRUE;
3632 static bool
3633 match_blame_header(const char *name, char **line)
3635 size_t namelen = strlen(name);
3636 bool matched = !strncmp(name, *line, namelen);
3638 if (matched)
3639 *line += namelen;
3641 return matched;
3644 static bool
3645 parse_blame_info(struct blame_commit *commit, char *line)
3647 if (match_blame_header("author ", &line)) {
3648 commit->author = get_author(line);
3650 } else if (match_blame_header("author-time ", &line)) {
3651 parse_timesec(&commit->time, line);
3653 } else if (match_blame_header("author-tz ", &line)) {
3654 parse_timezone(&commit->time, line);
3656 } else if (match_blame_header("summary ", &line)) {
3657 string_ncopy(commit->title, line, strlen(line));
3659 } else if (match_blame_header("previous ", &line)) {
3660 if (strlen(line) <= SIZEOF_REV)
3661 return FALSE;
3662 string_copy_rev(commit->parent_id, line);
3663 line += SIZEOF_REV;
3664 string_ncopy(commit->parent_filename, line, strlen(line));
3666 } else if (match_blame_header("filename ", &line)) {
3667 string_ncopy(commit->filename, line, strlen(line));
3668 return TRUE;
3671 return FALSE;
3675 * Pager backend
3678 static bool
3679 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3681 if (draw_lineno(view, lineno))
3682 return TRUE;
3684 draw_text(view, line->type, line->data);
3685 return TRUE;
3688 static bool
3689 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3691 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3692 char ref[SIZEOF_STR];
3694 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3695 return TRUE;
3697 /* This is the only fatal call, since it can "corrupt" the buffer. */
3698 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3699 return FALSE;
3701 return TRUE;
3704 static void
3705 add_pager_refs(struct view *view, struct line *line)
3707 char buf[SIZEOF_STR];
3708 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3709 struct ref_list *list;
3710 size_t bufpos = 0, i;
3711 const char *sep = "Refs: ";
3712 bool is_tag = FALSE;
3714 assert(line->type == LINE_COMMIT);
3716 list = get_ref_list(commit_id);
3717 if (!list) {
3718 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3719 goto try_add_describe_ref;
3720 return;
3723 for (i = 0; i < list->size; i++) {
3724 struct ref *ref = list->refs[i];
3725 const char *fmt = ref->tag ? "%s[%s]" :
3726 ref->remote ? "%s<%s>" : "%s%s";
3728 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3729 return;
3730 sep = ", ";
3731 if (ref->tag)
3732 is_tag = TRUE;
3735 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3736 try_add_describe_ref:
3737 /* Add <tag>-g<commit_id> "fake" reference. */
3738 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3739 return;
3742 if (bufpos == 0)
3743 return;
3745 add_line_text(view, buf, LINE_PP_REFS);
3748 static bool
3749 pager_common_read(struct view *view, char *data, enum line_type type)
3751 struct line *line;
3753 if (!data)
3754 return TRUE;
3756 line = add_line_text(view, data, type);
3757 if (!line)
3758 return FALSE;
3760 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3761 add_pager_refs(view, line);
3763 return TRUE;
3766 static bool
3767 pager_read(struct view *view, char *data)
3769 if (!data)
3770 return TRUE;
3772 return pager_common_read(view, data, get_line_type(data));
3775 static enum request
3776 pager_request(struct view *view, enum request request, struct line *line)
3778 int split = 0;
3780 if (request != REQ_ENTER)
3781 return request;
3783 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3784 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3785 split = 1;
3788 /* Always scroll the view even if it was split. That way
3789 * you can use Enter to scroll through the log view and
3790 * split open each commit diff. */
3791 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3793 /* FIXME: A minor workaround. Scrolling the view will call report("")
3794 * but if we are scrolling a non-current view this won't properly
3795 * update the view title. */
3796 if (split)
3797 update_view_title(view);
3799 return REQ_NONE;
3802 static bool
3803 pager_grep(struct view *view, struct line *line)
3805 const char *text[] = { line->data, NULL };
3807 return grep_text(view, text);
3810 static void
3811 pager_select(struct view *view, struct line *line)
3813 if (line->type == LINE_COMMIT) {
3814 char *text = (char *)line->data + STRING_SIZE("commit ");
3816 if (!view_has_flags(view, VIEW_NO_REF))
3817 string_copy_rev(view->ref, text);
3818 string_copy_rev(ref_commit, text);
3822 static bool
3823 pager_open(struct view *view, enum open_flags flags)
3825 return begin_update(view, NULL, NULL, flags);
3828 static struct view_ops pager_ops = {
3829 "line",
3830 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3832 pager_open,
3833 pager_read,
3834 pager_draw,
3835 pager_request,
3836 pager_grep,
3837 pager_select,
3840 static bool
3841 log_open(struct view *view, enum open_flags flags)
3843 static const char *log_argv[] = {
3844 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3847 return begin_update(view, NULL, log_argv, flags);
3850 static enum request
3851 log_request(struct view *view, enum request request, struct line *line)
3853 switch (request) {
3854 case REQ_REFRESH:
3855 load_refs();
3856 refresh_view(view);
3857 return REQ_NONE;
3858 default:
3859 return pager_request(view, request, line);
3863 static struct view_ops log_ops = {
3864 "line",
3865 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3867 log_open,
3868 pager_read,
3869 pager_draw,
3870 log_request,
3871 pager_grep,
3872 pager_select,
3875 struct diff_state {
3876 bool reading_diff_stat;
3877 bool combined_diff;
3880 static bool
3881 diff_open(struct view *view, enum open_flags flags)
3883 static const char *diff_argv[] = {
3884 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3885 "--patch-with-stat", "--find-copies-harder", "-C",
3886 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3887 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3890 return begin_update(view, NULL, diff_argv, flags);
3893 static bool
3894 diff_common_read(struct view *view, char *data, struct diff_state *state)
3896 enum line_type type;
3898 if (state->reading_diff_stat) {
3899 size_t len = strlen(data);
3900 char *pipe = strchr(data, '|');
3901 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3902 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3904 if (pipe && (has_histogram || has_bin_diff)) {
3905 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3906 } else {
3907 state->reading_diff_stat = FALSE;
3910 } else if (!strcmp(data, "---")) {
3911 state->reading_diff_stat = TRUE;
3914 type = get_line_type(data);
3916 if (type == LINE_DIFF_HEADER) {
3917 const int len = line_info[LINE_DIFF_HEADER].linelen;
3919 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3920 !strncmp(data + len, "cc ", strlen("cc ")))
3921 state->combined_diff = TRUE;
3924 /* ADD2 and DEL2 are only valid in combined diff hunks */
3925 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3926 type = LINE_DEFAULT;
3928 return pager_common_read(view, data, type);
3931 static enum request
3932 diff_common_enter(struct view *view, enum request request, struct line *line)
3934 if (line->type == LINE_DIFF_STAT) {
3935 int file_number = 0;
3937 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3938 file_number++;
3939 line--;
3942 while (line < view->line + view->lines) {
3943 if (line->type == LINE_DIFF_HEADER) {
3944 if (file_number == 1) {
3945 break;
3947 file_number--;
3949 line++;
3953 select_view_line(view, line - view->line);
3954 report("");
3955 return REQ_NONE;
3957 } else {
3958 return pager_request(view, request, line);
3962 static bool
3963 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3965 char *sep = strchr(*text, c);
3967 if (sep != NULL) {
3968 *sep = 0;
3969 draw_text(view, *type, *text);
3970 *sep = c;
3971 *text = sep;
3972 *type = next_type;
3975 return sep != NULL;
3978 static bool
3979 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3981 char *text = line->data;
3982 enum line_type type = line->type;
3984 if (draw_lineno(view, lineno))
3985 return TRUE;
3987 if (type == LINE_DIFF_STAT) {
3988 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3989 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3990 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3991 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3992 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3993 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3994 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3996 } else {
3997 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3998 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4002 draw_text(view, type, text);
4003 return TRUE;
4006 static bool
4007 diff_read(struct view *view, char *data)
4009 struct diff_state *state = view->private;
4011 if (!data) {
4012 /* Fall back to retry if no diff will be shown. */
4013 if (view->lines == 0 && opt_file_argv) {
4014 int pos = argv_size(view->argv)
4015 - argv_size(opt_file_argv) - 1;
4017 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4018 for (; view->argv[pos]; pos++) {
4019 free((void *) view->argv[pos]);
4020 view->argv[pos] = NULL;
4023 if (view->pipe)
4024 io_done(view->pipe);
4025 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4026 return FALSE;
4029 return TRUE;
4032 return diff_common_read(view, data, state);
4035 static bool
4036 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4037 struct blame_header *header, struct blame_commit *commit)
4039 char line_arg[SIZEOF_STR];
4040 const char *blame_argv[] = {
4041 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4043 struct io io;
4044 bool ok = FALSE;
4045 char *buf;
4047 if (!string_format(line_arg, "-L%d,+1", lineno))
4048 return FALSE;
4050 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4051 return FALSE;
4053 while ((buf = io_get(&io, '\n', TRUE))) {
4054 if (header) {
4055 if (!parse_blame_header(header, buf, 9999999))
4056 break;
4057 header = NULL;
4059 } else if (parse_blame_info(commit, buf)) {
4060 ok = TRUE;
4061 break;
4065 if (io_error(&io))
4066 ok = FALSE;
4068 io_done(&io);
4069 return ok;
4072 static bool
4073 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4075 return prefixcmp(chunk, "@@ -") ||
4076 !(chunk = strchr(chunk, marker)) ||
4077 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4080 static enum request
4081 diff_trace_origin(struct view *view, struct line *line)
4083 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4084 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4085 const char *chunk_data;
4086 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4087 int lineno = 0;
4088 const char *file = NULL;
4089 char ref[SIZEOF_REF];
4090 struct blame_header header;
4091 struct blame_commit commit;
4093 if (!diff || !chunk || chunk == line) {
4094 report("The line to trace must be inside a diff chunk");
4095 return REQ_NONE;
4098 for (; diff < line && !file; diff++) {
4099 const char *data = diff->data;
4101 if (!prefixcmp(data, "--- a/")) {
4102 file = data + STRING_SIZE("--- a/");
4103 break;
4107 if (diff == line || !file) {
4108 report("Failed to read the file name");
4109 return REQ_NONE;
4112 chunk_data = chunk->data;
4114 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4115 report("Failed to read the line number");
4116 return REQ_NONE;
4119 if (lineno == 0) {
4120 report("This is the origin of the line");
4121 return REQ_NONE;
4124 for (chunk += 1; chunk < line; chunk++) {
4125 if (chunk->type == LINE_DIFF_ADD) {
4126 lineno += chunk_marker == '+';
4127 } else if (chunk->type == LINE_DIFF_DEL) {
4128 lineno += chunk_marker == '-';
4129 } else {
4130 lineno++;
4134 if (chunk_marker == '+')
4135 string_copy(ref, view->vid);
4136 else
4137 string_format(ref, "%s^", view->vid);
4139 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4140 report("Failed to read blame data");
4141 return REQ_NONE;
4144 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4145 string_copy(opt_ref, header.id);
4146 opt_goto_line = header.orig_lineno - 1;
4148 return REQ_VIEW_BLAME;
4151 static enum request
4152 diff_request(struct view *view, enum request request, struct line *line)
4154 switch (request) {
4155 case REQ_VIEW_BLAME:
4156 return diff_trace_origin(view, line);
4158 case REQ_DIFF_CONTEXT_UP:
4159 case REQ_DIFF_CONTEXT_DOWN:
4160 if (!update_diff_context(request))
4161 return REQ_NONE;
4162 reload_view(view);
4163 return REQ_NONE;
4166 case REQ_ENTER:
4167 return diff_common_enter(view, request, line);
4169 default:
4170 return pager_request(view, request, line);
4174 static void
4175 diff_select(struct view *view, struct line *line)
4177 if (line->type == LINE_DIFF_STAT) {
4178 const char *key = get_view_key(view, REQ_ENTER);
4180 string_format(view->ref, "Press '%s' to jump to file diff", key);
4181 } else {
4182 string_ncopy(view->ref, view->id, strlen(view->id));
4183 return pager_select(view, line);
4187 static struct view_ops diff_ops = {
4188 "line",
4189 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4190 sizeof(struct diff_state),
4191 diff_open,
4192 diff_read,
4193 diff_common_draw,
4194 diff_request,
4195 pager_grep,
4196 diff_select,
4200 * Help backend
4203 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4205 static bool
4206 help_open_keymap_title(struct view *view, enum keymap keymap)
4208 struct line *line;
4210 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4211 help_keymap_hidden[keymap] ? '+' : '-',
4212 enum_name(keymap_map[keymap]));
4213 if (line)
4214 line->other = keymap;
4216 return help_keymap_hidden[keymap];
4219 static void
4220 help_open_keymap(struct view *view, enum keymap keymap)
4222 const char *group = NULL;
4223 char buf[SIZEOF_STR];
4224 size_t bufpos;
4225 bool add_title = TRUE;
4226 int i;
4228 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4229 const char *key = NULL;
4231 if (req_info[i].request == REQ_NONE)
4232 continue;
4234 if (!req_info[i].request) {
4235 group = req_info[i].help;
4236 continue;
4239 key = get_keys(keymap, req_info[i].request, TRUE);
4240 if (!key || !*key)
4241 continue;
4243 if (add_title && help_open_keymap_title(view, keymap))
4244 return;
4245 add_title = FALSE;
4247 if (group) {
4248 add_line_text(view, group, LINE_HELP_GROUP);
4249 group = NULL;
4252 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4253 enum_name(req_info[i]), req_info[i].help);
4256 group = "External commands:";
4258 for (i = 0; i < run_requests; i++) {
4259 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4260 const char *key;
4261 int argc;
4263 if (!req || req->keymap != keymap)
4264 continue;
4266 key = get_key_name(req->key);
4267 if (!*key)
4268 key = "(no key defined)";
4270 if (add_title && help_open_keymap_title(view, keymap))
4271 return;
4272 add_title = FALSE;
4274 if (group) {
4275 add_line_text(view, group, LINE_HELP_GROUP);
4276 group = NULL;
4279 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4280 if (!string_format_from(buf, &bufpos, "%s%s",
4281 argc ? " " : "", req->argv[argc]))
4282 return;
4284 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4288 static bool
4289 help_open(struct view *view, enum open_flags flags)
4291 enum keymap keymap;
4293 reset_view(view);
4294 view->p_restore = TRUE;
4295 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4296 add_line_text(view, "", LINE_DEFAULT);
4298 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4299 help_open_keymap(view, keymap);
4301 return TRUE;
4304 static enum request
4305 help_request(struct view *view, enum request request, struct line *line)
4307 switch (request) {
4308 case REQ_ENTER:
4309 if (line->type == LINE_HELP_KEYMAP) {
4310 help_keymap_hidden[line->other] =
4311 !help_keymap_hidden[line->other];
4312 refresh_view(view);
4315 return REQ_NONE;
4316 default:
4317 return pager_request(view, request, line);
4321 static struct view_ops help_ops = {
4322 "line",
4323 VIEW_NO_GIT_DIR,
4325 help_open,
4326 NULL,
4327 pager_draw,
4328 help_request,
4329 pager_grep,
4330 pager_select,
4335 * Tree backend
4338 struct tree_stack_entry {
4339 struct tree_stack_entry *prev; /* Entry below this in the stack */
4340 unsigned long lineno; /* Line number to restore */
4341 char *name; /* Position of name in opt_path */
4344 /* The top of the path stack. */
4345 static struct tree_stack_entry *tree_stack = NULL;
4346 unsigned long tree_lineno = 0;
4348 static void
4349 pop_tree_stack_entry(void)
4351 struct tree_stack_entry *entry = tree_stack;
4353 tree_lineno = entry->lineno;
4354 entry->name[0] = 0;
4355 tree_stack = entry->prev;
4356 free(entry);
4359 static void
4360 push_tree_stack_entry(const char *name, unsigned long lineno)
4362 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4363 size_t pathlen = strlen(opt_path);
4365 if (!entry)
4366 return;
4368 entry->prev = tree_stack;
4369 entry->name = opt_path + pathlen;
4370 tree_stack = entry;
4372 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4373 pop_tree_stack_entry();
4374 return;
4377 /* Move the current line to the first tree entry. */
4378 tree_lineno = 1;
4379 entry->lineno = lineno;
4382 /* Parse output from git-ls-tree(1):
4384 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4387 #define SIZEOF_TREE_ATTR \
4388 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4390 #define SIZEOF_TREE_MODE \
4391 STRING_SIZE("100644 ")
4393 #define TREE_ID_OFFSET \
4394 STRING_SIZE("100644 blob ")
4396 struct tree_entry {
4397 char id[SIZEOF_REV];
4398 mode_t mode;
4399 struct time time; /* Date from the author ident. */
4400 const char *author; /* Author of the commit. */
4401 char name[1];
4404 struct tree_state {
4405 const char *author_name;
4406 struct time author_time;
4407 bool read_date;
4410 static const char *
4411 tree_path(const struct line *line)
4413 return ((struct tree_entry *) line->data)->name;
4416 static int
4417 tree_compare_entry(const struct line *line1, const struct line *line2)
4419 if (line1->type != line2->type)
4420 return line1->type == LINE_TREE_DIR ? -1 : 1;
4421 return strcmp(tree_path(line1), tree_path(line2));
4424 static const enum sort_field tree_sort_fields[] = {
4425 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4427 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4429 static int
4430 tree_compare(const void *l1, const void *l2)
4432 const struct line *line1 = (const struct line *) l1;
4433 const struct line *line2 = (const struct line *) l2;
4434 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4435 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4437 if (line1->type == LINE_TREE_HEAD)
4438 return -1;
4439 if (line2->type == LINE_TREE_HEAD)
4440 return 1;
4442 switch (get_sort_field(tree_sort_state)) {
4443 case ORDERBY_DATE:
4444 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4446 case ORDERBY_AUTHOR:
4447 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4449 case ORDERBY_NAME:
4450 default:
4451 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4456 static struct line *
4457 tree_entry(struct view *view, enum line_type type, const char *path,
4458 const char *mode, const char *id)
4460 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4461 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4463 if (!entry || !line) {
4464 free(entry);
4465 return NULL;
4468 strncpy(entry->name, path, strlen(path));
4469 if (mode)
4470 entry->mode = strtoul(mode, NULL, 8);
4471 if (id)
4472 string_copy_rev(entry->id, id);
4474 return line;
4477 static bool
4478 tree_read_date(struct view *view, char *text, struct tree_state *state)
4480 if (!text && state->read_date) {
4481 state->read_date = FALSE;
4482 return TRUE;
4484 } else if (!text) {
4485 /* Find next entry to process */
4486 const char *log_file[] = {
4487 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4488 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4491 if (!view->lines) {
4492 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4493 report("Tree is empty");
4494 return TRUE;
4497 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4498 report("Failed to load tree data");
4499 return TRUE;
4502 state->read_date = TRUE;
4503 return FALSE;
4505 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4506 parse_author_line(text + STRING_SIZE("author "),
4507 &state->author_name, &state->author_time);
4509 } else if (*text == ':') {
4510 char *pos;
4511 size_t annotated = 1;
4512 size_t i;
4514 pos = strchr(text, '\t');
4515 if (!pos)
4516 return TRUE;
4517 text = pos + 1;
4518 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4519 text += strlen(opt_path);
4520 pos = strchr(text, '/');
4521 if (pos)
4522 *pos = 0;
4524 for (i = 1; i < view->lines; i++) {
4525 struct line *line = &view->line[i];
4526 struct tree_entry *entry = line->data;
4528 annotated += !!entry->author;
4529 if (entry->author || strcmp(entry->name, text))
4530 continue;
4532 entry->author = state->author_name;
4533 entry->time = state->author_time;
4534 line->dirty = 1;
4535 break;
4538 if (annotated == view->lines)
4539 io_kill(view->pipe);
4541 return TRUE;
4544 static bool
4545 tree_read(struct view *view, char *text)
4547 struct tree_state *state = view->private;
4548 struct tree_entry *data;
4549 struct line *entry, *line;
4550 enum line_type type;
4551 size_t textlen = text ? strlen(text) : 0;
4552 char *path = text + SIZEOF_TREE_ATTR;
4554 if (state->read_date || !text)
4555 return tree_read_date(view, text, state);
4557 if (textlen <= SIZEOF_TREE_ATTR)
4558 return FALSE;
4559 if (view->lines == 0 &&
4560 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4561 return FALSE;
4563 /* Strip the path part ... */
4564 if (*opt_path) {
4565 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4566 size_t striplen = strlen(opt_path);
4568 if (pathlen > striplen)
4569 memmove(path, path + striplen,
4570 pathlen - striplen + 1);
4572 /* Insert "link" to parent directory. */
4573 if (view->lines == 1 &&
4574 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4575 return FALSE;
4578 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4579 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4580 if (!entry)
4581 return FALSE;
4582 data = entry->data;
4584 /* Skip "Directory ..." and ".." line. */
4585 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4586 if (tree_compare_entry(line, entry) <= 0)
4587 continue;
4589 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4591 line->data = data;
4592 line->type = type;
4593 for (; line <= entry; line++)
4594 line->dirty = line->cleareol = 1;
4595 return TRUE;
4598 if (tree_lineno > view->lineno) {
4599 view->lineno = tree_lineno;
4600 tree_lineno = 0;
4603 return TRUE;
4606 static bool
4607 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4609 struct tree_entry *entry = line->data;
4611 if (line->type == LINE_TREE_HEAD) {
4612 if (draw_text(view, line->type, "Directory path /"))
4613 return TRUE;
4614 } else {
4615 if (draw_mode(view, entry->mode))
4616 return TRUE;
4618 if (draw_author(view, entry->author))
4619 return TRUE;
4621 if (draw_date(view, &entry->time))
4622 return TRUE;
4625 draw_text(view, line->type, entry->name);
4626 return TRUE;
4629 static void
4630 open_blob_editor(const char *id)
4632 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4633 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4634 int fd = mkstemp(file);
4636 if (fd == -1)
4637 report("Failed to create temporary file");
4638 else if (!io_run_append(blob_argv, fd))
4639 report("Failed to save blob data to file");
4640 else
4641 open_editor(file);
4642 if (fd != -1)
4643 unlink(file);
4646 static enum request
4647 tree_request(struct view *view, enum request request, struct line *line)
4649 enum open_flags flags;
4650 struct tree_entry *entry = line->data;
4652 switch (request) {
4653 case REQ_VIEW_BLAME:
4654 if (line->type != LINE_TREE_FILE) {
4655 report("Blame only supported for files");
4656 return REQ_NONE;
4659 string_copy(opt_ref, view->vid);
4660 return request;
4662 case REQ_EDIT:
4663 if (line->type != LINE_TREE_FILE) {
4664 report("Edit only supported for files");
4665 } else if (!is_head_commit(view->vid)) {
4666 open_blob_editor(entry->id);
4667 } else {
4668 open_editor(opt_file);
4670 return REQ_NONE;
4672 case REQ_TOGGLE_SORT_FIELD:
4673 case REQ_TOGGLE_SORT_ORDER:
4674 sort_view(view, request, &tree_sort_state, tree_compare);
4675 return REQ_NONE;
4677 case REQ_PARENT:
4678 if (!*opt_path) {
4679 /* quit view if at top of tree */
4680 return REQ_VIEW_CLOSE;
4682 /* fake 'cd ..' */
4683 line = &view->line[1];
4684 break;
4686 case REQ_ENTER:
4687 break;
4689 default:
4690 return request;
4693 /* Cleanup the stack if the tree view is at a different tree. */
4694 while (!*opt_path && tree_stack)
4695 pop_tree_stack_entry();
4697 switch (line->type) {
4698 case LINE_TREE_DIR:
4699 /* Depending on whether it is a subdirectory or parent link
4700 * mangle the path buffer. */
4701 if (line == &view->line[1] && *opt_path) {
4702 pop_tree_stack_entry();
4704 } else {
4705 const char *basename = tree_path(line);
4707 push_tree_stack_entry(basename, view->lineno);
4710 /* Trees and subtrees share the same ID, so they are not not
4711 * unique like blobs. */
4712 flags = OPEN_RELOAD;
4713 request = REQ_VIEW_TREE;
4714 break;
4716 case LINE_TREE_FILE:
4717 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4718 request = REQ_VIEW_BLOB;
4719 break;
4721 default:
4722 return REQ_NONE;
4725 open_view(view, request, flags);
4726 if (request == REQ_VIEW_TREE)
4727 view->lineno = tree_lineno;
4729 return REQ_NONE;
4732 static bool
4733 tree_grep(struct view *view, struct line *line)
4735 struct tree_entry *entry = line->data;
4736 const char *text[] = {
4737 entry->name,
4738 mkauthor(entry->author, opt_author_cols, opt_author),
4739 mkdate(&entry->time, opt_date),
4740 NULL
4743 return grep_text(view, text);
4746 static void
4747 tree_select(struct view *view, struct line *line)
4749 struct tree_entry *entry = line->data;
4751 if (line->type == LINE_TREE_FILE) {
4752 string_copy_rev(ref_blob, entry->id);
4753 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4755 } else if (line->type != LINE_TREE_DIR) {
4756 return;
4759 string_copy_rev(view->ref, entry->id);
4762 static bool
4763 tree_open(struct view *view, enum open_flags flags)
4765 static const char *tree_argv[] = {
4766 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4769 if (view->lines == 0 && opt_prefix[0]) {
4770 char *pos = opt_prefix;
4772 while (pos && *pos) {
4773 char *end = strchr(pos, '/');
4775 if (end)
4776 *end = 0;
4777 push_tree_stack_entry(pos, 0);
4778 pos = end;
4779 if (end) {
4780 *end = '/';
4781 pos++;
4785 } else if (strcmp(view->vid, view->id)) {
4786 opt_path[0] = 0;
4789 return begin_update(view, opt_cdup, tree_argv, flags);
4792 static struct view_ops tree_ops = {
4793 "file",
4794 VIEW_NO_FLAGS,
4795 sizeof(struct tree_state),
4796 tree_open,
4797 tree_read,
4798 tree_draw,
4799 tree_request,
4800 tree_grep,
4801 tree_select,
4804 static bool
4805 blob_open(struct view *view, enum open_flags flags)
4807 static const char *blob_argv[] = {
4808 "git", "cat-file", "blob", "%(blob)", NULL
4811 view->encoding = get_path_encoding(opt_file, opt_encoding);
4813 return begin_update(view, NULL, blob_argv, flags);
4816 static bool
4817 blob_read(struct view *view, char *line)
4819 if (!line)
4820 return TRUE;
4821 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4824 static enum request
4825 blob_request(struct view *view, enum request request, struct line *line)
4827 switch (request) {
4828 case REQ_EDIT:
4829 open_blob_editor(view->vid);
4830 return REQ_NONE;
4831 default:
4832 return pager_request(view, request, line);
4836 static struct view_ops blob_ops = {
4837 "line",
4838 VIEW_NO_FLAGS,
4840 blob_open,
4841 blob_read,
4842 pager_draw,
4843 blob_request,
4844 pager_grep,
4845 pager_select,
4849 * Blame backend
4851 * Loading the blame view is a two phase job:
4853 * 1. File content is read either using opt_file from the
4854 * filesystem or using git-cat-file.
4855 * 2. Then blame information is incrementally added by
4856 * reading output from git-blame.
4859 struct blame {
4860 struct blame_commit *commit;
4861 unsigned long lineno;
4862 char text[1];
4865 struct blame_state {
4866 struct blame_commit *commit;
4867 int blamed;
4868 bool done_reading;
4869 bool auto_filename_display;
4872 static bool
4873 blame_detect_filename_display(struct view *view)
4875 bool show_filenames = FALSE;
4876 const char *filename = NULL;
4877 int i;
4879 if (opt_blame_argv) {
4880 for (i = 0; opt_blame_argv[i]; i++) {
4881 if (prefixcmp(opt_blame_argv[i], "-C"))
4882 continue;
4884 show_filenames = TRUE;
4888 for (i = 0; i < view->lines; i++) {
4889 struct blame *blame = view->line[i].data;
4891 if (blame->commit && blame->commit->id[0]) {
4892 if (!filename)
4893 filename = blame->commit->filename;
4894 else if (strcmp(filename, blame->commit->filename))
4895 show_filenames = TRUE;
4899 return show_filenames;
4902 static bool
4903 blame_open(struct view *view, enum open_flags flags)
4905 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4906 char path[SIZEOF_STR];
4907 size_t i;
4909 if (!view->prev && *opt_prefix) {
4910 string_copy(path, opt_file);
4911 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4912 return FALSE;
4915 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4916 const char *blame_cat_file_argv[] = {
4917 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4920 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4921 return FALSE;
4924 /* First pass: remove multiple references to the same commit. */
4925 for (i = 0; i < view->lines; i++) {
4926 struct blame *blame = view->line[i].data;
4928 if (blame->commit && blame->commit->id[0])
4929 blame->commit->id[0] = 0;
4930 else
4931 blame->commit = NULL;
4934 /* Second pass: free existing references. */
4935 for (i = 0; i < view->lines; i++) {
4936 struct blame *blame = view->line[i].data;
4938 if (blame->commit)
4939 free(blame->commit);
4942 string_format(view->vid, "%s", opt_file);
4943 string_format(view->ref, "%s ...", opt_file);
4945 return TRUE;
4948 static struct blame_commit *
4949 get_blame_commit(struct view *view, const char *id)
4951 size_t i;
4953 for (i = 0; i < view->lines; i++) {
4954 struct blame *blame = view->line[i].data;
4956 if (!blame->commit)
4957 continue;
4959 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4960 return blame->commit;
4964 struct blame_commit *commit = calloc(1, sizeof(*commit));
4966 if (commit)
4967 string_ncopy(commit->id, id, SIZEOF_REV);
4968 return commit;
4972 static struct blame_commit *
4973 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4975 struct blame_header header;
4976 struct blame_commit *commit;
4977 struct blame *blame;
4979 if (!parse_blame_header(&header, text, view->lines))
4980 return NULL;
4982 commit = get_blame_commit(view, text);
4983 if (!commit)
4984 return NULL;
4986 state->blamed += header.group;
4987 while (header.group--) {
4988 struct line *line = &view->line[header.lineno + header.group - 1];
4990 blame = line->data;
4991 blame->commit = commit;
4992 blame->lineno = header.orig_lineno + header.group - 1;
4993 line->dirty = 1;
4996 return commit;
4999 static bool
5000 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5002 if (!line) {
5003 const char *blame_argv[] = {
5004 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5005 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5008 if (view->lines == 0 && !view->prev)
5009 die("No blame exist for %s", view->vid);
5011 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5012 report("Failed to load blame data");
5013 return TRUE;
5016 if (opt_goto_line > 0) {
5017 select_view_line(view, opt_goto_line);
5018 opt_goto_line = 0;
5021 state->done_reading = TRUE;
5022 return FALSE;
5024 } else {
5025 size_t linelen = strlen(line);
5026 struct blame *blame = malloc(sizeof(*blame) + linelen);
5028 if (!blame)
5029 return FALSE;
5031 blame->commit = NULL;
5032 strncpy(blame->text, line, linelen);
5033 blame->text[linelen] = 0;
5034 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5038 static bool
5039 blame_read(struct view *view, char *line)
5041 struct blame_state *state = view->private;
5043 if (!state->done_reading)
5044 return blame_read_file(view, line, state);
5046 if (!line) {
5047 state->auto_filename_display = blame_detect_filename_display(view);
5048 string_format(view->ref, "%s", view->vid);
5049 if (view_is_displayed(view)) {
5050 update_view_title(view);
5051 redraw_view_from(view, 0);
5053 return TRUE;
5056 if (!state->commit) {
5057 state->commit = read_blame_commit(view, line, state);
5058 string_format(view->ref, "%s %2d%%", view->vid,
5059 view->lines ? state->blamed * 100 / view->lines : 0);
5061 } else if (parse_blame_info(state->commit, line)) {
5062 state->commit = NULL;
5065 return TRUE;
5068 static bool
5069 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5071 struct blame_state *state = view->private;
5072 struct blame *blame = line->data;
5073 struct time *time = NULL;
5074 const char *id = NULL, *author = NULL, *filename = NULL;
5075 enum line_type id_type = LINE_BLAME_ID;
5076 static const enum line_type blame_colors[] = {
5077 LINE_PALETTE_0,
5078 LINE_PALETTE_1,
5079 LINE_PALETTE_2,
5080 LINE_PALETTE_3,
5081 LINE_PALETTE_4,
5082 LINE_PALETTE_5,
5083 LINE_PALETTE_6,
5086 #define BLAME_COLOR(i) \
5087 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5089 if (blame->commit && *blame->commit->filename) {
5090 id = blame->commit->id;
5091 author = blame->commit->author;
5092 filename = blame->commit->filename;
5093 time = &blame->commit->time;
5094 id_type = BLAME_COLOR((long) blame->commit);
5097 if (draw_date(view, time))
5098 return TRUE;
5100 if (draw_author(view, author))
5101 return TRUE;
5103 if (draw_filename(view, filename, state->auto_filename_display))
5104 return TRUE;
5106 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5107 return TRUE;
5109 if (draw_lineno(view, lineno))
5110 return TRUE;
5112 draw_text(view, LINE_DEFAULT, blame->text);
5113 return TRUE;
5116 static bool
5117 check_blame_commit(struct blame *blame, bool check_null_id)
5119 if (!blame->commit)
5120 report("Commit data not loaded yet");
5121 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5122 report("No commit exist for the selected line");
5123 else
5124 return TRUE;
5125 return FALSE;
5128 static void
5129 setup_blame_parent_line(struct view *view, struct blame *blame)
5131 char from[SIZEOF_REF + SIZEOF_STR];
5132 char to[SIZEOF_REF + SIZEOF_STR];
5133 const char *diff_tree_argv[] = {
5134 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5135 "--no-color", "-U0", from, to, "--", NULL
5137 struct io io;
5138 int parent_lineno = -1;
5139 int blamed_lineno = -1;
5140 char *line;
5142 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5143 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5144 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5145 return;
5147 while ((line = io_get(&io, '\n', TRUE))) {
5148 if (*line == '@') {
5149 char *pos = strchr(line, '+');
5151 parent_lineno = atoi(line + 4);
5152 if (pos)
5153 blamed_lineno = atoi(pos + 1);
5155 } else if (*line == '+' && parent_lineno != -1) {
5156 if (blame->lineno == blamed_lineno - 1 &&
5157 !strcmp(blame->text, line + 1)) {
5158 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5159 break;
5161 blamed_lineno++;
5165 io_done(&io);
5168 static enum request
5169 blame_request(struct view *view, enum request request, struct line *line)
5171 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5172 struct blame *blame = line->data;
5174 switch (request) {
5175 case REQ_VIEW_BLAME:
5176 if (check_blame_commit(blame, TRUE)) {
5177 string_copy(opt_ref, blame->commit->id);
5178 string_copy(opt_file, blame->commit->filename);
5179 if (blame->lineno)
5180 view->lineno = blame->lineno;
5181 reload_view(view);
5183 break;
5185 case REQ_PARENT:
5186 if (!check_blame_commit(blame, TRUE))
5187 break;
5188 if (!*blame->commit->parent_id) {
5189 report("The selected commit has no parents");
5190 } else {
5191 string_copy_rev(opt_ref, blame->commit->parent_id);
5192 string_copy(opt_file, blame->commit->parent_filename);
5193 setup_blame_parent_line(view, blame);
5194 opt_goto_line = blame->lineno;
5195 reload_view(view);
5197 break;
5199 case REQ_ENTER:
5200 if (!check_blame_commit(blame, FALSE))
5201 break;
5203 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5204 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5205 break;
5207 if (!strcmp(blame->commit->id, NULL_ID)) {
5208 struct view *diff = VIEW(REQ_VIEW_DIFF);
5209 const char *diff_parent_argv[] = {
5210 GIT_DIFF_BLAME(opt_diff_context_arg,
5211 opt_ignore_space_arg, view->vid)
5213 const char *diff_no_parent_argv[] = {
5214 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5215 opt_ignore_space_arg, view->vid)
5217 const char **diff_index_argv = *blame->commit->parent_id
5218 ? diff_parent_argv : diff_no_parent_argv;
5220 open_argv(view, diff, diff_index_argv, NULL, flags);
5221 if (diff->pipe)
5222 string_copy_rev(diff->ref, NULL_ID);
5223 } else {
5224 open_view(view, REQ_VIEW_DIFF, flags);
5226 break;
5228 default:
5229 return request;
5232 return REQ_NONE;
5235 static bool
5236 blame_grep(struct view *view, struct line *line)
5238 struct blame *blame = line->data;
5239 struct blame_commit *commit = blame->commit;
5240 const char *text[] = {
5241 blame->text,
5242 commit ? commit->title : "",
5243 commit ? commit->id : "",
5244 commit && opt_author ? commit->author : "",
5245 commit ? mkdate(&commit->time, opt_date) : "",
5246 NULL
5249 return grep_text(view, text);
5252 static void
5253 blame_select(struct view *view, struct line *line)
5255 struct blame *blame = line->data;
5256 struct blame_commit *commit = blame->commit;
5258 if (!commit)
5259 return;
5261 if (!strcmp(commit->id, NULL_ID))
5262 string_ncopy(ref_commit, "HEAD", 4);
5263 else
5264 string_copy_rev(ref_commit, commit->id);
5267 static struct view_ops blame_ops = {
5268 "line",
5269 VIEW_ALWAYS_LINENO,
5270 sizeof(struct blame_state),
5271 blame_open,
5272 blame_read,
5273 blame_draw,
5274 blame_request,
5275 blame_grep,
5276 blame_select,
5280 * Branch backend
5283 struct branch {
5284 const char *author; /* Author of the last commit. */
5285 struct time time; /* Date of the last activity. */
5286 const struct ref *ref; /* Name and commit ID information. */
5289 static const struct ref branch_all;
5291 static const enum sort_field branch_sort_fields[] = {
5292 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5294 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5296 struct branch_state {
5297 char id[SIZEOF_REV];
5300 static int
5301 branch_compare(const void *l1, const void *l2)
5303 const struct branch *branch1 = ((const struct line *) l1)->data;
5304 const struct branch *branch2 = ((const struct line *) l2)->data;
5306 if (branch1->ref == &branch_all)
5307 return -1;
5308 else if (branch2->ref == &branch_all)
5309 return 1;
5311 switch (get_sort_field(branch_sort_state)) {
5312 case ORDERBY_DATE:
5313 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5315 case ORDERBY_AUTHOR:
5316 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5318 case ORDERBY_NAME:
5319 default:
5320 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5324 static bool
5325 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5327 struct branch *branch = line->data;
5328 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5330 if (draw_date(view, &branch->time))
5331 return TRUE;
5333 if (draw_author(view, branch->author))
5334 return TRUE;
5336 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5337 return TRUE;
5340 static enum request
5341 branch_request(struct view *view, enum request request, struct line *line)
5343 struct branch *branch = line->data;
5345 switch (request) {
5346 case REQ_REFRESH:
5347 load_refs();
5348 refresh_view(view);
5349 return REQ_NONE;
5351 case REQ_TOGGLE_SORT_FIELD:
5352 case REQ_TOGGLE_SORT_ORDER:
5353 sort_view(view, request, &branch_sort_state, branch_compare);
5354 return REQ_NONE;
5356 case REQ_ENTER:
5358 const struct ref *ref = branch->ref;
5359 const char *all_branches_argv[] = {
5360 "git", "log", ENCODING_ARG, "--no-color",
5361 "--pretty=raw", "--parents", "--topo-order",
5362 ref == &branch_all ? "--all" : ref->name, NULL
5364 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5366 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5367 return REQ_NONE;
5369 case REQ_JUMP_COMMIT:
5371 int lineno;
5373 for (lineno = 0; lineno < view->lines; lineno++) {
5374 struct branch *branch = view->line[lineno].data;
5376 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5377 select_view_line(view, lineno);
5378 report("");
5379 return REQ_NONE;
5383 default:
5384 return request;
5388 static bool
5389 branch_read(struct view *view, char *line)
5391 struct branch_state *state = view->private;
5392 struct branch *reference;
5393 size_t i;
5395 if (!line)
5396 return TRUE;
5398 switch (get_line_type(line)) {
5399 case LINE_COMMIT:
5400 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5401 return TRUE;
5403 case LINE_AUTHOR:
5404 for (i = 0, reference = NULL; i < view->lines; i++) {
5405 struct branch *branch = view->line[i].data;
5407 if (strcmp(branch->ref->id, state->id))
5408 continue;
5410 view->line[i].dirty = TRUE;
5411 if (reference) {
5412 branch->author = reference->author;
5413 branch->time = reference->time;
5414 continue;
5417 parse_author_line(line + STRING_SIZE("author "),
5418 &branch->author, &branch->time);
5419 reference = branch;
5421 return TRUE;
5423 default:
5424 return TRUE;
5429 static bool
5430 branch_open_visitor(void *data, const struct ref *ref)
5432 struct view *view = data;
5433 struct branch *branch;
5435 if (ref->tag || ref->ltag)
5436 return TRUE;
5438 branch = calloc(1, sizeof(*branch));
5439 if (!branch)
5440 return FALSE;
5442 branch->ref = ref;
5443 return !!add_line_data(view, branch, LINE_DEFAULT);
5446 static bool
5447 branch_open(struct view *view, enum open_flags flags)
5449 const char *branch_log[] = {
5450 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5451 "--simplify-by-decoration", "--all", NULL
5454 if (!begin_update(view, NULL, branch_log, flags)) {
5455 report("Failed to load branch data");
5456 return TRUE;
5459 branch_open_visitor(view, &branch_all);
5460 foreach_ref(branch_open_visitor, view);
5461 view->p_restore = TRUE;
5463 return TRUE;
5466 static bool
5467 branch_grep(struct view *view, struct line *line)
5469 struct branch *branch = line->data;
5470 const char *text[] = {
5471 branch->ref->name,
5472 mkauthor(branch->author, opt_author_cols, opt_author),
5473 NULL
5476 return grep_text(view, text);
5479 static void
5480 branch_select(struct view *view, struct line *line)
5482 struct branch *branch = line->data;
5484 string_copy_rev(view->ref, branch->ref->id);
5485 string_copy_rev(ref_commit, branch->ref->id);
5486 string_copy_rev(ref_head, branch->ref->id);
5487 string_copy_rev(ref_branch, branch->ref->name);
5490 static struct view_ops branch_ops = {
5491 "branch",
5492 VIEW_NO_FLAGS,
5493 sizeof(struct branch_state),
5494 branch_open,
5495 branch_read,
5496 branch_draw,
5497 branch_request,
5498 branch_grep,
5499 branch_select,
5503 * Status backend
5506 struct status {
5507 char status;
5508 struct {
5509 mode_t mode;
5510 char rev[SIZEOF_REV];
5511 char name[SIZEOF_STR];
5512 } old;
5513 struct {
5514 mode_t mode;
5515 char rev[SIZEOF_REV];
5516 char name[SIZEOF_STR];
5517 } new;
5520 static char status_onbranch[SIZEOF_STR];
5521 static struct status stage_status;
5522 static enum line_type stage_line_type;
5524 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5526 /* This should work even for the "On branch" line. */
5527 static inline bool
5528 status_has_none(struct view *view, struct line *line)
5530 return line < view->line + view->lines && !line[1].data;
5533 /* Get fields from the diff line:
5534 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5536 static inline bool
5537 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5539 const char *old_mode = buf + 1;
5540 const char *new_mode = buf + 8;
5541 const char *old_rev = buf + 15;
5542 const char *new_rev = buf + 56;
5543 const char *status = buf + 97;
5545 if (bufsize < 98 ||
5546 old_mode[-1] != ':' ||
5547 new_mode[-1] != ' ' ||
5548 old_rev[-1] != ' ' ||
5549 new_rev[-1] != ' ' ||
5550 status[-1] != ' ')
5551 return FALSE;
5553 file->status = *status;
5555 string_copy_rev(file->old.rev, old_rev);
5556 string_copy_rev(file->new.rev, new_rev);
5558 file->old.mode = strtoul(old_mode, NULL, 8);
5559 file->new.mode = strtoul(new_mode, NULL, 8);
5561 file->old.name[0] = file->new.name[0] = 0;
5563 return TRUE;
5566 static bool
5567 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5569 struct status *unmerged = NULL;
5570 char *buf;
5571 struct io io;
5573 if (!io_run(&io, IO_RD, opt_cdup, argv))
5574 return FALSE;
5576 add_line_data(view, NULL, type);
5578 while ((buf = io_get(&io, 0, TRUE))) {
5579 struct status *file = unmerged;
5581 if (!file) {
5582 file = calloc(1, sizeof(*file));
5583 if (!file || !add_line_data(view, file, type))
5584 goto error_out;
5587 /* Parse diff info part. */
5588 if (status) {
5589 file->status = status;
5590 if (status == 'A')
5591 string_copy(file->old.rev, NULL_ID);
5593 } else if (!file->status || file == unmerged) {
5594 if (!status_get_diff(file, buf, strlen(buf)))
5595 goto error_out;
5597 buf = io_get(&io, 0, TRUE);
5598 if (!buf)
5599 break;
5601 /* Collapse all modified entries that follow an
5602 * associated unmerged entry. */
5603 if (unmerged == file) {
5604 unmerged->status = 'U';
5605 unmerged = NULL;
5606 } else if (file->status == 'U') {
5607 unmerged = file;
5611 /* Grab the old name for rename/copy. */
5612 if (!*file->old.name &&
5613 (file->status == 'R' || file->status == 'C')) {
5614 string_ncopy(file->old.name, buf, strlen(buf));
5616 buf = io_get(&io, 0, TRUE);
5617 if (!buf)
5618 break;
5621 /* git-ls-files just delivers a NUL separated list of
5622 * file names similar to the second half of the
5623 * git-diff-* output. */
5624 string_ncopy(file->new.name, buf, strlen(buf));
5625 if (!*file->old.name)
5626 string_copy(file->old.name, file->new.name);
5627 file = NULL;
5630 if (io_error(&io)) {
5631 error_out:
5632 io_done(&io);
5633 return FALSE;
5636 if (!view->line[view->lines - 1].data)
5637 add_line_data(view, NULL, LINE_STAT_NONE);
5639 io_done(&io);
5640 return TRUE;
5643 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5644 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5646 static const char *status_list_other_argv[] = {
5647 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5650 static const char *status_list_no_head_argv[] = {
5651 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5654 static const char *update_index_argv[] = {
5655 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5658 /* Restore the previous line number to stay in the context or select a
5659 * line with something that can be updated. */
5660 static void
5661 status_restore(struct view *view)
5663 if (view->p_lineno >= view->lines)
5664 view->p_lineno = view->lines - 1;
5665 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5666 view->p_lineno++;
5667 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5668 view->p_lineno--;
5670 /* If the above fails, always skip the "On branch" line. */
5671 if (view->p_lineno < view->lines)
5672 view->lineno = view->p_lineno;
5673 else
5674 view->lineno = 1;
5676 if (view->lineno < view->offset)
5677 view->offset = view->lineno;
5678 else if (view->offset + view->height <= view->lineno)
5679 view->offset = view->lineno - view->height + 1;
5681 view->p_restore = FALSE;
5684 static void
5685 status_update_onbranch(void)
5687 static const char *paths[][2] = {
5688 { "rebase-apply/rebasing", "Rebasing" },
5689 { "rebase-apply/applying", "Applying mailbox" },
5690 { "rebase-apply/", "Rebasing mailbox" },
5691 { "rebase-merge/interactive", "Interactive rebase" },
5692 { "rebase-merge/", "Rebase merge" },
5693 { "MERGE_HEAD", "Merging" },
5694 { "BISECT_LOG", "Bisecting" },
5695 { "HEAD", "On branch" },
5697 char buf[SIZEOF_STR];
5698 struct stat stat;
5699 int i;
5701 if (is_initial_commit()) {
5702 string_copy(status_onbranch, "Initial commit");
5703 return;
5706 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5707 char *head = opt_head;
5709 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5710 lstat(buf, &stat) < 0)
5711 continue;
5713 if (!*opt_head) {
5714 struct io io;
5716 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5717 io_read_buf(&io, buf, sizeof(buf))) {
5718 head = buf;
5719 if (!prefixcmp(head, "refs/heads/"))
5720 head += STRING_SIZE("refs/heads/");
5724 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5725 string_copy(status_onbranch, opt_head);
5726 return;
5729 string_copy(status_onbranch, "Not currently on any branch");
5732 /* First parse staged info using git-diff-index(1), then parse unstaged
5733 * info using git-diff-files(1), and finally untracked files using
5734 * git-ls-files(1). */
5735 static bool
5736 status_open(struct view *view, enum open_flags flags)
5738 reset_view(view);
5740 add_line_data(view, NULL, LINE_STAT_HEAD);
5741 status_update_onbranch();
5743 io_run_bg(update_index_argv);
5745 if (is_initial_commit()) {
5746 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5747 return FALSE;
5748 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5749 return FALSE;
5752 if (!opt_untracked_dirs_content)
5753 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5755 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5756 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5757 return FALSE;
5759 /* Restore the exact position or use the specialized restore
5760 * mode? */
5761 if (!view->p_restore)
5762 status_restore(view);
5763 return TRUE;
5766 static bool
5767 status_draw(struct view *view, struct line *line, unsigned int lineno)
5769 struct status *status = line->data;
5770 enum line_type type;
5771 const char *text;
5773 if (!status) {
5774 switch (line->type) {
5775 case LINE_STAT_STAGED:
5776 type = LINE_STAT_SECTION;
5777 text = "Changes to be committed:";
5778 break;
5780 case LINE_STAT_UNSTAGED:
5781 type = LINE_STAT_SECTION;
5782 text = "Changed but not updated:";
5783 break;
5785 case LINE_STAT_UNTRACKED:
5786 type = LINE_STAT_SECTION;
5787 text = "Untracked files:";
5788 break;
5790 case LINE_STAT_NONE:
5791 type = LINE_DEFAULT;
5792 text = " (no files)";
5793 break;
5795 case LINE_STAT_HEAD:
5796 type = LINE_STAT_HEAD;
5797 text = status_onbranch;
5798 break;
5800 default:
5801 return FALSE;
5803 } else {
5804 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5806 buf[0] = status->status;
5807 if (draw_text(view, line->type, buf))
5808 return TRUE;
5809 type = LINE_DEFAULT;
5810 text = status->new.name;
5813 draw_text(view, type, text);
5814 return TRUE;
5817 static enum request
5818 status_enter(struct view *view, struct line *line)
5820 struct status *status = line->data;
5821 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5823 if (line->type == LINE_STAT_NONE ||
5824 (!status && line[1].type == LINE_STAT_NONE)) {
5825 report("No file to diff");
5826 return REQ_NONE;
5829 switch (line->type) {
5830 case LINE_STAT_STAGED:
5831 case LINE_STAT_UNSTAGED:
5832 break;
5834 case LINE_STAT_UNTRACKED:
5835 if (!status) {
5836 report("No file to show");
5837 return REQ_NONE;
5840 if (!suffixcmp(status->new.name, -1, "/")) {
5841 report("Cannot display a directory");
5842 return REQ_NONE;
5844 break;
5846 case LINE_STAT_HEAD:
5847 return REQ_NONE;
5849 default:
5850 die("line type %d not handled in switch", line->type);
5853 if (status) {
5854 stage_status = *status;
5855 } else {
5856 memset(&stage_status, 0, sizeof(stage_status));
5859 stage_line_type = line->type;
5861 open_view(view, REQ_VIEW_STAGE, flags);
5862 return REQ_NONE;
5865 static bool
5866 status_exists(struct view *view, struct status *status, enum line_type type)
5868 unsigned long lineno;
5870 for (lineno = 0; lineno < view->lines; lineno++) {
5871 struct line *line = &view->line[lineno];
5872 struct status *pos = line->data;
5874 if (line->type != type)
5875 continue;
5876 if (!pos && (!status || !status->status) && line[1].data) {
5877 select_view_line(view, lineno);
5878 return TRUE;
5880 if (pos && !strcmp(status->new.name, pos->new.name)) {
5881 select_view_line(view, lineno);
5882 return TRUE;
5886 return FALSE;
5890 static bool
5891 status_update_prepare(struct io *io, enum line_type type)
5893 const char *staged_argv[] = {
5894 "git", "update-index", "-z", "--index-info", NULL
5896 const char *others_argv[] = {
5897 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5900 switch (type) {
5901 case LINE_STAT_STAGED:
5902 return io_run(io, IO_WR, opt_cdup, staged_argv);
5904 case LINE_STAT_UNSTAGED:
5905 case LINE_STAT_UNTRACKED:
5906 return io_run(io, IO_WR, opt_cdup, others_argv);
5908 default:
5909 die("line type %d not handled in switch", type);
5910 return FALSE;
5914 static bool
5915 status_update_write(struct io *io, struct status *status, enum line_type type)
5917 switch (type) {
5918 case LINE_STAT_STAGED:
5919 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5920 status->old.rev, status->old.name, 0);
5922 case LINE_STAT_UNSTAGED:
5923 case LINE_STAT_UNTRACKED:
5924 return io_printf(io, "%s%c", status->new.name, 0);
5926 default:
5927 die("line type %d not handled in switch", type);
5928 return FALSE;
5932 static bool
5933 status_update_file(struct status *status, enum line_type type)
5935 struct io io;
5936 bool result;
5938 if (!status_update_prepare(&io, type))
5939 return FALSE;
5941 result = status_update_write(&io, status, type);
5942 return io_done(&io) && result;
5945 static bool
5946 status_update_files(struct view *view, struct line *line)
5948 char buf[sizeof(view->ref)];
5949 struct io io;
5950 bool result = TRUE;
5951 struct line *pos = view->line + view->lines;
5952 int files = 0;
5953 int file, done;
5954 int cursor_y = -1, cursor_x = -1;
5956 if (!status_update_prepare(&io, line->type))
5957 return FALSE;
5959 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5960 files++;
5962 string_copy(buf, view->ref);
5963 getsyx(cursor_y, cursor_x);
5964 for (file = 0, done = 5; result && file < files; line++, file++) {
5965 int almost_done = file * 100 / files;
5967 if (almost_done > done) {
5968 done = almost_done;
5969 string_format(view->ref, "updating file %u of %u (%d%% done)",
5970 file, files, done);
5971 update_view_title(view);
5972 setsyx(cursor_y, cursor_x);
5973 doupdate();
5975 result = status_update_write(&io, line->data, line->type);
5977 string_copy(view->ref, buf);
5979 return io_done(&io) && result;
5982 static bool
5983 status_update(struct view *view)
5985 struct line *line = &view->line[view->lineno];
5987 assert(view->lines);
5989 if (!line->data) {
5990 /* This should work even for the "On branch" line. */
5991 if (line < view->line + view->lines && !line[1].data) {
5992 report("Nothing to update");
5993 return FALSE;
5996 if (!status_update_files(view, line + 1)) {
5997 report("Failed to update file status");
5998 return FALSE;
6001 } else if (!status_update_file(line->data, line->type)) {
6002 report("Failed to update file status");
6003 return FALSE;
6006 return TRUE;
6009 static bool
6010 status_revert(struct status *status, enum line_type type, bool has_none)
6012 if (!status || type != LINE_STAT_UNSTAGED) {
6013 if (type == LINE_STAT_STAGED) {
6014 report("Cannot revert changes to staged files");
6015 } else if (type == LINE_STAT_UNTRACKED) {
6016 report("Cannot revert changes to untracked files");
6017 } else if (has_none) {
6018 report("Nothing to revert");
6019 } else {
6020 report("Cannot revert changes to multiple files");
6023 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6024 char mode[10] = "100644";
6025 const char *reset_argv[] = {
6026 "git", "update-index", "--cacheinfo", mode,
6027 status->old.rev, status->old.name, NULL
6029 const char *checkout_argv[] = {
6030 "git", "checkout", "--", status->old.name, NULL
6033 if (status->status == 'U') {
6034 string_format(mode, "%5o", status->old.mode);
6036 if (status->old.mode == 0 && status->new.mode == 0) {
6037 reset_argv[2] = "--force-remove";
6038 reset_argv[3] = status->old.name;
6039 reset_argv[4] = NULL;
6042 if (!io_run_fg(reset_argv, opt_cdup))
6043 return FALSE;
6044 if (status->old.mode == 0 && status->new.mode == 0)
6045 return TRUE;
6048 return io_run_fg(checkout_argv, opt_cdup);
6051 return FALSE;
6054 static enum request
6055 status_request(struct view *view, enum request request, struct line *line)
6057 struct status *status = line->data;
6059 switch (request) {
6060 case REQ_STATUS_UPDATE:
6061 if (!status_update(view))
6062 return REQ_NONE;
6063 break;
6065 case REQ_STATUS_REVERT:
6066 if (!status_revert(status, line->type, status_has_none(view, line)))
6067 return REQ_NONE;
6068 break;
6070 case REQ_STATUS_MERGE:
6071 if (!status || status->status != 'U') {
6072 report("Merging only possible for files with unmerged status ('U').");
6073 return REQ_NONE;
6075 open_mergetool(status->new.name);
6076 break;
6078 case REQ_EDIT:
6079 if (!status)
6080 return request;
6081 if (status->status == 'D') {
6082 report("File has been deleted.");
6083 return REQ_NONE;
6086 open_editor(status->new.name);
6087 break;
6089 case REQ_VIEW_BLAME:
6090 if (status)
6091 opt_ref[0] = 0;
6092 return request;
6094 case REQ_ENTER:
6095 /* After returning the status view has been split to
6096 * show the stage view. No further reloading is
6097 * necessary. */
6098 return status_enter(view, line);
6100 case REQ_REFRESH:
6101 /* Simply reload the view. */
6102 break;
6104 default:
6105 return request;
6108 refresh_view(view);
6110 return REQ_NONE;
6113 static void
6114 status_select(struct view *view, struct line *line)
6116 struct status *status = line->data;
6117 char file[SIZEOF_STR] = "all files";
6118 const char *text;
6119 const char *key;
6121 if (status && !string_format(file, "'%s'", status->new.name))
6122 return;
6124 if (!status && line[1].type == LINE_STAT_NONE)
6125 line++;
6127 switch (line->type) {
6128 case LINE_STAT_STAGED:
6129 text = "Press %s to unstage %s for commit";
6130 break;
6132 case LINE_STAT_UNSTAGED:
6133 text = "Press %s to stage %s for commit";
6134 break;
6136 case LINE_STAT_UNTRACKED:
6137 text = "Press %s to stage %s for addition";
6138 break;
6140 case LINE_STAT_HEAD:
6141 case LINE_STAT_NONE:
6142 text = "Nothing to update";
6143 break;
6145 default:
6146 die("line type %d not handled in switch", line->type);
6149 if (status && status->status == 'U') {
6150 text = "Press %s to resolve conflict in %s";
6151 key = get_view_key(view, REQ_STATUS_MERGE);
6153 } else {
6154 key = get_view_key(view, REQ_STATUS_UPDATE);
6157 string_format(view->ref, text, key, file);
6158 if (status)
6159 string_copy(opt_file, status->new.name);
6162 static bool
6163 status_grep(struct view *view, struct line *line)
6165 struct status *status = line->data;
6167 if (status) {
6168 const char buf[2] = { status->status, 0 };
6169 const char *text[] = { status->new.name, buf, NULL };
6171 return grep_text(view, text);
6174 return FALSE;
6177 static struct view_ops status_ops = {
6178 "file",
6179 VIEW_CUSTOM_STATUS,
6181 status_open,
6182 NULL,
6183 status_draw,
6184 status_request,
6185 status_grep,
6186 status_select,
6190 struct stage_state {
6191 struct diff_state diff;
6192 size_t chunks;
6193 int *chunk;
6196 static bool
6197 stage_diff_write(struct io *io, struct line *line, struct line *end)
6199 while (line < end) {
6200 if (!io_write(io, line->data, strlen(line->data)) ||
6201 !io_write(io, "\n", 1))
6202 return FALSE;
6203 line++;
6204 if (line->type == LINE_DIFF_CHUNK ||
6205 line->type == LINE_DIFF_HEADER)
6206 break;
6209 return TRUE;
6212 static bool
6213 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6215 const char *apply_argv[SIZEOF_ARG] = {
6216 "git", "apply", "--whitespace=nowarn", NULL
6218 struct line *diff_hdr;
6219 struct io io;
6220 int argc = 3;
6222 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6223 if (!diff_hdr)
6224 return FALSE;
6226 if (!revert)
6227 apply_argv[argc++] = "--cached";
6228 if (line != NULL)
6229 apply_argv[argc++] = "--unidiff-zero";
6230 if (revert || stage_line_type == LINE_STAT_STAGED)
6231 apply_argv[argc++] = "-R";
6232 apply_argv[argc++] = "-";
6233 apply_argv[argc++] = NULL;
6234 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6235 return FALSE;
6237 if (line != NULL) {
6238 int lineno = 0;
6239 struct line *context = chunk + 1;
6240 const char *markers[] = {
6241 line->type == LINE_DIFF_DEL ? "" : ",0",
6242 line->type == LINE_DIFF_DEL ? ",0" : "",
6245 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6247 while (context < line) {
6248 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6249 break;
6250 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6251 lineno++;
6253 context++;
6256 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6257 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6258 lineno, markers[0], lineno, markers[1]) ||
6259 !stage_diff_write(&io, line, line + 1)) {
6260 chunk = NULL;
6262 } else {
6263 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6264 !stage_diff_write(&io, chunk, view->line + view->lines))
6265 chunk = NULL;
6268 io_done(&io);
6269 io_run_bg(update_index_argv);
6271 return chunk ? TRUE : FALSE;
6274 static bool
6275 stage_update(struct view *view, struct line *line, bool single)
6277 struct line *chunk = NULL;
6279 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6280 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6282 if (chunk) {
6283 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6284 report("Failed to apply chunk");
6285 return FALSE;
6288 } else if (!stage_status.status) {
6289 view = view->parent;
6291 for (line = view->line; line < view->line + view->lines; line++)
6292 if (line->type == stage_line_type)
6293 break;
6295 if (!status_update_files(view, line + 1)) {
6296 report("Failed to update files");
6297 return FALSE;
6300 } else if (!status_update_file(&stage_status, stage_line_type)) {
6301 report("Failed to update file");
6302 return FALSE;
6305 return TRUE;
6308 static bool
6309 stage_revert(struct view *view, struct line *line)
6311 struct line *chunk = NULL;
6313 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6314 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6316 if (chunk) {
6317 if (!prompt_yesno("Are you sure you want to revert changes?"))
6318 return FALSE;
6320 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6321 report("Failed to revert chunk");
6322 return FALSE;
6324 return TRUE;
6326 } else {
6327 return status_revert(stage_status.status ? &stage_status : NULL,
6328 stage_line_type, FALSE);
6333 static void
6334 stage_next(struct view *view, struct line *line)
6336 struct stage_state *state = view->private;
6337 int i;
6339 if (!state->chunks) {
6340 for (line = view->line; line < view->line + view->lines; line++) {
6341 if (line->type != LINE_DIFF_CHUNK)
6342 continue;
6344 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6345 report("Allocation failure");
6346 return;
6349 state->chunk[state->chunks++] = line - view->line;
6353 for (i = 0; i < state->chunks; i++) {
6354 if (state->chunk[i] > view->lineno) {
6355 do_scroll_view(view, state->chunk[i] - view->lineno);
6356 report("Chunk %d of %d", i + 1, state->chunks);
6357 return;
6361 report("No next chunk found");
6364 static enum request
6365 stage_request(struct view *view, enum request request, struct line *line)
6367 switch (request) {
6368 case REQ_STATUS_UPDATE:
6369 if (!stage_update(view, line, FALSE))
6370 return REQ_NONE;
6371 break;
6373 case REQ_STATUS_REVERT:
6374 if (!stage_revert(view, line))
6375 return REQ_NONE;
6376 break;
6378 case REQ_STAGE_UPDATE_LINE:
6379 if (stage_line_type == LINE_STAT_UNTRACKED ||
6380 stage_status.status == 'A') {
6381 report("Staging single lines is not supported for new files");
6382 return REQ_NONE;
6384 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6385 report("Please select a change to stage");
6386 return REQ_NONE;
6388 if (!stage_update(view, line, TRUE))
6389 return REQ_NONE;
6390 break;
6392 case REQ_STAGE_NEXT:
6393 if (stage_line_type == LINE_STAT_UNTRACKED) {
6394 report("File is untracked; press %s to add",
6395 get_view_key(view, REQ_STATUS_UPDATE));
6396 return REQ_NONE;
6398 stage_next(view, line);
6399 return REQ_NONE;
6401 case REQ_EDIT:
6402 if (!stage_status.new.name[0])
6403 return request;
6404 if (stage_status.status == 'D') {
6405 report("File has been deleted.");
6406 return REQ_NONE;
6409 open_editor(stage_status.new.name);
6410 break;
6412 case REQ_REFRESH:
6413 /* Reload everything ... */
6414 break;
6416 case REQ_VIEW_BLAME:
6417 if (stage_status.new.name[0]) {
6418 string_copy(opt_file, stage_status.new.name);
6419 opt_ref[0] = 0;
6421 return request;
6423 case REQ_ENTER:
6424 return diff_common_enter(view, request, line);
6426 case REQ_DIFF_CONTEXT_UP:
6427 case REQ_DIFF_CONTEXT_DOWN:
6428 if (!update_diff_context(request))
6429 return REQ_NONE;
6430 break;
6432 default:
6433 return request;
6436 refresh_view(view->parent);
6438 /* Check whether the staged entry still exists, and close the
6439 * stage view if it doesn't. */
6440 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6441 status_restore(view->parent);
6442 return REQ_VIEW_CLOSE;
6445 refresh_view(view);
6447 return REQ_NONE;
6450 static bool
6451 stage_open(struct view *view, enum open_flags flags)
6453 static const char *no_head_diff_argv[] = {
6454 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6455 stage_status.new.name)
6457 static const char *index_show_argv[] = {
6458 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6459 stage_status.old.name, stage_status.new.name)
6461 static const char *files_show_argv[] = {
6462 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6463 stage_status.old.name, stage_status.new.name)
6465 /* Diffs for unmerged entries are empty when passing the new
6466 * path, so leave out the new path. */
6467 static const char *files_unmerged_argv[] = {
6468 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6469 opt_diff_context_arg, opt_ignore_space_arg, "--",
6470 stage_status.old.name, NULL
6472 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6473 const char **argv = NULL;
6474 const char *info;
6476 view->encoding = NULL;
6478 switch (stage_line_type) {
6479 case LINE_STAT_STAGED:
6480 if (is_initial_commit()) {
6481 argv = no_head_diff_argv;
6482 } else {
6483 argv = index_show_argv;
6485 if (stage_status.status)
6486 info = "Staged changes to %s";
6487 else
6488 info = "Staged changes";
6489 break;
6491 case LINE_STAT_UNSTAGED:
6492 if (stage_status.status != 'U')
6493 argv = files_show_argv;
6494 else
6495 argv = files_unmerged_argv;
6496 if (stage_status.status)
6497 info = "Unstaged changes to %s";
6498 else
6499 info = "Unstaged changes";
6500 break;
6502 case LINE_STAT_UNTRACKED:
6503 info = "Untracked file %s";
6504 argv = file_argv;
6505 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6506 break;
6508 case LINE_STAT_HEAD:
6509 default:
6510 die("line type %d not handled in switch", stage_line_type);
6513 string_format(view->ref, info, stage_status.new.name);
6514 view->vid[0] = 0;
6515 view->dir = opt_cdup;
6516 return argv_copy(&view->argv, argv)
6517 && begin_update(view, NULL, NULL, flags);
6520 static bool
6521 stage_read(struct view *view, char *data)
6523 struct stage_state *state = view->private;
6525 if (data && diff_common_read(view, data, &state->diff))
6526 return TRUE;
6528 return pager_read(view, data);
6531 static struct view_ops stage_ops = {
6532 "line",
6533 VIEW_DIFF_LIKE,
6534 sizeof(struct stage_state),
6535 stage_open,
6536 stage_read,
6537 diff_common_draw,
6538 stage_request,
6539 pager_grep,
6540 pager_select,
6545 * Revision graph
6548 static const enum line_type graph_colors[] = {
6549 LINE_PALETTE_0,
6550 LINE_PALETTE_1,
6551 LINE_PALETTE_2,
6552 LINE_PALETTE_3,
6553 LINE_PALETTE_4,
6554 LINE_PALETTE_5,
6555 LINE_PALETTE_6,
6558 static enum line_type get_graph_color(struct graph_symbol *symbol)
6560 if (symbol->commit)
6561 return LINE_GRAPH_COMMIT;
6562 assert(symbol->color < ARRAY_SIZE(graph_colors));
6563 return graph_colors[symbol->color];
6566 static bool
6567 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6569 const char *chars = graph_symbol_to_utf8(symbol);
6571 return draw_text(view, color, chars + !!first);
6574 static bool
6575 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6577 const char *chars = graph_symbol_to_ascii(symbol);
6579 return draw_text(view, color, chars + !!first);
6582 static bool
6583 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6585 const chtype *chars = graph_symbol_to_chtype(symbol);
6587 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6590 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6592 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6594 static const draw_graph_fn fns[] = {
6595 draw_graph_ascii,
6596 draw_graph_chtype,
6597 draw_graph_utf8
6599 draw_graph_fn fn = fns[opt_line_graphics];
6600 int i;
6602 for (i = 0; i < canvas->size; i++) {
6603 struct graph_symbol *symbol = &canvas->symbols[i];
6604 enum line_type color = get_graph_color(symbol);
6606 if (fn(view, symbol, color, i == 0))
6607 return TRUE;
6610 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6614 * Main view backend
6617 struct commit {
6618 char id[SIZEOF_REV]; /* SHA1 ID. */
6619 char title[128]; /* First line of the commit message. */
6620 const char *author; /* Author of the commit. */
6621 struct time time; /* Date from the author ident. */
6622 struct ref_list *refs; /* Repository references. */
6623 struct graph_canvas graph; /* Ancestry chain graphics. */
6626 static struct commit *
6627 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6629 struct graph *graph = view->private;
6630 struct commit *commit;
6632 commit = calloc(1, sizeof(struct commit));
6633 if (!commit)
6634 return NULL;
6636 string_copy_rev(commit->id, ids);
6637 commit->refs = get_ref_list(commit->id);
6638 add_line_data(view, commit, type);
6639 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6640 return commit;
6643 bool
6644 main_has_changes(const char *argv[])
6646 struct io io;
6648 if (!io_run(&io, IO_BG, NULL, argv, -1))
6649 return FALSE;
6650 io_done(&io);
6651 return io.status == 1;
6654 static void
6655 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6657 char ids[SIZEOF_STR] = NULL_ID " ";
6658 struct graph *graph = view->private;
6659 struct commit *commit;
6660 struct timeval now;
6661 struct timezone tz;
6663 if (!parent)
6664 return;
6666 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6668 commit = main_add_commit(view, type, ids, FALSE);
6669 if (!commit)
6670 return;
6672 if (!gettimeofday(&now, &tz)) {
6673 commit->time.tz = tz.tz_minuteswest * 60;
6674 commit->time.sec = now.tv_sec - commit->time.tz;
6677 commit->author = "";
6678 string_ncopy(commit->title, title, strlen(title));
6679 graph_render_parents(graph);
6682 static void
6683 main_add_changes_commits(struct view *view, const char *parent)
6685 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6686 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6687 const char *staged_parent = NULL_ID;
6688 const char *unstaged_parent = parent;
6690 if (!main_has_changes(unstaged_argv)) {
6691 unstaged_parent = NULL;
6692 staged_parent = parent;
6695 if (!main_has_changes(staged_argv)) {
6696 staged_parent = NULL;
6699 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6700 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6703 static bool
6704 main_open(struct view *view, enum open_flags flags)
6706 static const char *main_argv[] = {
6707 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6708 "--topo-order", "%(diffargs)", "%(revargs)",
6709 "--", "%(fileargs)", NULL
6712 return begin_update(view, NULL, main_argv, flags);
6715 static bool
6716 main_draw(struct view *view, struct line *line, unsigned int lineno)
6718 struct commit *commit = line->data;
6720 if (!commit->author)
6721 return FALSE;
6723 if (draw_lineno(view, lineno))
6724 return TRUE;
6726 if (draw_date(view, &commit->time))
6727 return TRUE;
6729 if (draw_author(view, commit->author))
6730 return TRUE;
6732 if (opt_rev_graph && draw_graph(view, &commit->graph))
6733 return TRUE;
6735 if (draw_refs(view, commit->refs))
6736 return TRUE;
6738 draw_text(view, LINE_DEFAULT, commit->title);
6739 return TRUE;
6742 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6743 static bool
6744 main_read(struct view *view, char *line)
6746 struct graph *graph = view->private;
6747 enum line_type type;
6748 struct commit *commit;
6749 static bool in_header;
6751 if (!line) {
6752 if (!view->lines && !view->prev)
6753 die("No revisions match the given arguments.");
6754 if (view->lines > 0) {
6755 commit = view->line[view->lines - 1].data;
6756 view->line[view->lines - 1].dirty = 1;
6757 if (!commit->author) {
6758 view->lines--;
6759 free(commit);
6763 done_graph(graph);
6764 return TRUE;
6767 type = get_line_type(line);
6768 if (type == LINE_COMMIT) {
6769 bool is_boundary;
6771 in_header = TRUE;
6772 line += STRING_SIZE("commit ");
6773 is_boundary = *line == '-';
6774 if (is_boundary)
6775 line++;
6777 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6778 main_add_changes_commits(view, line);
6780 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6783 if (!view->lines)
6784 return TRUE;
6785 commit = view->line[view->lines - 1].data;
6787 /* Empty line separates the commit header from the log itself. */
6788 if (*line == '\0')
6789 in_header = FALSE;
6791 switch (type) {
6792 case LINE_PARENT:
6793 if (!graph->has_parents)
6794 graph_add_parent(graph, line + STRING_SIZE("parent "));
6795 break;
6797 case LINE_AUTHOR:
6798 parse_author_line(line + STRING_SIZE("author "),
6799 &commit->author, &commit->time);
6800 graph_render_parents(graph);
6801 break;
6803 default:
6804 /* Fill in the commit title if it has not already been set. */
6805 if (commit->title[0])
6806 break;
6808 /* Skip lines in the commit header. */
6809 if (in_header)
6810 break;
6812 /* Require titles to start with a non-space character at the
6813 * offset used by git log. */
6814 if (strncmp(line, " ", 4))
6815 break;
6816 line += 4;
6817 /* Well, if the title starts with a whitespace character,
6818 * try to be forgiving. Otherwise we end up with no title. */
6819 while (isspace(*line))
6820 line++;
6821 if (*line == '\0')
6822 break;
6823 /* FIXME: More graceful handling of titles; append "..." to
6824 * shortened titles, etc. */
6826 string_expand(commit->title, sizeof(commit->title), line, 1);
6827 view->line[view->lines - 1].dirty = 1;
6830 return TRUE;
6833 static enum request
6834 main_request(struct view *view, enum request request, struct line *line)
6836 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6838 switch (request) {
6839 case REQ_ENTER:
6840 if (view_is_displayed(view) && display[0] != view)
6841 maximize_view(view, TRUE);
6843 if (line->type == LINE_STAT_UNSTAGED
6844 || line->type == LINE_STAT_STAGED) {
6845 struct view *diff = VIEW(REQ_VIEW_DIFF);
6846 const char *diff_staged_argv[] = {
6847 GIT_DIFF_STAGED(opt_diff_context_arg,
6848 opt_ignore_space_arg, NULL, NULL)
6850 const char *diff_unstaged_argv[] = {
6851 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6852 opt_ignore_space_arg, NULL, NULL)
6854 const char **diff_argv = line->type == LINE_STAT_STAGED
6855 ? diff_staged_argv : diff_unstaged_argv;
6857 open_argv(view, diff, diff_argv, NULL, flags);
6858 break;
6861 open_view(view, REQ_VIEW_DIFF, flags);
6862 break;
6863 case REQ_REFRESH:
6864 load_refs();
6865 refresh_view(view);
6866 break;
6868 case REQ_JUMP_COMMIT:
6870 int lineno;
6872 for (lineno = 0; lineno < view->lines; lineno++) {
6873 struct commit *commit = view->line[lineno].data;
6875 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6876 select_view_line(view, lineno);
6877 report("");
6878 return REQ_NONE;
6882 report("Unable to find commit '%s'", opt_search);
6883 break;
6885 default:
6886 return request;
6889 return REQ_NONE;
6892 static bool
6893 grep_refs(struct ref_list *list, regex_t *regex)
6895 regmatch_t pmatch;
6896 size_t i;
6898 if (!opt_show_refs || !list)
6899 return FALSE;
6901 for (i = 0; i < list->size; i++) {
6902 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6903 return TRUE;
6906 return FALSE;
6909 static bool
6910 main_grep(struct view *view, struct line *line)
6912 struct commit *commit = line->data;
6913 const char *text[] = {
6914 commit->title,
6915 mkauthor(commit->author, opt_author_cols, opt_author),
6916 mkdate(&commit->time, opt_date),
6917 NULL
6920 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6923 static void
6924 main_select(struct view *view, struct line *line)
6926 struct commit *commit = line->data;
6928 string_copy_rev(view->ref, commit->id);
6929 string_copy_rev(ref_commit, view->ref);
6932 static struct view_ops main_ops = {
6933 "commit",
6934 VIEW_NO_FLAGS,
6935 sizeof(struct graph),
6936 main_open,
6937 main_read,
6938 main_draw,
6939 main_request,
6940 main_grep,
6941 main_select,
6946 * Status management
6949 /* Whether or not the curses interface has been initialized. */
6950 static bool cursed = FALSE;
6952 /* Terminal hacks and workarounds. */
6953 static bool use_scroll_redrawwin;
6954 static bool use_scroll_status_wclear;
6956 /* The status window is used for polling keystrokes. */
6957 static WINDOW *status_win;
6959 /* Reading from the prompt? */
6960 static bool input_mode = FALSE;
6962 static bool status_empty = FALSE;
6964 /* Update status and title window. */
6965 static void
6966 report(const char *msg, ...)
6968 struct view *view = display[current_view];
6970 if (input_mode)
6971 return;
6973 if (!view) {
6974 char buf[SIZEOF_STR];
6975 int retval;
6977 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6978 die("%s", buf);
6981 if (!status_empty || *msg) {
6982 va_list args;
6984 va_start(args, msg);
6986 wmove(status_win, 0, 0);
6987 if (view->has_scrolled && use_scroll_status_wclear)
6988 wclear(status_win);
6989 if (*msg) {
6990 vwprintw(status_win, msg, args);
6991 status_empty = FALSE;
6992 } else {
6993 status_empty = TRUE;
6995 wclrtoeol(status_win);
6996 wnoutrefresh(status_win);
6998 va_end(args);
7001 update_view_title(view);
7004 static void
7005 init_display(void)
7007 const char *term;
7008 int x, y;
7010 /* Initialize the curses library */
7011 if (isatty(STDIN_FILENO)) {
7012 cursed = !!initscr();
7013 opt_tty = stdin;
7014 } else {
7015 /* Leave stdin and stdout alone when acting as a pager. */
7016 opt_tty = fopen("/dev/tty", "r+");
7017 if (!opt_tty)
7018 die("Failed to open /dev/tty");
7019 cursed = !!newterm(NULL, opt_tty, opt_tty);
7022 if (!cursed)
7023 die("Failed to initialize curses");
7025 nonl(); /* Disable conversion and detect newlines from input. */
7026 cbreak(); /* Take input chars one at a time, no wait for \n */
7027 noecho(); /* Don't echo input */
7028 leaveok(stdscr, FALSE);
7030 if (has_colors())
7031 init_colors();
7033 getmaxyx(stdscr, y, x);
7034 status_win = newwin(1, x, y - 1, 0);
7035 if (!status_win)
7036 die("Failed to create status window");
7038 /* Enable keyboard mapping */
7039 keypad(status_win, TRUE);
7040 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7042 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7043 set_tabsize(opt_tab_size);
7044 #else
7045 TABSIZE = opt_tab_size;
7046 #endif
7048 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7049 if (term && !strcmp(term, "gnome-terminal")) {
7050 /* In the gnome-terminal-emulator, the message from
7051 * scrolling up one line when impossible followed by
7052 * scrolling down one line causes corruption of the
7053 * status line. This is fixed by calling wclear. */
7054 use_scroll_status_wclear = TRUE;
7055 use_scroll_redrawwin = FALSE;
7057 } else if (term && !strcmp(term, "xrvt-xpm")) {
7058 /* No problems with full optimizations in xrvt-(unicode)
7059 * and aterm. */
7060 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7062 } else {
7063 /* When scrolling in (u)xterm the last line in the
7064 * scrolling direction will update slowly. */
7065 use_scroll_redrawwin = TRUE;
7066 use_scroll_status_wclear = FALSE;
7070 static int
7071 get_input(int prompt_position)
7073 struct view *view;
7074 int i, key, cursor_y, cursor_x;
7076 if (prompt_position)
7077 input_mode = TRUE;
7079 while (TRUE) {
7080 bool loading = FALSE;
7082 foreach_view (view, i) {
7083 update_view(view);
7084 if (view_is_displayed(view) && view->has_scrolled &&
7085 use_scroll_redrawwin)
7086 redrawwin(view->win);
7087 view->has_scrolled = FALSE;
7088 if (view->pipe)
7089 loading = TRUE;
7092 /* Update the cursor position. */
7093 if (prompt_position) {
7094 getbegyx(status_win, cursor_y, cursor_x);
7095 cursor_x = prompt_position;
7096 } else {
7097 view = display[current_view];
7098 getbegyx(view->win, cursor_y, cursor_x);
7099 cursor_x = view->width - 1;
7100 cursor_y += view->lineno - view->offset;
7102 setsyx(cursor_y, cursor_x);
7104 /* Refresh, accept single keystroke of input */
7105 doupdate();
7106 nodelay(status_win, loading);
7107 key = wgetch(status_win);
7109 /* wgetch() with nodelay() enabled returns ERR when
7110 * there's no input. */
7111 if (key == ERR) {
7113 } else if (key == KEY_RESIZE) {
7114 int height, width;
7116 getmaxyx(stdscr, height, width);
7118 wresize(status_win, 1, width);
7119 mvwin(status_win, height - 1, 0);
7120 wnoutrefresh(status_win);
7121 resize_display();
7122 redraw_display(TRUE);
7124 } else {
7125 input_mode = FALSE;
7126 if (key == erasechar())
7127 key = KEY_BACKSPACE;
7128 return key;
7133 static char *
7134 prompt_input(const char *prompt, input_handler handler, void *data)
7136 enum input_status status = INPUT_OK;
7137 static char buf[SIZEOF_STR];
7138 size_t pos = 0;
7140 buf[pos] = 0;
7142 while (status == INPUT_OK || status == INPUT_SKIP) {
7143 int key;
7145 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7146 wclrtoeol(status_win);
7148 key = get_input(pos + 1);
7149 switch (key) {
7150 case KEY_RETURN:
7151 case KEY_ENTER:
7152 case '\n':
7153 status = pos ? INPUT_STOP : INPUT_CANCEL;
7154 break;
7156 case KEY_BACKSPACE:
7157 if (pos > 0)
7158 buf[--pos] = 0;
7159 else
7160 status = INPUT_CANCEL;
7161 break;
7163 case KEY_ESC:
7164 status = INPUT_CANCEL;
7165 break;
7167 default:
7168 if (pos >= sizeof(buf)) {
7169 report("Input string too long");
7170 return NULL;
7173 status = handler(data, buf, key);
7174 if (status == INPUT_OK)
7175 buf[pos++] = (char) key;
7179 /* Clear the status window */
7180 status_empty = FALSE;
7181 report("");
7183 if (status == INPUT_CANCEL)
7184 return NULL;
7186 buf[pos++] = 0;
7188 return buf;
7191 static enum input_status
7192 prompt_yesno_handler(void *data, char *buf, int c)
7194 if (c == 'y' || c == 'Y')
7195 return INPUT_STOP;
7196 if (c == 'n' || c == 'N')
7197 return INPUT_CANCEL;
7198 return INPUT_SKIP;
7201 static bool
7202 prompt_yesno(const char *prompt)
7204 char prompt2[SIZEOF_STR];
7206 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7207 return FALSE;
7209 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7212 static enum input_status
7213 read_prompt_handler(void *data, char *buf, int c)
7215 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7218 static char *
7219 read_prompt(const char *prompt)
7221 return prompt_input(prompt, read_prompt_handler, NULL);
7224 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7226 enum input_status status = INPUT_OK;
7227 int size = 0;
7229 while (items[size].text)
7230 size++;
7232 while (status == INPUT_OK) {
7233 const struct menu_item *item = &items[*selected];
7234 int key;
7235 int i;
7237 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7238 prompt, *selected + 1, size);
7239 if (item->hotkey)
7240 wprintw(status_win, "[%c] ", (char) item->hotkey);
7241 wprintw(status_win, "%s", item->text);
7242 wclrtoeol(status_win);
7244 key = get_input(COLS - 1);
7245 switch (key) {
7246 case KEY_RETURN:
7247 case KEY_ENTER:
7248 case '\n':
7249 status = INPUT_STOP;
7250 break;
7252 case KEY_LEFT:
7253 case KEY_UP:
7254 *selected = *selected - 1;
7255 if (*selected < 0)
7256 *selected = size - 1;
7257 break;
7259 case KEY_RIGHT:
7260 case KEY_DOWN:
7261 *selected = (*selected + 1) % size;
7262 break;
7264 case KEY_ESC:
7265 status = INPUT_CANCEL;
7266 break;
7268 default:
7269 for (i = 0; items[i].text; i++)
7270 if (items[i].hotkey == key) {
7271 *selected = i;
7272 status = INPUT_STOP;
7273 break;
7278 /* Clear the status window */
7279 status_empty = FALSE;
7280 report("");
7282 return status != INPUT_CANCEL;
7286 * Repository properties
7289 static struct ref **refs = NULL;
7290 static size_t refs_size = 0;
7291 static struct ref *refs_head = NULL;
7293 static struct ref_list **ref_lists = NULL;
7294 static size_t ref_lists_size = 0;
7296 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7297 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7298 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7300 static int
7301 compare_refs(const void *ref1_, const void *ref2_)
7303 const struct ref *ref1 = *(const struct ref **)ref1_;
7304 const struct ref *ref2 = *(const struct ref **)ref2_;
7306 if (ref1->tag != ref2->tag)
7307 return ref2->tag - ref1->tag;
7308 if (ref1->ltag != ref2->ltag)
7309 return ref2->ltag - ref1->ltag;
7310 if (ref1->head != ref2->head)
7311 return ref2->head - ref1->head;
7312 if (ref1->tracked != ref2->tracked)
7313 return ref2->tracked - ref1->tracked;
7314 if (ref1->replace != ref2->replace)
7315 return ref2->replace - ref1->replace;
7316 /* Order remotes last. */
7317 if (ref1->remote != ref2->remote)
7318 return ref1->remote - ref2->remote;
7319 return strcmp(ref1->name, ref2->name);
7322 static void
7323 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7325 size_t i;
7327 for (i = 0; i < refs_size; i++)
7328 if (!visitor(data, refs[i]))
7329 break;
7332 static struct ref *
7333 get_ref_head()
7335 return refs_head;
7338 static struct ref_list *
7339 get_ref_list(const char *id)
7341 struct ref_list *list;
7342 size_t i;
7344 for (i = 0; i < ref_lists_size; i++)
7345 if (!strcmp(id, ref_lists[i]->id))
7346 return ref_lists[i];
7348 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7349 return NULL;
7350 list = calloc(1, sizeof(*list));
7351 if (!list)
7352 return NULL;
7354 for (i = 0; i < refs_size; i++) {
7355 if (!strcmp(id, refs[i]->id) &&
7356 realloc_refs_list(&list->refs, list->size, 1))
7357 list->refs[list->size++] = refs[i];
7360 if (!list->refs) {
7361 free(list);
7362 return NULL;
7365 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7366 ref_lists[ref_lists_size++] = list;
7367 return list;
7370 static int
7371 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7373 struct ref *ref = NULL;
7374 bool tag = FALSE;
7375 bool ltag = FALSE;
7376 bool remote = FALSE;
7377 bool replace = FALSE;
7378 bool tracked = FALSE;
7379 bool head = FALSE;
7380 int from = 0, to = refs_size - 1;
7382 if (!prefixcmp(name, "refs/tags/")) {
7383 if (!suffixcmp(name, namelen, "^{}")) {
7384 namelen -= 3;
7385 name[namelen] = 0;
7386 } else {
7387 ltag = TRUE;
7390 tag = TRUE;
7391 namelen -= STRING_SIZE("refs/tags/");
7392 name += STRING_SIZE("refs/tags/");
7394 } else if (!prefixcmp(name, "refs/remotes/")) {
7395 remote = TRUE;
7396 namelen -= STRING_SIZE("refs/remotes/");
7397 name += STRING_SIZE("refs/remotes/");
7398 tracked = !strcmp(opt_remote, name);
7400 } else if (!prefixcmp(name, "refs/replace/")) {
7401 replace = TRUE;
7402 id = name + strlen("refs/replace/");
7403 idlen = namelen - strlen("refs/replace/");
7404 name = "replaced";
7405 namelen = strlen(name);
7407 } else if (!prefixcmp(name, "refs/heads/")) {
7408 namelen -= STRING_SIZE("refs/heads/");
7409 name += STRING_SIZE("refs/heads/");
7410 if (strlen(opt_head) == namelen
7411 && !strncmp(opt_head, name, namelen))
7412 return OK;
7414 } else if (!strcmp(name, "HEAD")) {
7415 head = TRUE;
7416 if (*opt_head) {
7417 namelen = strlen(opt_head);
7418 name = opt_head;
7422 /* If we are reloading or it's an annotated tag, replace the
7423 * previous SHA1 with the resolved commit id; relies on the fact
7424 * git-ls-remote lists the commit id of an annotated tag right
7425 * before the commit id it points to. */
7426 while ((from <= to) && !replace) {
7427 size_t pos = (to + from) / 2;
7428 int cmp = strcmp(name, refs[pos]->name);
7430 if (!cmp) {
7431 ref = refs[pos];
7432 break;
7435 if (cmp < 0)
7436 to = pos - 1;
7437 else
7438 from = pos + 1;
7441 if (!ref) {
7442 if (!realloc_refs(&refs, refs_size, 1))
7443 return ERR;
7444 ref = calloc(1, sizeof(*ref) + namelen);
7445 if (!ref)
7446 return ERR;
7447 memmove(refs + from + 1, refs + from,
7448 (refs_size - from) * sizeof(*refs));
7449 refs[from] = ref;
7450 strncpy(ref->name, name, namelen);
7451 refs_size++;
7454 ref->head = head;
7455 ref->tag = tag;
7456 ref->ltag = ltag;
7457 ref->remote = remote;
7458 ref->replace = replace;
7459 ref->tracked = tracked;
7460 string_copy_rev(ref->id, id);
7462 if (head)
7463 refs_head = ref;
7464 return OK;
7467 static int
7468 load_refs(void)
7470 const char *head_argv[] = {
7471 "git", "symbolic-ref", "HEAD", NULL
7473 static const char *ls_remote_argv[SIZEOF_ARG] = {
7474 "git", "ls-remote", opt_git_dir, NULL
7476 static bool init = FALSE;
7477 size_t i;
7479 if (!init) {
7480 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7481 die("TIG_LS_REMOTE contains too many arguments");
7482 init = TRUE;
7485 if (!*opt_git_dir)
7486 return OK;
7488 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7489 !prefixcmp(opt_head, "refs/heads/")) {
7490 char *offset = opt_head + STRING_SIZE("refs/heads/");
7492 memmove(opt_head, offset, strlen(offset) + 1);
7495 refs_head = NULL;
7496 for (i = 0; i < refs_size; i++)
7497 refs[i]->id[0] = 0;
7499 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7500 return ERR;
7502 /* Update the ref lists to reflect changes. */
7503 for (i = 0; i < ref_lists_size; i++) {
7504 struct ref_list *list = ref_lists[i];
7505 size_t old, new;
7507 for (old = new = 0; old < list->size; old++)
7508 if (!strcmp(list->id, list->refs[old]->id))
7509 list->refs[new++] = list->refs[old];
7510 list->size = new;
7513 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7515 return OK;
7518 static void
7519 set_remote_branch(const char *name, const char *value, size_t valuelen)
7521 if (!strcmp(name, ".remote")) {
7522 string_ncopy(opt_remote, value, valuelen);
7524 } else if (*opt_remote && !strcmp(name, ".merge")) {
7525 size_t from = strlen(opt_remote);
7527 if (!prefixcmp(value, "refs/heads/"))
7528 value += STRING_SIZE("refs/heads/");
7530 if (!string_format_from(opt_remote, &from, "/%s", value))
7531 opt_remote[0] = 0;
7535 static void
7536 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7538 const char *argv[SIZEOF_ARG] = { name, "=" };
7539 int argc = 1 + (cmd == option_set_command);
7540 enum option_code error;
7542 if (!argv_from_string(argv, &argc, value))
7543 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7544 else
7545 error = cmd(argc, argv);
7547 if (error != OPT_OK)
7548 warn("Option 'tig.%s': %s", name, option_errors[error]);
7551 static bool
7552 set_environment_variable(const char *name, const char *value)
7554 size_t len = strlen(name) + 1 + strlen(value) + 1;
7555 char *env = malloc(len);
7557 if (env &&
7558 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7559 putenv(env) == 0)
7560 return TRUE;
7561 free(env);
7562 return FALSE;
7565 static void
7566 set_work_tree(const char *value)
7568 char cwd[SIZEOF_STR];
7570 if (!getcwd(cwd, sizeof(cwd)))
7571 die("Failed to get cwd path: %s", strerror(errno));
7572 if (chdir(opt_git_dir) < 0)
7573 die("Failed to chdir(%s): %s", strerror(errno));
7574 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7575 die("Failed to get git path: %s", strerror(errno));
7576 if (chdir(cwd) < 0)
7577 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7578 if (chdir(value) < 0)
7579 die("Failed to chdir(%s): %s", value, strerror(errno));
7580 if (!getcwd(cwd, sizeof(cwd)))
7581 die("Failed to get cwd path: %s", strerror(errno));
7582 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7583 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7584 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7585 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7586 opt_is_inside_work_tree = TRUE;
7589 static void
7590 parse_git_color_option(enum line_type type, char *value)
7592 struct line_info *info = &line_info[type];
7593 const char *argv[SIZEOF_ARG];
7594 int argc = 0;
7595 bool first_color = TRUE;
7596 int i;
7598 if (!argv_from_string(argv, &argc, value))
7599 return;
7601 info->fg = COLOR_DEFAULT;
7602 info->bg = COLOR_DEFAULT;
7603 info->attr = 0;
7605 for (i = 0; i < argc; i++) {
7606 int attr = 0;
7608 if (set_attribute(&attr, argv[i])) {
7609 info->attr |= attr;
7611 } else if (set_color(&attr, argv[i])) {
7612 if (first_color)
7613 info->fg = attr;
7614 else
7615 info->bg = attr;
7616 first_color = FALSE;
7621 static void
7622 set_git_color_option(const char *name, char *value)
7624 static const struct enum_map color_option_map[] = {
7625 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7626 ENUM_MAP("branch.local", LINE_MAIN_REF),
7627 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7628 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7630 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7631 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7632 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7633 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7634 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7635 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7636 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7638 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7640 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7641 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7642 ENUM_MAP("status.added", LINE_STAT_STAGED),
7643 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7644 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7645 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7648 int type = LINE_NONE;
7650 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7651 parse_git_color_option(type, value);
7655 static int
7656 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7658 if (!strcmp(name, "gui.encoding"))
7659 parse_encoding(&opt_encoding, value, TRUE);
7661 else if (!strcmp(name, "core.editor"))
7662 string_ncopy(opt_editor, value, valuelen);
7664 else if (!strcmp(name, "core.worktree"))
7665 set_work_tree(value);
7667 else if (!prefixcmp(name, "tig.color."))
7668 set_repo_config_option(name + 10, value, option_color_command);
7670 else if (!prefixcmp(name, "tig.bind."))
7671 set_repo_config_option(name + 9, value, option_bind_command);
7673 else if (!prefixcmp(name, "tig."))
7674 set_repo_config_option(name + 4, value, option_set_command);
7676 else if (!prefixcmp(name, "color."))
7677 set_git_color_option(name + STRING_SIZE("color."), value);
7679 else if (*opt_head && !prefixcmp(name, "branch.") &&
7680 !strncmp(name + 7, opt_head, strlen(opt_head)))
7681 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7683 return OK;
7686 static int
7687 load_git_config(void)
7689 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7691 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7694 static int
7695 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7697 if (!opt_git_dir[0]) {
7698 string_ncopy(opt_git_dir, name, namelen);
7700 } else if (opt_is_inside_work_tree == -1) {
7701 /* This can be 3 different values depending on the
7702 * version of git being used. If git-rev-parse does not
7703 * understand --is-inside-work-tree it will simply echo
7704 * the option else either "true" or "false" is printed.
7705 * Default to true for the unknown case. */
7706 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7708 } else if (*name == '.') {
7709 string_ncopy(opt_cdup, name, namelen);
7711 } else {
7712 string_ncopy(opt_prefix, name, namelen);
7715 return OK;
7718 static int
7719 load_repo_info(void)
7721 const char *rev_parse_argv[] = {
7722 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7723 "--show-cdup", "--show-prefix", NULL
7726 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7731 * Main
7734 static const char usage[] =
7735 "tig " TIG_VERSION " (" __DATE__ ")\n"
7736 "\n"
7737 "Usage: tig [options] [revs] [--] [paths]\n"
7738 " or: tig show [options] [revs] [--] [paths]\n"
7739 " or: tig blame [options] [rev] [--] path\n"
7740 " or: tig status\n"
7741 " or: tig < [git command output]\n"
7742 "\n"
7743 "Options:\n"
7744 " +<number> Select line <number> in the first view\n"
7745 " -v, --version Show version and exit\n"
7746 " -h, --help Show help message and exit";
7748 static void __NORETURN
7749 quit(int sig)
7751 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7752 if (cursed)
7753 endwin();
7754 exit(0);
7757 static void __NORETURN
7758 die(const char *err, ...)
7760 va_list args;
7762 endwin();
7764 va_start(args, err);
7765 fputs("tig: ", stderr);
7766 vfprintf(stderr, err, args);
7767 fputs("\n", stderr);
7768 va_end(args);
7770 exit(1);
7773 static void
7774 warn(const char *msg, ...)
7776 va_list args;
7778 va_start(args, msg);
7779 fputs("tig warning: ", stderr);
7780 vfprintf(stderr, msg, args);
7781 fputs("\n", stderr);
7782 va_end(args);
7785 static int
7786 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7788 const char ***filter_args = data;
7790 return argv_append(filter_args, name) ? OK : ERR;
7793 static void
7794 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7796 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7797 const char **all_argv = NULL;
7799 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7800 !argv_append_array(&all_argv, argv) ||
7801 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7802 die("Failed to split arguments");
7803 argv_free(all_argv);
7804 free(all_argv);
7807 static void
7808 filter_options(const char *argv[], bool blame)
7810 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7812 if (blame)
7813 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7814 else
7815 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7817 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7820 static enum request
7821 parse_options(int argc, const char *argv[])
7823 enum request request = REQ_VIEW_MAIN;
7824 const char *subcommand;
7825 bool seen_dashdash = FALSE;
7826 const char **filter_argv = NULL;
7827 int i;
7829 if (!isatty(STDIN_FILENO))
7830 return REQ_VIEW_PAGER;
7832 if (argc <= 1)
7833 return REQ_VIEW_MAIN;
7835 subcommand = argv[1];
7836 if (!strcmp(subcommand, "status")) {
7837 if (argc > 2)
7838 warn("ignoring arguments after `%s'", subcommand);
7839 return REQ_VIEW_STATUS;
7841 } else if (!strcmp(subcommand, "blame")) {
7842 request = REQ_VIEW_BLAME;
7844 } else if (!strcmp(subcommand, "show")) {
7845 request = REQ_VIEW_DIFF;
7847 } else {
7848 subcommand = NULL;
7851 for (i = 1 + !!subcommand; i < argc; i++) {
7852 const char *opt = argv[i];
7854 // stop parsing our options after -- and let rev-parse handle the rest
7855 if (!seen_dashdash) {
7856 if (!strcmp(opt, "--")) {
7857 seen_dashdash = TRUE;
7858 continue;
7860 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7861 printf("tig version %s\n", TIG_VERSION);
7862 quit(0);
7864 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7865 printf("%s\n", usage);
7866 quit(0);
7868 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7869 opt_lineno = atoi(opt + 1);
7870 continue;
7875 if (!argv_append(&filter_argv, opt))
7876 die("command too long");
7879 if (filter_argv)
7880 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7882 /* Finish validating and setting up blame options */
7883 if (request == REQ_VIEW_BLAME) {
7884 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7885 die("invalid number of options to blame\n\n%s", usage);
7887 if (opt_rev_argv) {
7888 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7891 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7894 return request;
7898 main(int argc, const char *argv[])
7900 const char *codeset = ENCODING_UTF8;
7901 enum request request = parse_options(argc, argv);
7902 struct view *view;
7904 signal(SIGINT, quit);
7905 signal(SIGPIPE, SIG_IGN);
7907 if (setlocale(LC_ALL, "")) {
7908 codeset = nl_langinfo(CODESET);
7911 if (load_repo_info() == ERR)
7912 die("Failed to load repo info.");
7914 if (load_options() == ERR)
7915 die("Failed to load user config.");
7917 if (load_git_config() == ERR)
7918 die("Failed to load repo config.");
7920 /* Require a git repository unless when running in pager mode. */
7921 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7922 die("Not a git repository");
7924 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7925 char translit[SIZEOF_STR];
7927 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7928 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7929 else
7930 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7931 if (opt_iconv_out == ICONV_NONE)
7932 die("Failed to initialize character set conversion");
7935 if (load_refs() == ERR)
7936 die("Failed to load refs.");
7938 init_display();
7940 while (view_driver(display[current_view], request)) {
7941 int key = get_input(0);
7943 view = display[current_view];
7944 request = get_keybinding(view->keymap, key);
7946 /* Some low-level request handling. This keeps access to
7947 * status_win restricted. */
7948 switch (request) {
7949 case REQ_NONE:
7950 report("Unknown key, press %s for help",
7951 get_view_key(view, REQ_VIEW_HELP));
7952 break;
7953 case REQ_PROMPT:
7955 char *cmd = read_prompt(":");
7957 if (cmd && string_isnumber(cmd)) {
7958 int lineno = view->lineno + 1;
7960 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7961 select_view_line(view, lineno - 1);
7962 report("");
7963 } else {
7964 report("Unable to parse '%s' as a line number", cmd);
7966 } else if (cmd && iscommit(cmd)) {
7967 string_ncopy(opt_search, cmd, strlen(cmd));
7969 request = view_request(view, REQ_JUMP_COMMIT);
7970 if (request == REQ_JUMP_COMMIT) {
7971 report("Jumping to commits is not supported by the '%s' view", view->name);
7974 } else if (cmd) {
7975 struct view *next = VIEW(REQ_VIEW_PAGER);
7976 const char *argv[SIZEOF_ARG] = { "git" };
7977 int argc = 1;
7979 /* When running random commands, initially show the
7980 * command in the title. However, it maybe later be
7981 * overwritten if a commit line is selected. */
7982 string_ncopy(next->ref, cmd, strlen(cmd));
7984 if (!argv_from_string(argv, &argc, cmd)) {
7985 report("Too many arguments");
7986 } else if (!format_argv(&next->argv, argv, FALSE)) {
7987 report("Argument formatting failed");
7988 } else {
7989 next->dir = NULL;
7990 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7994 request = REQ_NONE;
7995 break;
7997 case REQ_SEARCH:
7998 case REQ_SEARCH_BACK:
8000 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8001 char *search = read_prompt(prompt);
8003 if (search)
8004 string_ncopy(opt_search, search, strlen(search));
8005 else if (*opt_search)
8006 request = request == REQ_SEARCH ?
8007 REQ_FIND_NEXT :
8008 REQ_FIND_PREV;
8009 else
8010 request = REQ_NONE;
8011 break;
8013 default:
8014 break;
8018 quit(0);
8020 return 0;