Allow space to be ignored in the stage view and blame diffs
[tig.git] / tig.c
blobf0b04257d05b6a0a3a48df34cc1c7231e68fa495
1 /* Copyright (c) 2006-2010 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"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24 char id[SIZEOF_REV]; /* Commit SHA1 ID */
25 unsigned int head:1; /* Is it the current HEAD? */
26 unsigned int tag:1; /* Is it a tag? */
27 unsigned int ltag:1; /* If so, is the tag local? */
28 unsigned int remote:1; /* Is it a remote ref? */
29 unsigned int replace:1; /* Is it a replace ref? */
30 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
31 char name[1]; /* Ref name; tag or head names are shortened. */
34 struct ref_list {
35 char id[SIZEOF_REV]; /* Commit SHA1 ID */
36 size_t size; /* Number of refs. */
37 struct ref **refs; /* References for this ID. */
40 static struct ref *get_ref_head();
41 static struct ref_list *get_ref_list(const char *id);
42 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
43 static int load_refs(void);
45 enum input_status {
46 INPUT_OK,
47 INPUT_SKIP,
48 INPUT_STOP,
49 INPUT_CANCEL
52 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
54 static char *prompt_input(const char *prompt, input_handler handler, void *data);
55 static bool prompt_yesno(const char *prompt);
57 struct menu_item {
58 int hotkey;
59 const char *text;
60 void *data;
63 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
65 #define GRAPHIC_ENUM(_) \
66 _(GRAPHIC, ASCII), \
67 _(GRAPHIC, DEFAULT), \
68 _(GRAPHIC, UTF_8)
70 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
72 #define DATE_ENUM(_) \
73 _(DATE, NO), \
74 _(DATE, DEFAULT), \
75 _(DATE, LOCAL), \
76 _(DATE, RELATIVE), \
77 _(DATE, SHORT)
79 DEFINE_ENUM(date, DATE_ENUM);
81 struct time {
82 time_t sec;
83 int tz;
86 static inline int timecmp(const struct time *t1, const struct time *t2)
88 return t1->sec - t2->sec;
91 static const char *
92 mkdate(const struct time *time, enum date date)
94 static char buf[DATE_COLS + 1];
95 static const struct enum_map reldate[] = {
96 { "second", 1, 60 * 2 },
97 { "minute", 60, 60 * 60 * 2 },
98 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
99 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
100 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
101 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
103 struct tm tm;
105 if (!date || !time || !time->sec)
106 return "";
108 if (date == DATE_RELATIVE) {
109 struct timeval now;
110 time_t date = time->sec + time->tz;
111 time_t seconds;
112 int i;
114 gettimeofday(&now, NULL);
115 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
116 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
117 if (seconds >= reldate[i].value)
118 continue;
120 seconds /= reldate[i].namelen;
121 if (!string_format(buf, "%ld %s%s %s",
122 seconds, reldate[i].name,
123 seconds > 1 ? "s" : "",
124 now.tv_sec >= date ? "ago" : "ahead"))
125 break;
126 return buf;
130 if (date == DATE_LOCAL) {
131 time_t date = time->sec + time->tz;
132 localtime_r(&date, &tm);
134 else {
135 gmtime_r(&time->sec, &tm);
137 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
141 #define AUTHOR_ENUM(_) \
142 _(AUTHOR, NO), \
143 _(AUTHOR, FULL), \
144 _(AUTHOR, ABBREVIATED)
146 DEFINE_ENUM(author, AUTHOR_ENUM);
148 static const char *
149 get_author_initials(const char *author)
151 static char initials[AUTHOR_COLS * 6 + 1];
152 size_t pos = 0;
153 const char *end = strchr(author, '\0');
155 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
157 memset(initials, 0, sizeof(initials));
158 while (author < end) {
159 unsigned char bytes;
160 size_t i;
162 while (author < end && is_initial_sep(*author))
163 author++;
165 bytes = utf8_char_length(author, end);
166 if (bytes >= sizeof(initials) - 1 - pos)
167 break;
168 while (bytes--) {
169 initials[pos++] = *author++;
172 i = pos;
173 while (author < end && !is_initial_sep(*author)) {
174 bytes = utf8_char_length(author, end);
175 if (bytes >= sizeof(initials) - 1 - i) {
176 while (author < end && !is_initial_sep(*author))
177 author++;
178 break;
180 while (bytes--) {
181 initials[i++] = *author++;
185 initials[i++] = 0;
188 return initials;
191 #define author_trim(cols) (cols == 0 || cols > 5)
193 static const char *
194 mkauthor(const char *text, int cols, enum author author)
196 bool trim = author_trim(cols);
197 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
199 if (author == AUTHOR_NO)
200 return "";
201 if (abbreviate && text)
202 return get_author_initials(text);
203 return text;
206 static const char *
207 mkmode(mode_t mode)
209 if (S_ISDIR(mode))
210 return "drwxr-xr-x";
211 else if (S_ISLNK(mode))
212 return "lrwxrwxrwx";
213 else if (S_ISGITLINK(mode))
214 return "m---------";
215 else if (S_ISREG(mode) && mode & S_IXUSR)
216 return "-rwxr-xr-x";
217 else if (S_ISREG(mode))
218 return "-rw-r--r--";
219 else
220 return "----------";
223 #define FILENAME_ENUM(_) \
224 _(FILENAME, NO), \
225 _(FILENAME, ALWAYS), \
226 _(FILENAME, AUTO)
228 DEFINE_ENUM(filename, FILENAME_ENUM);
231 #define VIEW_INFO(_) \
232 _(MAIN, main, ref_head), \
233 _(DIFF, diff, ref_commit), \
234 _(LOG, log, ref_head), \
235 _(TREE, tree, ref_commit), \
236 _(BLOB, blob, ref_blob), \
237 _(BLAME, blame, ref_commit), \
238 _(BRANCH, branch, ref_head), \
239 _(HELP, help, ""), \
240 _(PAGER, pager, ""), \
241 _(STATUS, status, "status"), \
242 _(STAGE, stage, "stage")
245 * User requests
248 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
250 #define REQ_INFO \
251 REQ_GROUP("View switching") \
252 VIEW_INFO(VIEW_REQ), \
254 REQ_GROUP("View manipulation") \
255 REQ_(ENTER, "Enter current line and scroll"), \
256 REQ_(NEXT, "Move to next"), \
257 REQ_(PREVIOUS, "Move to previous"), \
258 REQ_(PARENT, "Move to parent"), \
259 REQ_(VIEW_NEXT, "Move focus to next view"), \
260 REQ_(REFRESH, "Reload and refresh"), \
261 REQ_(MAXIMIZE, "Maximize the current view"), \
262 REQ_(VIEW_CLOSE, "Close the current view"), \
263 REQ_(QUIT, "Close all views and quit"), \
265 REQ_GROUP("View specific requests") \
266 REQ_(STATUS_UPDATE, "Update file status"), \
267 REQ_(STATUS_REVERT, "Revert file changes"), \
268 REQ_(STATUS_MERGE, "Merge file using external tool"), \
269 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
270 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
271 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
272 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
274 REQ_GROUP("Cursor navigation") \
275 REQ_(MOVE_UP, "Move cursor one line up"), \
276 REQ_(MOVE_DOWN, "Move cursor one line down"), \
277 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
278 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
279 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
280 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
282 REQ_GROUP("Scrolling") \
283 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
284 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
285 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
286 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
287 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
288 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
289 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
291 REQ_GROUP("Searching") \
292 REQ_(SEARCH, "Search the view"), \
293 REQ_(SEARCH_BACK, "Search backwards in the view"), \
294 REQ_(FIND_NEXT, "Find next search match"), \
295 REQ_(FIND_PREV, "Find previous search match"), \
297 REQ_GROUP("Option manipulation") \
298 REQ_(OPTIONS, "Open option menu"), \
299 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
300 REQ_(TOGGLE_DATE, "Toggle date display"), \
301 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
302 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
303 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
304 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
305 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
306 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
307 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
308 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
310 REQ_GROUP("Misc") \
311 REQ_(PROMPT, "Bring up the prompt"), \
312 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
313 REQ_(SHOW_VERSION, "Show version information"), \
314 REQ_(STOP_LOADING, "Stop all loading views"), \
315 REQ_(EDIT, "Open in editor"), \
316 REQ_(NONE, "Do nothing")
319 /* User action requests. */
320 enum request {
321 #define REQ_GROUP(help)
322 #define REQ_(req, help) REQ_##req
324 /* Offset all requests to avoid conflicts with ncurses getch values. */
325 REQ_UNKNOWN = KEY_MAX + 1,
326 REQ_OFFSET,
327 REQ_INFO,
329 /* Internal requests. */
330 REQ_JUMP_COMMIT,
332 #undef REQ_GROUP
333 #undef REQ_
336 struct request_info {
337 enum request request;
338 const char *name;
339 int namelen;
340 const char *help;
343 static const struct request_info req_info[] = {
344 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
345 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
346 REQ_INFO
347 #undef REQ_GROUP
348 #undef REQ_
351 static enum request
352 get_request(const char *name)
354 int namelen = strlen(name);
355 int i;
357 for (i = 0; i < ARRAY_SIZE(req_info); i++)
358 if (enum_equals(req_info[i], name, namelen))
359 return req_info[i].request;
361 return REQ_UNKNOWN;
366 * Options
369 /* Option and state variables. */
370 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
371 static enum date opt_date = DATE_DEFAULT;
372 static enum author opt_author = AUTHOR_FULL;
373 static enum filename opt_filename = FILENAME_AUTO;
374 static bool opt_rev_graph = TRUE;
375 static bool opt_line_number = FALSE;
376 static bool opt_show_refs = TRUE;
377 static bool opt_untracked_dirs_content = TRUE;
378 static int opt_diff_context = 3;
379 static char opt_diff_context_arg[9] = "";
380 static bool opt_ignore_space = FALSE;
381 static char opt_ignore_space_arg[22] = "";
382 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
383 static int opt_num_interval = 5;
384 static double opt_hscroll = 0.50;
385 static double opt_scale_split_view = 2.0 / 3.0;
386 static int opt_tab_size = 8;
387 static int opt_author_cols = AUTHOR_COLS;
388 static int opt_filename_cols = FILENAME_COLS;
389 static char opt_path[SIZEOF_STR] = "";
390 static char opt_file[SIZEOF_STR] = "";
391 static char opt_ref[SIZEOF_REF] = "";
392 static unsigned long opt_goto_line = 0;
393 static char opt_head[SIZEOF_REF] = "";
394 static char opt_remote[SIZEOF_REF] = "";
395 static char opt_encoding[20] = ENCODING_UTF8;
396 static iconv_t opt_iconv_in = ICONV_NONE;
397 static iconv_t opt_iconv_out = ICONV_NONE;
398 static char opt_search[SIZEOF_STR] = "";
399 static char opt_cdup[SIZEOF_STR] = "";
400 static char opt_prefix[SIZEOF_STR] = "";
401 static char opt_git_dir[SIZEOF_STR] = "";
402 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
403 static char opt_editor[SIZEOF_STR] = "";
404 static FILE *opt_tty = NULL;
405 static const char **opt_diff_argv = NULL;
406 static const char **opt_rev_argv = NULL;
407 static const char **opt_file_argv = NULL;
408 static const char **opt_blame_argv = NULL;
409 static int opt_lineno = 0;
411 #define is_initial_commit() (!get_ref_head())
412 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
414 static inline void
415 update_diff_context_arg(int diff_context)
417 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
418 string_ncopy(opt_diff_context_arg, "-U3", 3);
421 static inline void
422 update_ignore_space_arg()
424 if (opt_ignore_space)
425 string_copy(opt_ignore_space_arg, "--ignore-all-space");
426 else
427 string_copy(opt_ignore_space_arg, "");
431 * Line-oriented content detection.
434 #define LINE_INFO \
435 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
436 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
437 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
438 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
439 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
440 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
441 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
442 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
443 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
444 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
445 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
446 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
447 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
448 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
449 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
451 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
452 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
453 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
454 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
455 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
456 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
457 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
458 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
459 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
460 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
461 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
462 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
463 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
464 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
465 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
466 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
467 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
468 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
469 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
470 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
471 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
472 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
473 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
474 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
475 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
476 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
477 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
478 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
479 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
480 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
481 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
482 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
483 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
484 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
485 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
486 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
487 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
488 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
489 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
490 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
491 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
492 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
493 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
494 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
495 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
496 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
497 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
498 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
499 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
500 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
502 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
503 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
504 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
505 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
506 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
508 enum line_type {
509 #define LINE(type, line, fg, bg, attr) \
510 LINE_##type
511 LINE_INFO,
512 LINE_NONE
513 #undef LINE
516 struct line_info {
517 const char *name; /* Option name. */
518 int namelen; /* Size of option name. */
519 const char *line; /* The start of line to match. */
520 int linelen; /* Size of string to match. */
521 int fg, bg, attr; /* Color and text attributes for the lines. */
524 static struct line_info line_info[] = {
525 #define LINE(type, line, fg, bg, attr) \
526 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
527 LINE_INFO
528 #undef LINE
531 static struct line_info *custom_color;
532 static size_t custom_colors;
534 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
536 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
537 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
539 /* Color IDs must be 1 or higher. [GH #15] */
540 #define COLOR_ID(line_type) ((line_type) + 1)
542 static enum line_type
543 get_line_type(const char *line)
545 int linelen = strlen(line);
546 enum line_type type;
548 for (type = 0; type < custom_colors; type++)
549 /* Case insensitive search matches Signed-off-by lines better. */
550 if (linelen >= custom_color[type].linelen &&
551 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
552 return TO_CUSTOM_COLOR_TYPE(type);
554 for (type = 0; type < ARRAY_SIZE(line_info); type++)
555 /* Case insensitive search matches Signed-off-by lines better. */
556 if (linelen >= line_info[type].linelen &&
557 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
558 return type;
560 return LINE_DEFAULT;
563 static enum line_type
564 get_line_type_from_ref(const struct ref *ref)
566 if (ref->head)
567 return LINE_MAIN_HEAD;
568 else if (ref->ltag)
569 return LINE_MAIN_LOCAL_TAG;
570 else if (ref->tag)
571 return LINE_MAIN_TAG;
572 else if (ref->tracked)
573 return LINE_MAIN_TRACKED;
574 else if (ref->remote)
575 return LINE_MAIN_REMOTE;
576 else if (ref->replace)
577 return LINE_MAIN_REPLACE;
579 return LINE_MAIN_REF;
582 static inline int
583 get_line_attr(enum line_type type)
585 if (type > LINE_NONE) {
586 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
587 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
589 assert(type < ARRAY_SIZE(line_info));
590 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
593 static struct line_info *
594 get_line_info(const char *name)
596 size_t namelen = strlen(name);
597 enum line_type type;
599 for (type = 0; type < ARRAY_SIZE(line_info); type++)
600 if (enum_equals(line_info[type], name, namelen))
601 return &line_info[type];
603 return NULL;
606 static struct line_info *
607 add_custom_color(const char *quoted_line)
609 struct line_info *info;
610 char *line;
611 size_t linelen;
613 if (!realloc_custom_color(&custom_color, custom_colors, 1))
614 die("Failed to alloc custom line info");
616 linelen = strlen(quoted_line) - 1;
617 line = malloc(linelen);
618 if (!line)
619 return NULL;
621 strncpy(line, quoted_line + 1, linelen);
622 line[linelen - 1] = 0;
624 info = &custom_color[custom_colors++];
625 info->name = info->line = line;
626 info->namelen = info->linelen = strlen(line);
628 return info;
631 static void
632 init_line_info_color_pair(struct line_info *info, enum line_type type,
633 int default_bg, int default_fg)
635 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
636 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
638 init_pair(COLOR_ID(type), fg, bg);
641 static void
642 init_colors(void)
644 int default_bg = line_info[LINE_DEFAULT].bg;
645 int default_fg = line_info[LINE_DEFAULT].fg;
646 enum line_type type;
648 start_color();
650 if (assume_default_colors(default_fg, default_bg) == ERR) {
651 default_bg = COLOR_BLACK;
652 default_fg = COLOR_WHITE;
655 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
656 struct line_info *info = &line_info[type];
658 init_line_info_color_pair(info, type, default_bg, default_fg);
661 for (type = 0; type < custom_colors; type++) {
662 struct line_info *info = &custom_color[type];
664 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
665 default_bg, default_fg);
669 struct line {
670 enum line_type type;
672 /* State flags */
673 unsigned int selected:1;
674 unsigned int dirty:1;
675 unsigned int cleareol:1;
676 unsigned int other:16;
678 void *data; /* User data */
683 * Keys
686 struct keybinding {
687 int alias;
688 enum request request;
691 static struct keybinding default_keybindings[] = {
692 /* View switching */
693 { 'm', REQ_VIEW_MAIN },
694 { 'd', REQ_VIEW_DIFF },
695 { 'l', REQ_VIEW_LOG },
696 { 't', REQ_VIEW_TREE },
697 { 'f', REQ_VIEW_BLOB },
698 { 'B', REQ_VIEW_BLAME },
699 { 'H', REQ_VIEW_BRANCH },
700 { 'p', REQ_VIEW_PAGER },
701 { 'h', REQ_VIEW_HELP },
702 { 'S', REQ_VIEW_STATUS },
703 { 'c', REQ_VIEW_STAGE },
705 /* View manipulation */
706 { 'q', REQ_VIEW_CLOSE },
707 { KEY_TAB, REQ_VIEW_NEXT },
708 { KEY_RETURN, REQ_ENTER },
709 { KEY_UP, REQ_PREVIOUS },
710 { KEY_CTL('P'), REQ_PREVIOUS },
711 { KEY_DOWN, REQ_NEXT },
712 { KEY_CTL('N'), REQ_NEXT },
713 { 'R', REQ_REFRESH },
714 { KEY_F(5), REQ_REFRESH },
715 { 'O', REQ_MAXIMIZE },
716 { ',', REQ_PARENT },
718 /* View specific */
719 { 'u', REQ_STATUS_UPDATE },
720 { '!', REQ_STATUS_REVERT },
721 { 'M', REQ_STATUS_MERGE },
722 { '1', REQ_STAGE_UPDATE_LINE },
723 { '@', REQ_STAGE_NEXT },
724 { '[', REQ_DIFF_CONTEXT_DOWN },
725 { ']', REQ_DIFF_CONTEXT_UP },
727 /* Cursor navigation */
728 { 'k', REQ_MOVE_UP },
729 { 'j', REQ_MOVE_DOWN },
730 { KEY_HOME, REQ_MOVE_FIRST_LINE },
731 { KEY_END, REQ_MOVE_LAST_LINE },
732 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
733 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
734 { ' ', REQ_MOVE_PAGE_DOWN },
735 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
736 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
737 { 'b', REQ_MOVE_PAGE_UP },
738 { '-', REQ_MOVE_PAGE_UP },
740 /* Scrolling */
741 { '|', REQ_SCROLL_FIRST_COL },
742 { KEY_LEFT, REQ_SCROLL_LEFT },
743 { KEY_RIGHT, REQ_SCROLL_RIGHT },
744 { KEY_IC, REQ_SCROLL_LINE_UP },
745 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
746 { KEY_DC, REQ_SCROLL_LINE_DOWN },
747 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
748 { 'w', REQ_SCROLL_PAGE_UP },
749 { 's', REQ_SCROLL_PAGE_DOWN },
751 /* Searching */
752 { '/', REQ_SEARCH },
753 { '?', REQ_SEARCH_BACK },
754 { 'n', REQ_FIND_NEXT },
755 { 'N', REQ_FIND_PREV },
757 /* Misc */
758 { 'Q', REQ_QUIT },
759 { 'z', REQ_STOP_LOADING },
760 { 'v', REQ_SHOW_VERSION },
761 { 'r', REQ_SCREEN_REDRAW },
762 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
763 { 'o', REQ_OPTIONS },
764 { '.', REQ_TOGGLE_LINENO },
765 { 'D', REQ_TOGGLE_DATE },
766 { 'A', REQ_TOGGLE_AUTHOR },
767 { 'g', REQ_TOGGLE_REV_GRAPH },
768 { '~', REQ_TOGGLE_GRAPHIC },
769 { '#', REQ_TOGGLE_FILENAME },
770 { 'F', REQ_TOGGLE_REFS },
771 { 'I', REQ_TOGGLE_SORT_ORDER },
772 { 'i', REQ_TOGGLE_SORT_FIELD },
773 { 'W', REQ_TOGGLE_IGNORE_SPACE },
774 { ':', REQ_PROMPT },
775 { 'e', REQ_EDIT },
778 #define KEYMAP_ENUM(_) \
779 _(KEYMAP, GENERIC), \
780 _(KEYMAP, MAIN), \
781 _(KEYMAP, DIFF), \
782 _(KEYMAP, LOG), \
783 _(KEYMAP, TREE), \
784 _(KEYMAP, BLOB), \
785 _(KEYMAP, BLAME), \
786 _(KEYMAP, BRANCH), \
787 _(KEYMAP, PAGER), \
788 _(KEYMAP, HELP), \
789 _(KEYMAP, STATUS), \
790 _(KEYMAP, STAGE)
792 DEFINE_ENUM(keymap, KEYMAP_ENUM);
794 #define set_keymap(map, name) map_enum(map, keymap_map, name)
796 struct keybinding_table {
797 struct keybinding *data;
798 size_t size;
801 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
803 static void
804 add_keybinding(enum keymap keymap, enum request request, int key)
806 struct keybinding_table *table = &keybindings[keymap];
807 size_t i;
809 for (i = 0; i < table->size; i++) {
810 if (table->data[i].alias == key) {
811 table->data[i].request = request;
812 return;
816 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
817 if (!table->data)
818 die("Failed to allocate keybinding");
819 table->data[table->size].alias = key;
820 table->data[table->size++].request = request;
822 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
823 int i;
825 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
826 if (default_keybindings[i].alias == key)
827 default_keybindings[i].request = REQ_NONE;
831 /* Looks for a key binding first in the given map, then in the generic map, and
832 * lastly in the default keybindings. */
833 static enum request
834 get_keybinding(enum keymap keymap, int key)
836 size_t i;
838 for (i = 0; i < keybindings[keymap].size; i++)
839 if (keybindings[keymap].data[i].alias == key)
840 return keybindings[keymap].data[i].request;
842 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
843 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
844 return keybindings[KEYMAP_GENERIC].data[i].request;
846 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
847 if (default_keybindings[i].alias == key)
848 return default_keybindings[i].request;
850 return (enum request) key;
854 struct key {
855 const char *name;
856 int value;
859 static const struct key key_table[] = {
860 { "Enter", KEY_RETURN },
861 { "Space", ' ' },
862 { "Backspace", KEY_BACKSPACE },
863 { "Tab", KEY_TAB },
864 { "Escape", KEY_ESC },
865 { "Left", KEY_LEFT },
866 { "Right", KEY_RIGHT },
867 { "Up", KEY_UP },
868 { "Down", KEY_DOWN },
869 { "Insert", KEY_IC },
870 { "Delete", KEY_DC },
871 { "Hash", '#' },
872 { "Home", KEY_HOME },
873 { "End", KEY_END },
874 { "PageUp", KEY_PPAGE },
875 { "PageDown", KEY_NPAGE },
876 { "F1", KEY_F(1) },
877 { "F2", KEY_F(2) },
878 { "F3", KEY_F(3) },
879 { "F4", KEY_F(4) },
880 { "F5", KEY_F(5) },
881 { "F6", KEY_F(6) },
882 { "F7", KEY_F(7) },
883 { "F8", KEY_F(8) },
884 { "F9", KEY_F(9) },
885 { "F10", KEY_F(10) },
886 { "F11", KEY_F(11) },
887 { "F12", KEY_F(12) },
890 static int
891 get_key_value(const char *name)
893 int i;
895 for (i = 0; i < ARRAY_SIZE(key_table); i++)
896 if (!strcasecmp(key_table[i].name, name))
897 return key_table[i].value;
899 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
900 return (int)name[1] & 0x1f;
901 if (strlen(name) == 1 && isprint(*name))
902 return (int) *name;
903 return ERR;
906 static const char *
907 get_key_name(int key_value)
909 static char key_char[] = "'X'\0";
910 const char *seq = NULL;
911 int key;
913 for (key = 0; key < ARRAY_SIZE(key_table); key++)
914 if (key_table[key].value == key_value)
915 seq = key_table[key].name;
917 if (seq == NULL && key_value < 0x7f) {
918 char *s = key_char + 1;
920 if (key_value >= 0x20) {
921 *s++ = key_value;
922 } else {
923 *s++ = '^';
924 *s++ = 0x40 | (key_value & 0x1f);
926 *s++ = '\'';
927 *s++ = '\0';
928 seq = key_char;
931 return seq ? seq : "(no key)";
934 static bool
935 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
937 const char *sep = *pos > 0 ? ", " : "";
938 const char *keyname = get_key_name(keybinding->alias);
940 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
943 static bool
944 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
945 enum keymap keymap, bool all)
947 int i;
949 for (i = 0; i < keybindings[keymap].size; i++) {
950 if (keybindings[keymap].data[i].request == request) {
951 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
952 return FALSE;
953 if (!all)
954 break;
958 return TRUE;
961 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
963 static const char *
964 get_keys(enum keymap keymap, enum request request, bool all)
966 static char buf[BUFSIZ];
967 size_t pos = 0;
968 int i;
970 buf[pos] = 0;
972 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
973 return "Too many keybindings!";
974 if (pos > 0 && !all)
975 return buf;
977 if (keymap != KEYMAP_GENERIC) {
978 /* Only the generic keymap includes the default keybindings when
979 * listing all keys. */
980 if (all)
981 return buf;
983 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
984 return "Too many keybindings!";
985 if (pos)
986 return buf;
989 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
990 if (default_keybindings[i].request == request) {
991 if (!append_key(buf, &pos, &default_keybindings[i]))
992 return "Too many keybindings!";
993 if (!all)
994 return buf;
998 return buf;
1001 struct run_request {
1002 enum keymap keymap;
1003 int key;
1004 const char **argv;
1007 static struct run_request *run_request;
1008 static size_t run_requests;
1010 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1012 static enum request
1013 add_run_request(enum keymap keymap, int key, const char **argv)
1015 struct run_request *req;
1017 if (!realloc_run_requests(&run_request, run_requests, 1))
1018 return REQ_NONE;
1020 req = &run_request[run_requests];
1021 req->keymap = keymap;
1022 req->key = key;
1023 req->argv = NULL;
1025 if (!argv_copy(&req->argv, argv))
1026 return REQ_NONE;
1028 return REQ_NONE + ++run_requests;
1031 static struct run_request *
1032 get_run_request(enum request request)
1034 if (request <= REQ_NONE)
1035 return NULL;
1036 return &run_request[request - REQ_NONE - 1];
1039 static void
1040 add_builtin_run_requests(void)
1042 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1043 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1044 const char *commit[] = { "git", "commit", NULL };
1045 const char *gc[] = { "git", "gc", NULL };
1046 struct run_request reqs[] = {
1047 { KEYMAP_MAIN, 'C', cherry_pick },
1048 { KEYMAP_STATUS, 'C', commit },
1049 { KEYMAP_BRANCH, 'C', checkout },
1050 { KEYMAP_GENERIC, 'G', gc },
1052 int i;
1054 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1055 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1057 if (req != reqs[i].key)
1058 continue;
1059 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1060 if (req != REQ_NONE)
1061 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1066 * User config file handling.
1069 #define OPT_ERR_INFO \
1070 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1071 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1072 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1073 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1074 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1075 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1076 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1077 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1078 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1079 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1080 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1081 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1082 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1083 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1084 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1085 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1086 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1087 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1089 enum option_code {
1090 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1091 OPT_ERR_INFO
1092 #undef OPT_ERR_
1093 OPT_OK
1096 static const char *option_errors[] = {
1097 #define OPT_ERR_(name, msg) msg
1098 OPT_ERR_INFO
1099 #undef OPT_ERR_
1102 static const struct enum_map color_map[] = {
1103 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1104 COLOR_MAP(DEFAULT),
1105 COLOR_MAP(BLACK),
1106 COLOR_MAP(BLUE),
1107 COLOR_MAP(CYAN),
1108 COLOR_MAP(GREEN),
1109 COLOR_MAP(MAGENTA),
1110 COLOR_MAP(RED),
1111 COLOR_MAP(WHITE),
1112 COLOR_MAP(YELLOW),
1115 static const struct enum_map attr_map[] = {
1116 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1117 ATTR_MAP(NORMAL),
1118 ATTR_MAP(BLINK),
1119 ATTR_MAP(BOLD),
1120 ATTR_MAP(DIM),
1121 ATTR_MAP(REVERSE),
1122 ATTR_MAP(STANDOUT),
1123 ATTR_MAP(UNDERLINE),
1126 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1128 static enum option_code
1129 parse_step(double *opt, const char *arg)
1131 *opt = atoi(arg);
1132 if (!strchr(arg, '%'))
1133 return OPT_OK;
1135 /* "Shift down" so 100% and 1 does not conflict. */
1136 *opt = (*opt - 1) / 100;
1137 if (*opt >= 1.0) {
1138 *opt = 0.99;
1139 return OPT_ERR_INVALID_STEP_VALUE;
1141 if (*opt < 0.0) {
1142 *opt = 1;
1143 return OPT_ERR_INVALID_STEP_VALUE;
1145 return OPT_OK;
1148 static enum option_code
1149 parse_int(int *opt, const char *arg, int min, int max)
1151 int value = atoi(arg);
1153 if (min <= value && value <= max) {
1154 *opt = value;
1155 return OPT_OK;
1158 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1161 static bool
1162 set_color(int *color, const char *name)
1164 if (map_enum(color, color_map, name))
1165 return TRUE;
1166 if (!prefixcmp(name, "color"))
1167 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1168 return FALSE;
1171 /* Wants: object fgcolor bgcolor [attribute] */
1172 static enum option_code
1173 option_color_command(int argc, const char *argv[])
1175 struct line_info *info;
1177 if (argc < 3)
1178 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1180 if (*argv[0] == '"' || *argv[0] == '\'') {
1181 info = add_custom_color(argv[0]);
1182 } else {
1183 info = get_line_info(argv[0]);
1185 if (!info) {
1186 static const struct enum_map obsolete[] = {
1187 ENUM_MAP("main-delim", LINE_DELIMITER),
1188 ENUM_MAP("main-date", LINE_DATE),
1189 ENUM_MAP("main-author", LINE_AUTHOR),
1191 int index;
1193 if (!map_enum(&index, obsolete, argv[0]))
1194 return OPT_ERR_UNKNOWN_COLOR_NAME;
1195 info = &line_info[index];
1198 if (!set_color(&info->fg, argv[1]) ||
1199 !set_color(&info->bg, argv[2]))
1200 return OPT_ERR_UNKNOWN_COLOR;
1202 info->attr = 0;
1203 while (argc-- > 3) {
1204 int attr;
1206 if (!set_attribute(&attr, argv[argc]))
1207 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1208 info->attr |= attr;
1211 return OPT_OK;
1214 static enum option_code
1215 parse_bool(bool *opt, const char *arg)
1217 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1218 ? TRUE : FALSE;
1219 return OPT_OK;
1222 static enum option_code
1223 parse_enum_do(unsigned int *opt, const char *arg,
1224 const struct enum_map *map, size_t map_size)
1226 bool is_true;
1228 assert(map_size > 1);
1230 if (map_enum_do(map, map_size, (int *) opt, arg))
1231 return OPT_OK;
1233 parse_bool(&is_true, arg);
1234 *opt = is_true ? map[1].value : map[0].value;
1235 return OPT_OK;
1238 #define parse_enum(opt, arg, map) \
1239 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1241 static enum option_code
1242 parse_string(char *opt, const char *arg, size_t optsize)
1244 int arglen = strlen(arg);
1246 switch (arg[0]) {
1247 case '\"':
1248 case '\'':
1249 if (arglen == 1 || arg[arglen - 1] != arg[0])
1250 return OPT_ERR_UNMATCHED_QUOTATION;
1251 arg += 1; arglen -= 2;
1252 default:
1253 string_ncopy_do(opt, optsize, arg, arglen);
1254 return OPT_OK;
1258 static enum option_code
1259 parse_args(const char ***args, const char *argv[])
1261 if (*args == NULL && !argv_copy(args, argv))
1262 return OPT_ERR_OUT_OF_MEMORY;
1263 return OPT_OK;
1266 /* Wants: name = value */
1267 static enum option_code
1268 option_set_command(int argc, const char *argv[])
1270 if (argc < 3)
1271 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1273 if (strcmp(argv[1], "="))
1274 return OPT_ERR_NO_VALUE_ASSIGNED;
1276 if (!strcmp(argv[0], "blame-options"))
1277 return parse_args(&opt_blame_argv, argv + 2);
1279 if (argc != 3)
1280 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1282 if (!strcmp(argv[0], "show-author"))
1283 return parse_enum(&opt_author, argv[2], author_map);
1285 if (!strcmp(argv[0], "show-date"))
1286 return parse_enum(&opt_date, argv[2], date_map);
1288 if (!strcmp(argv[0], "show-rev-graph"))
1289 return parse_bool(&opt_rev_graph, argv[2]);
1291 if (!strcmp(argv[0], "show-refs"))
1292 return parse_bool(&opt_show_refs, argv[2]);
1294 if (!strcmp(argv[0], "show-notes")) {
1295 int res;
1297 strcpy(opt_notes_arg, "--notes=");
1298 res = parse_string(opt_notes_arg + 8, argv[2],
1299 sizeof(opt_notes_arg) - 8);
1300 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1301 opt_notes_arg[7] = '\0';
1302 return res;
1305 if (!strcmp(argv[0], "show-line-numbers"))
1306 return parse_bool(&opt_line_number, argv[2]);
1308 if (!strcmp(argv[0], "line-graphics"))
1309 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1311 if (!strcmp(argv[0], "line-number-interval"))
1312 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1314 if (!strcmp(argv[0], "author-width"))
1315 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1317 if (!strcmp(argv[0], "filename-width"))
1318 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1320 if (!strcmp(argv[0], "show-filename"))
1321 return parse_enum(&opt_filename, argv[2], filename_map);
1323 if (!strcmp(argv[0], "horizontal-scroll"))
1324 return parse_step(&opt_hscroll, argv[2]);
1326 if (!strcmp(argv[0], "split-view-height"))
1327 return parse_step(&opt_scale_split_view, argv[2]);
1329 if (!strcmp(argv[0], "tab-size"))
1330 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1332 if (!strcmp(argv[0], "diff-context")) {
1333 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1335 if (code == OPT_OK)
1336 update_diff_context_arg(opt_diff_context);
1337 return code;
1340 if (!strcmp(argv[0], "ignore-space")) {
1341 enum option_code code = parse_bool(&opt_ignore_space, argv[2]);
1343 if (code == OPT_OK)
1344 update_ignore_space_arg();
1345 return code;
1348 if (!strcmp(argv[0], "commit-encoding"))
1349 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1351 if (!strcmp(argv[0], "status-untracked-dirs"))
1352 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1354 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1357 /* Wants: mode request key */
1358 static enum option_code
1359 option_bind_command(int argc, const char *argv[])
1361 enum request request;
1362 int keymap = -1;
1363 int key;
1365 if (argc < 3)
1366 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1368 if (!set_keymap(&keymap, argv[0]))
1369 return OPT_ERR_UNKNOWN_KEY_MAP;
1371 key = get_key_value(argv[1]);
1372 if (key == ERR)
1373 return OPT_ERR_UNKNOWN_KEY;
1375 request = get_request(argv[2]);
1376 if (request == REQ_UNKNOWN) {
1377 static const struct enum_map obsolete[] = {
1378 ENUM_MAP("cherry-pick", REQ_NONE),
1379 ENUM_MAP("screen-resize", REQ_NONE),
1380 ENUM_MAP("tree-parent", REQ_PARENT),
1382 int alias;
1384 if (map_enum(&alias, obsolete, argv[2])) {
1385 if (alias != REQ_NONE)
1386 add_keybinding(keymap, alias, key);
1387 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1390 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1391 request = add_run_request(keymap, key, argv + 2);
1392 if (request == REQ_UNKNOWN)
1393 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1395 add_keybinding(keymap, request, key);
1397 return OPT_OK;
1401 static enum option_code load_option_file(const char *path);
1403 static enum option_code
1404 option_source_command(int argc, const char *argv[])
1406 if (argc < 1)
1407 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1409 return load_option_file(argv[0]);
1412 static enum option_code
1413 set_option(const char *opt, char *value)
1415 const char *argv[SIZEOF_ARG];
1416 int argc = 0;
1418 if (!argv_from_string(argv, &argc, value))
1419 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1421 if (!strcmp(opt, "color"))
1422 return option_color_command(argc, argv);
1424 if (!strcmp(opt, "set"))
1425 return option_set_command(argc, argv);
1427 if (!strcmp(opt, "bind"))
1428 return option_bind_command(argc, argv);
1430 if (!strcmp(opt, "source"))
1431 return option_source_command(argc, argv);
1433 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1436 struct config_state {
1437 const char *path;
1438 int lineno;
1439 bool errors;
1442 static int
1443 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1445 struct config_state *config = data;
1446 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1448 config->lineno++;
1450 /* Check for comment markers, since read_properties() will
1451 * only ensure opt and value are split at first " \t". */
1452 optlen = strcspn(opt, "#");
1453 if (optlen == 0)
1454 return OK;
1456 if (opt[optlen] == 0) {
1457 /* Look for comment endings in the value. */
1458 size_t len = strcspn(value, "#");
1460 if (len < valuelen) {
1461 valuelen = len;
1462 value[valuelen] = 0;
1465 status = set_option(opt, value);
1468 if (status != OPT_OK) {
1469 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1470 option_errors[status], (int) optlen, opt);
1471 config->errors = TRUE;
1474 /* Always keep going if errors are encountered. */
1475 return OK;
1478 static enum option_code
1479 load_option_file(const char *path)
1481 struct config_state config = { path, 0, FALSE };
1482 struct io io;
1484 /* Do not read configuration from stdin if set to "" */
1485 if (!path || !strlen(path))
1486 return OPT_OK;
1488 /* It's OK that the file doesn't exist. */
1489 if (!io_open(&io, "%s", path))
1490 return OPT_ERR_FILE_DOES_NOT_EXIST;
1492 if (io_load(&io, " \t", read_option, &config) == ERR ||
1493 config.errors == TRUE)
1494 warn("Errors while loading %s.", path);
1495 return OPT_OK;
1498 static int
1499 load_options(void)
1501 const char *home = getenv("HOME");
1502 const char *tigrc_user = getenv("TIGRC_USER");
1503 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1504 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1505 char buf[SIZEOF_STR];
1507 if (!tigrc_system)
1508 tigrc_system = SYSCONFDIR "/tigrc";
1509 load_option_file(tigrc_system);
1511 if (!tigrc_user) {
1512 if (!home || !string_format(buf, "%s/.tigrc", home))
1513 return ERR;
1514 tigrc_user = buf;
1516 load_option_file(tigrc_user);
1518 /* Add _after_ loading config files to avoid adding run requests
1519 * that conflict with keybindings. */
1520 add_builtin_run_requests();
1522 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1523 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1524 int argc = 0;
1526 if (!string_format(buf, "%s", tig_diff_opts) ||
1527 !argv_from_string(diff_opts, &argc, buf))
1528 die("TIG_DIFF_OPTS contains too many arguments");
1529 else if (!argv_copy(&opt_diff_argv, diff_opts))
1530 die("Failed to format TIG_DIFF_OPTS arguments");
1533 return OK;
1538 * The viewer
1541 struct view;
1542 struct view_ops;
1544 /* The display array of active views and the index of the current view. */
1545 static struct view *display[2];
1546 static WINDOW *display_win[2];
1547 static WINDOW *display_title[2];
1548 static unsigned int current_view;
1550 #define foreach_displayed_view(view, i) \
1551 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1553 #define displayed_views() (display[1] != NULL ? 2 : 1)
1555 /* Current head and commit ID */
1556 static char ref_blob[SIZEOF_REF] = "";
1557 static char ref_commit[SIZEOF_REF] = "HEAD";
1558 static char ref_head[SIZEOF_REF] = "HEAD";
1559 static char ref_branch[SIZEOF_REF] = "";
1561 enum view_flag {
1562 VIEW_NO_FLAGS = 0,
1563 VIEW_ALWAYS_LINENO = 1 << 0,
1564 VIEW_CUSTOM_STATUS = 1 << 1,
1565 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1566 VIEW_ADD_PAGER_REFS = 1 << 3,
1567 VIEW_OPEN_DIFF = 1 << 4,
1568 VIEW_NO_REF = 1 << 5,
1569 VIEW_NO_GIT_DIR = 1 << 6,
1570 VIEW_DIFF_LIKE = 1 << 7,
1573 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1575 struct view {
1576 const char *name; /* View name */
1577 const char *id; /* Points to either of ref_{head,commit,blob} */
1579 struct view_ops *ops; /* View operations */
1581 enum keymap keymap; /* What keymap does this view have */
1583 char ref[SIZEOF_REF]; /* Hovered commit reference */
1584 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1586 int height, width; /* The width and height of the main window */
1587 WINDOW *win; /* The main window */
1589 /* Navigation */
1590 unsigned long offset; /* Offset of the window top */
1591 unsigned long yoffset; /* Offset from the window side. */
1592 unsigned long lineno; /* Current line number */
1593 unsigned long p_offset; /* Previous offset of the window top */
1594 unsigned long p_yoffset;/* Previous offset from the window side */
1595 unsigned long p_lineno; /* Previous current line number */
1596 bool p_restore; /* Should the previous position be restored. */
1598 /* Searching */
1599 char grep[SIZEOF_STR]; /* Search string */
1600 regex_t *regex; /* Pre-compiled regexp */
1602 /* If non-NULL, points to the view that opened this view. If this view
1603 * is closed tig will switch back to the parent view. */
1604 struct view *parent;
1605 struct view *prev;
1607 /* Buffering */
1608 size_t lines; /* Total number of lines */
1609 struct line *line; /* Line index */
1610 unsigned int digits; /* Number of digits in the lines member. */
1612 /* Drawing */
1613 struct line *curline; /* Line currently being drawn. */
1614 enum line_type curtype; /* Attribute currently used for drawing. */
1615 unsigned long col; /* Column when drawing. */
1616 bool has_scrolled; /* View was scrolled. */
1618 /* Loading */
1619 const char **argv; /* Shell command arguments. */
1620 const char *dir; /* Directory from which to execute. */
1621 struct io io;
1622 struct io *pipe;
1623 time_t start_time;
1624 time_t update_secs;
1626 /* Private data */
1627 void *private;
1630 enum open_flags {
1631 OPEN_DEFAULT = 0, /* Use default view switching. */
1632 OPEN_SPLIT = 1, /* Split current view. */
1633 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1634 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1635 OPEN_PREPARED = 32, /* Open already prepared command. */
1636 OPEN_EXTRA = 64, /* Open extra data from command. */
1639 struct view_ops {
1640 /* What type of content being displayed. Used in the title bar. */
1641 const char *type;
1642 /* Flags to control the view behavior. */
1643 enum view_flag flags;
1644 /* Size of private data. */
1645 size_t private_size;
1646 /* Open and reads in all view content. */
1647 bool (*open)(struct view *view, enum open_flags flags);
1648 /* Read one line; updates view->line. */
1649 bool (*read)(struct view *view, char *data);
1650 /* Draw one line; @lineno must be < view->height. */
1651 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1652 /* Depending on view handle a special requests. */
1653 enum request (*request)(struct view *view, enum request request, struct line *line);
1654 /* Search for regexp in a line. */
1655 bool (*grep)(struct view *view, struct line *line);
1656 /* Select line */
1657 void (*select)(struct view *view, struct line *line);
1660 #define VIEW_OPS(id, name, ref) name##_ops
1661 static struct view_ops VIEW_INFO(VIEW_OPS);
1663 static struct view views[] = {
1664 #define VIEW_DATA(id, name, ref) \
1665 { #name, ref, &name##_ops, KEYMAP_##id }
1666 VIEW_INFO(VIEW_DATA)
1669 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1671 #define foreach_view(view, i) \
1672 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1674 #define view_is_displayed(view) \
1675 (view == display[0] || view == display[1])
1677 static enum request
1678 view_request(struct view *view, enum request request)
1680 if (!view || !view->lines)
1681 return request;
1682 return view->ops->request(view, request, &view->line[view->lineno]);
1687 * View drawing.
1690 static inline void
1691 set_view_attr(struct view *view, enum line_type type)
1693 if (!view->curline->selected && view->curtype != type) {
1694 (void) wattrset(view->win, get_line_attr(type));
1695 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1696 view->curtype = type;
1700 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1702 static bool
1703 draw_chars(struct view *view, enum line_type type, const char *string,
1704 int max_len, bool use_tilde)
1706 static char out_buffer[BUFSIZ * 2];
1707 int len = 0;
1708 int col = 0;
1709 int trimmed = FALSE;
1710 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1712 if (max_len <= 0)
1713 return VIEW_MAX_LEN(view) <= 0;
1715 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1717 set_view_attr(view, type);
1718 if (len > 0) {
1719 if (opt_iconv_out != ICONV_NONE) {
1720 size_t inlen = len + 1;
1721 char *instr = calloc(1, inlen);
1722 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1723 if (!instr)
1724 return VIEW_MAX_LEN(view) <= 0;
1726 strncpy(instr, string, len);
1728 char *outbuf = out_buffer;
1729 size_t outlen = sizeof(out_buffer);
1731 size_t ret;
1733 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1734 if (ret != (size_t) -1) {
1735 string = out_buffer;
1736 len = sizeof(out_buffer) - outlen;
1738 free(instr);
1741 waddnstr(view->win, string, len);
1743 if (trimmed && use_tilde) {
1744 set_view_attr(view, LINE_DELIMITER);
1745 waddch(view->win, '~');
1746 col++;
1750 view->col += col;
1751 return VIEW_MAX_LEN(view) <= 0;
1754 static bool
1755 draw_space(struct view *view, enum line_type type, int max, int spaces)
1757 static char space[] = " ";
1759 spaces = MIN(max, spaces);
1761 while (spaces > 0) {
1762 int len = MIN(spaces, sizeof(space) - 1);
1764 if (draw_chars(view, type, space, len, FALSE))
1765 return TRUE;
1766 spaces -= len;
1769 return VIEW_MAX_LEN(view) <= 0;
1772 static bool
1773 draw_text(struct view *view, enum line_type type, const char *string)
1775 char text[SIZEOF_STR];
1777 do {
1778 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1780 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1781 return TRUE;
1782 string += pos;
1783 } while (*string);
1785 return VIEW_MAX_LEN(view) <= 0;
1788 static bool
1789 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1791 char text[SIZEOF_STR];
1792 int retval;
1794 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1795 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1798 static bool
1799 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1801 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1802 int max = VIEW_MAX_LEN(view);
1803 int i;
1805 if (max < size)
1806 size = max;
1808 set_view_attr(view, type);
1809 /* Using waddch() instead of waddnstr() ensures that
1810 * they'll be rendered correctly for the cursor line. */
1811 for (i = skip; i < size; i++)
1812 waddch(view->win, graphic[i]);
1814 view->col += size;
1815 if (separator) {
1816 if (size < max && skip <= size)
1817 waddch(view->win, ' ');
1818 view->col++;
1821 return VIEW_MAX_LEN(view) <= 0;
1824 static bool
1825 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1827 int max = MIN(VIEW_MAX_LEN(view), len);
1828 int col = view->col;
1830 if (!text)
1831 return draw_space(view, type, max, max);
1833 return draw_chars(view, type, text, max - 1, trim)
1834 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1837 static bool
1838 draw_date(struct view *view, struct time *time)
1840 const char *date = mkdate(time, opt_date);
1841 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1843 if (opt_date == DATE_NO)
1844 return FALSE;
1846 return draw_field(view, LINE_DATE, date, cols, FALSE);
1849 static bool
1850 draw_author(struct view *view, const char *author)
1852 bool trim = author_trim(opt_author_cols);
1853 const char *text = mkauthor(author, opt_author_cols, opt_author);
1855 if (opt_author == AUTHOR_NO)
1856 return FALSE;
1858 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1861 static bool
1862 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1864 bool trim = filename && strlen(filename) >= opt_filename_cols;
1866 if (opt_filename == FILENAME_NO)
1867 return FALSE;
1869 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1870 return FALSE;
1872 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1875 static bool
1876 draw_mode(struct view *view, mode_t mode)
1878 const char *str = mkmode(mode);
1880 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1883 static bool
1884 draw_lineno(struct view *view, unsigned int lineno)
1886 char number[10];
1887 int digits3 = view->digits < 3 ? 3 : view->digits;
1888 int max = MIN(VIEW_MAX_LEN(view), digits3);
1889 char *text = NULL;
1890 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1892 lineno += view->offset + 1;
1893 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1894 static char fmt[] = "%1ld";
1896 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1897 if (string_format(number, fmt, lineno))
1898 text = number;
1900 if (text)
1901 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1902 else
1903 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1904 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1907 static bool
1908 draw_refs(struct view *view, struct ref_list *refs)
1910 size_t i;
1912 if (!opt_show_refs || !refs)
1913 return FALSE;
1915 for (i = 0; i < refs->size; i++) {
1916 struct ref *ref = refs->refs[i];
1917 enum line_type type = get_line_type_from_ref(ref);
1919 if (draw_formatted(view, type, "[%s]", ref->name))
1920 return TRUE;
1922 if (draw_text(view, LINE_DEFAULT, " "))
1923 return TRUE;
1926 return FALSE;
1929 static bool
1930 draw_view_line(struct view *view, unsigned int lineno)
1932 struct line *line;
1933 bool selected = (view->offset + lineno == view->lineno);
1935 assert(view_is_displayed(view));
1937 if (view->offset + lineno >= view->lines)
1938 return FALSE;
1940 line = &view->line[view->offset + lineno];
1942 wmove(view->win, lineno, 0);
1943 if (line->cleareol)
1944 wclrtoeol(view->win);
1945 view->col = 0;
1946 view->curline = line;
1947 view->curtype = LINE_NONE;
1948 line->selected = FALSE;
1949 line->dirty = line->cleareol = 0;
1951 if (selected) {
1952 set_view_attr(view, LINE_CURSOR);
1953 line->selected = TRUE;
1954 view->ops->select(view, line);
1957 return view->ops->draw(view, line, lineno);
1960 static void
1961 redraw_view_dirty(struct view *view)
1963 bool dirty = FALSE;
1964 int lineno;
1966 for (lineno = 0; lineno < view->height; lineno++) {
1967 if (view->offset + lineno >= view->lines)
1968 break;
1969 if (!view->line[view->offset + lineno].dirty)
1970 continue;
1971 dirty = TRUE;
1972 if (!draw_view_line(view, lineno))
1973 break;
1976 if (!dirty)
1977 return;
1978 wnoutrefresh(view->win);
1981 static void
1982 redraw_view_from(struct view *view, int lineno)
1984 assert(0 <= lineno && lineno < view->height);
1986 for (; lineno < view->height; lineno++) {
1987 if (!draw_view_line(view, lineno))
1988 break;
1991 wnoutrefresh(view->win);
1994 static void
1995 redraw_view(struct view *view)
1997 werase(view->win);
1998 redraw_view_from(view, 0);
2002 static void
2003 update_view_title(struct view *view)
2005 char buf[SIZEOF_STR];
2006 char state[SIZEOF_STR];
2007 size_t bufpos = 0, statelen = 0;
2008 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2010 assert(view_is_displayed(view));
2012 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2013 unsigned int view_lines = view->offset + view->height;
2014 unsigned int lines = view->lines
2015 ? MIN(view_lines, view->lines) * 100 / view->lines
2016 : 0;
2018 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2019 view->ops->type,
2020 view->lineno + 1,
2021 view->lines,
2022 lines);
2026 if (view->pipe) {
2027 time_t secs = time(NULL) - view->start_time;
2029 /* Three git seconds are a long time ... */
2030 if (secs > 2)
2031 string_format_from(state, &statelen, " loading %lds", secs);
2034 string_format_from(buf, &bufpos, "[%s]", view->name);
2035 if (*view->ref && bufpos < view->width) {
2036 size_t refsize = strlen(view->ref);
2037 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2039 if (minsize < view->width)
2040 refsize = view->width - minsize + 7;
2041 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2044 if (statelen && bufpos < view->width) {
2045 string_format_from(buf, &bufpos, "%s", state);
2048 if (view == display[current_view])
2049 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2050 else
2051 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2053 mvwaddnstr(window, 0, 0, buf, bufpos);
2054 wclrtoeol(window);
2055 wnoutrefresh(window);
2058 static int
2059 apply_step(double step, int value)
2061 if (step >= 1)
2062 return (int) step;
2063 value *= step + 0.01;
2064 return value ? value : 1;
2067 static void
2068 resize_display(void)
2070 int offset, i;
2071 struct view *base = display[0];
2072 struct view *view = display[1] ? display[1] : display[0];
2074 /* Setup window dimensions */
2076 getmaxyx(stdscr, base->height, base->width);
2078 /* Make room for the status window. */
2079 base->height -= 1;
2081 if (view != base) {
2082 /* Horizontal split. */
2083 view->width = base->width;
2084 view->height = apply_step(opt_scale_split_view, base->height);
2085 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2086 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2087 base->height -= view->height;
2089 /* Make room for the title bar. */
2090 view->height -= 1;
2093 /* Make room for the title bar. */
2094 base->height -= 1;
2096 offset = 0;
2098 foreach_displayed_view (view, i) {
2099 if (!display_win[i]) {
2100 display_win[i] = newwin(view->height, view->width, offset, 0);
2101 if (!display_win[i])
2102 die("Failed to create %s view", view->name);
2104 scrollok(display_win[i], FALSE);
2106 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2107 if (!display_title[i])
2108 die("Failed to create title window");
2110 } else {
2111 wresize(display_win[i], view->height, view->width);
2112 mvwin(display_win[i], offset, 0);
2113 mvwin(display_title[i], offset + view->height, 0);
2116 view->win = display_win[i];
2118 offset += view->height + 1;
2122 static void
2123 redraw_display(bool clear)
2125 struct view *view;
2126 int i;
2128 foreach_displayed_view (view, i) {
2129 if (clear)
2130 wclear(view->win);
2131 redraw_view(view);
2132 update_view_title(view);
2138 * Option management
2141 #define TOGGLE_MENU \
2142 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2143 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2144 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2145 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2146 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2147 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2148 TOGGLE_(IGNORE_SPACE, 'W', "ignore space", &opt_ignore_space, NULL) \
2149 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2151 static void
2152 toggle_option(enum request request)
2154 const struct {
2155 enum request request;
2156 const struct enum_map *map;
2157 size_t map_size;
2158 } data[] = {
2159 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2160 TOGGLE_MENU
2161 #undef TOGGLE_
2163 const struct menu_item menu[] = {
2164 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2165 TOGGLE_MENU
2166 #undef TOGGLE_
2167 { 0 }
2169 int i = 0;
2171 if (request == REQ_OPTIONS) {
2172 if (!prompt_menu("Toggle option", menu, &i))
2173 return;
2174 } else {
2175 while (i < ARRAY_SIZE(data) && data[i].request != request)
2176 i++;
2177 if (i >= ARRAY_SIZE(data))
2178 die("Invalid request (%d)", request);
2181 if (data[i].map != NULL) {
2182 unsigned int *opt = menu[i].data;
2184 *opt = (*opt + 1) % data[i].map_size;
2185 redraw_display(FALSE);
2186 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2188 } else {
2189 bool *option = menu[i].data;
2191 *option = !*option;
2192 if (option == &opt_ignore_space)
2193 update_ignore_space_arg();
2194 else
2195 redraw_display(FALSE);
2196 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2200 static void
2201 maximize_view(struct view *view, bool redraw)
2203 memset(display, 0, sizeof(display));
2204 current_view = 0;
2205 display[current_view] = view;
2206 resize_display();
2207 if (redraw) {
2208 redraw_display(FALSE);
2209 report("");
2215 * Navigation
2218 static bool
2219 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2221 if (lineno >= view->lines)
2222 lineno = view->lines > 0 ? view->lines - 1 : 0;
2224 if (offset > lineno || offset + view->height <= lineno) {
2225 unsigned long half = view->height / 2;
2227 if (lineno > half)
2228 offset = lineno - half;
2229 else
2230 offset = 0;
2233 if (offset != view->offset || lineno != view->lineno) {
2234 view->offset = offset;
2235 view->lineno = lineno;
2236 return TRUE;
2239 return FALSE;
2242 /* Scrolling backend */
2243 static void
2244 do_scroll_view(struct view *view, int lines)
2246 bool redraw_current_line = FALSE;
2248 /* The rendering expects the new offset. */
2249 view->offset += lines;
2251 assert(0 <= view->offset && view->offset < view->lines);
2252 assert(lines);
2254 /* Move current line into the view. */
2255 if (view->lineno < view->offset) {
2256 view->lineno = view->offset;
2257 redraw_current_line = TRUE;
2258 } else if (view->lineno >= view->offset + view->height) {
2259 view->lineno = view->offset + view->height - 1;
2260 redraw_current_line = TRUE;
2263 assert(view->offset <= view->lineno && view->lineno < view->lines);
2265 /* Redraw the whole screen if scrolling is pointless. */
2266 if (view->height < ABS(lines)) {
2267 redraw_view(view);
2269 } else {
2270 int line = lines > 0 ? view->height - lines : 0;
2271 int end = line + ABS(lines);
2273 scrollok(view->win, TRUE);
2274 wscrl(view->win, lines);
2275 scrollok(view->win, FALSE);
2277 while (line < end && draw_view_line(view, line))
2278 line++;
2280 if (redraw_current_line)
2281 draw_view_line(view, view->lineno - view->offset);
2282 wnoutrefresh(view->win);
2285 view->has_scrolled = TRUE;
2286 report("");
2289 /* Scroll frontend */
2290 static void
2291 scroll_view(struct view *view, enum request request)
2293 int lines = 1;
2295 assert(view_is_displayed(view));
2297 switch (request) {
2298 case REQ_SCROLL_FIRST_COL:
2299 view->yoffset = 0;
2300 redraw_view_from(view, 0);
2301 report("");
2302 return;
2303 case REQ_SCROLL_LEFT:
2304 if (view->yoffset == 0) {
2305 report("Cannot scroll beyond the first column");
2306 return;
2308 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2309 view->yoffset = 0;
2310 else
2311 view->yoffset -= apply_step(opt_hscroll, view->width);
2312 redraw_view_from(view, 0);
2313 report("");
2314 return;
2315 case REQ_SCROLL_RIGHT:
2316 view->yoffset += apply_step(opt_hscroll, view->width);
2317 redraw_view(view);
2318 report("");
2319 return;
2320 case REQ_SCROLL_PAGE_DOWN:
2321 lines = view->height;
2322 case REQ_SCROLL_LINE_DOWN:
2323 if (view->offset + lines > view->lines)
2324 lines = view->lines - view->offset;
2326 if (lines == 0 || view->offset + view->height >= view->lines) {
2327 report("Cannot scroll beyond the last line");
2328 return;
2330 break;
2332 case REQ_SCROLL_PAGE_UP:
2333 lines = view->height;
2334 case REQ_SCROLL_LINE_UP:
2335 if (lines > view->offset)
2336 lines = view->offset;
2338 if (lines == 0) {
2339 report("Cannot scroll beyond the first line");
2340 return;
2343 lines = -lines;
2344 break;
2346 default:
2347 die("request %d not handled in switch", request);
2350 do_scroll_view(view, lines);
2353 /* Cursor moving */
2354 static void
2355 move_view(struct view *view, enum request request)
2357 int scroll_steps = 0;
2358 int steps;
2360 switch (request) {
2361 case REQ_MOVE_FIRST_LINE:
2362 steps = -view->lineno;
2363 break;
2365 case REQ_MOVE_LAST_LINE:
2366 steps = view->lines - view->lineno - 1;
2367 break;
2369 case REQ_MOVE_PAGE_UP:
2370 steps = view->height > view->lineno
2371 ? -view->lineno : -view->height;
2372 break;
2374 case REQ_MOVE_PAGE_DOWN:
2375 steps = view->lineno + view->height >= view->lines
2376 ? view->lines - view->lineno - 1 : view->height;
2377 break;
2379 case REQ_MOVE_UP:
2380 steps = -1;
2381 break;
2383 case REQ_MOVE_DOWN:
2384 steps = 1;
2385 break;
2387 default:
2388 die("request %d not handled in switch", request);
2391 if (steps <= 0 && view->lineno == 0) {
2392 report("Cannot move beyond the first line");
2393 return;
2395 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2396 report("Cannot move beyond the last line");
2397 return;
2400 /* Move the current line */
2401 view->lineno += steps;
2402 assert(0 <= view->lineno && view->lineno < view->lines);
2404 /* Check whether the view needs to be scrolled */
2405 if (view->lineno < view->offset ||
2406 view->lineno >= view->offset + view->height) {
2407 scroll_steps = steps;
2408 if (steps < 0 && -steps > view->offset) {
2409 scroll_steps = -view->offset;
2411 } else if (steps > 0) {
2412 if (view->lineno == view->lines - 1 &&
2413 view->lines > view->height) {
2414 scroll_steps = view->lines - view->offset - 1;
2415 if (scroll_steps >= view->height)
2416 scroll_steps -= view->height - 1;
2421 if (!view_is_displayed(view)) {
2422 view->offset += scroll_steps;
2423 assert(0 <= view->offset && view->offset < view->lines);
2424 view->ops->select(view, &view->line[view->lineno]);
2425 return;
2428 /* Repaint the old "current" line if we be scrolling */
2429 if (ABS(steps) < view->height)
2430 draw_view_line(view, view->lineno - steps - view->offset);
2432 if (scroll_steps) {
2433 do_scroll_view(view, scroll_steps);
2434 return;
2437 /* Draw the current line */
2438 draw_view_line(view, view->lineno - view->offset);
2440 wnoutrefresh(view->win);
2441 report("");
2446 * Searching
2449 static void search_view(struct view *view, enum request request);
2451 static bool
2452 grep_text(struct view *view, const char *text[])
2454 regmatch_t pmatch;
2455 size_t i;
2457 for (i = 0; text[i]; i++)
2458 if (*text[i] &&
2459 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2460 return TRUE;
2461 return FALSE;
2464 static void
2465 select_view_line(struct view *view, unsigned long lineno)
2467 unsigned long old_lineno = view->lineno;
2468 unsigned long old_offset = view->offset;
2470 if (goto_view_line(view, view->offset, lineno)) {
2471 if (view_is_displayed(view)) {
2472 if (old_offset != view->offset) {
2473 redraw_view(view);
2474 } else {
2475 draw_view_line(view, old_lineno - view->offset);
2476 draw_view_line(view, view->lineno - view->offset);
2477 wnoutrefresh(view->win);
2479 } else {
2480 view->ops->select(view, &view->line[view->lineno]);
2485 static void
2486 find_next(struct view *view, enum request request)
2488 unsigned long lineno = view->lineno;
2489 int direction;
2491 if (!*view->grep) {
2492 if (!*opt_search)
2493 report("No previous search");
2494 else
2495 search_view(view, request);
2496 return;
2499 switch (request) {
2500 case REQ_SEARCH:
2501 case REQ_FIND_NEXT:
2502 direction = 1;
2503 break;
2505 case REQ_SEARCH_BACK:
2506 case REQ_FIND_PREV:
2507 direction = -1;
2508 break;
2510 default:
2511 return;
2514 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2515 lineno += direction;
2517 /* Note, lineno is unsigned long so will wrap around in which case it
2518 * will become bigger than view->lines. */
2519 for (; lineno < view->lines; lineno += direction) {
2520 if (view->ops->grep(view, &view->line[lineno])) {
2521 select_view_line(view, lineno);
2522 report("Line %ld matches '%s'", lineno + 1, view->grep);
2523 return;
2527 report("No match found for '%s'", view->grep);
2530 static void
2531 search_view(struct view *view, enum request request)
2533 int regex_err;
2535 if (view->regex) {
2536 regfree(view->regex);
2537 *view->grep = 0;
2538 } else {
2539 view->regex = calloc(1, sizeof(*view->regex));
2540 if (!view->regex)
2541 return;
2544 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2545 if (regex_err != 0) {
2546 char buf[SIZEOF_STR] = "unknown error";
2548 regerror(regex_err, view->regex, buf, sizeof(buf));
2549 report("Search failed: %s", buf);
2550 return;
2553 string_copy(view->grep, opt_search);
2555 find_next(view, request);
2559 * Incremental updating
2562 static void
2563 reset_view(struct view *view)
2565 int i;
2567 for (i = 0; i < view->lines; i++)
2568 free(view->line[i].data);
2569 free(view->line);
2571 view->p_offset = view->offset;
2572 view->p_yoffset = view->yoffset;
2573 view->p_lineno = view->lineno;
2575 view->line = NULL;
2576 view->offset = 0;
2577 view->yoffset = 0;
2578 view->lines = 0;
2579 view->lineno = 0;
2580 view->vid[0] = 0;
2581 view->update_secs = 0;
2584 static const char *
2585 format_arg(const char *name)
2587 static struct {
2588 const char *name;
2589 size_t namelen;
2590 const char *value;
2591 const char *value_if_empty;
2592 } vars[] = {
2593 #define FORMAT_VAR(name, value, value_if_empty) \
2594 { name, STRING_SIZE(name), value, value_if_empty }
2595 FORMAT_VAR("%(directory)", opt_path, "."),
2596 FORMAT_VAR("%(file)", opt_file, ""),
2597 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2598 FORMAT_VAR("%(head)", ref_head, ""),
2599 FORMAT_VAR("%(commit)", ref_commit, ""),
2600 FORMAT_VAR("%(blob)", ref_blob, ""),
2601 FORMAT_VAR("%(branch)", ref_branch, ""),
2603 int i;
2605 for (i = 0; i < ARRAY_SIZE(vars); i++)
2606 if (!strncmp(name, vars[i].name, vars[i].namelen))
2607 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2609 report("Unknown replacement: `%s`", name);
2610 return NULL;
2613 static bool
2614 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2616 char buf[SIZEOF_STR];
2617 int argc;
2619 argv_free(*dst_argv);
2621 for (argc = 0; src_argv[argc]; argc++) {
2622 const char *arg = src_argv[argc];
2623 size_t bufpos = 0;
2625 if (!strcmp(arg, "%(fileargs)")) {
2626 if (!argv_append_array(dst_argv, opt_file_argv))
2627 break;
2628 continue;
2630 } else if (!strcmp(arg, "%(diffargs)")) {
2631 if (!argv_append_array(dst_argv, opt_diff_argv))
2632 break;
2633 continue;
2635 } else if (!strcmp(arg, "%(blameargs)")) {
2636 if (!argv_append_array(dst_argv, opt_blame_argv))
2637 break;
2638 continue;
2640 } else if (!strcmp(arg, "%(revargs)") ||
2641 (first && !strcmp(arg, "%(commit)"))) {
2642 if (!argv_append_array(dst_argv, opt_rev_argv))
2643 break;
2644 continue;
2647 while (arg) {
2648 char *next = strstr(arg, "%(");
2649 int len = next - arg;
2650 const char *value;
2652 if (!next) {
2653 len = strlen(arg);
2654 value = "";
2656 } else {
2657 value = format_arg(next);
2659 if (!value) {
2660 return FALSE;
2664 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2665 return FALSE;
2667 arg = next ? strchr(next, ')') + 1 : NULL;
2670 if (!argv_append(dst_argv, buf))
2671 break;
2674 return src_argv[argc] == NULL;
2677 static bool
2678 restore_view_position(struct view *view)
2680 /* A view without a previous view is the first view */
2681 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2682 select_view_line(view, opt_lineno - 1);
2683 opt_lineno = 0;
2686 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2687 return FALSE;
2689 /* Changing the view position cancels the restoring. */
2690 /* FIXME: Changing back to the first line is not detected. */
2691 if (view->offset != 0 || view->lineno != 0) {
2692 view->p_restore = FALSE;
2693 return FALSE;
2696 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2697 view_is_displayed(view))
2698 werase(view->win);
2700 view->yoffset = view->p_yoffset;
2701 view->p_restore = FALSE;
2703 return TRUE;
2706 static void
2707 end_update(struct view *view, bool force)
2709 if (!view->pipe)
2710 return;
2711 while (!view->ops->read(view, NULL))
2712 if (!force)
2713 return;
2714 if (force)
2715 io_kill(view->pipe);
2716 io_done(view->pipe);
2717 view->pipe = NULL;
2720 static void
2721 setup_update(struct view *view, const char *vid)
2723 reset_view(view);
2724 string_copy_rev(view->vid, vid);
2725 view->pipe = &view->io;
2726 view->start_time = time(NULL);
2729 static bool
2730 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2732 bool extra = !!(flags & (OPEN_EXTRA));
2733 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2734 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2736 if (!reload && !strcmp(view->vid, view->id))
2737 return TRUE;
2739 if (view->pipe) {
2740 if (extra)
2741 io_done(view->pipe);
2742 else
2743 end_update(view, TRUE);
2746 if (!refresh && argv) {
2747 view->dir = dir;
2748 if (!format_argv(&view->argv, argv, !view->prev))
2749 return FALSE;
2751 /* Put the current ref_* value to the view title ref
2752 * member. This is needed by the blob view. Most other
2753 * views sets it automatically after loading because the
2754 * first line is a commit line. */
2755 string_copy_rev(view->ref, view->id);
2758 if (view->argv && view->argv[0] &&
2759 !io_run(&view->io, IO_RD, view->dir, view->argv))
2760 return FALSE;
2762 if (!extra)
2763 setup_update(view, view->id);
2765 return TRUE;
2768 static bool
2769 update_view(struct view *view)
2771 char out_buffer[BUFSIZ * 2];
2772 char *line;
2773 /* Clear the view and redraw everything since the tree sorting
2774 * might have rearranged things. */
2775 bool redraw = view->lines == 0;
2776 bool can_read = TRUE;
2778 if (!view->pipe)
2779 return TRUE;
2781 if (!io_can_read(view->pipe, FALSE)) {
2782 if (view->lines == 0 && view_is_displayed(view)) {
2783 time_t secs = time(NULL) - view->start_time;
2785 if (secs > 1 && secs > view->update_secs) {
2786 if (view->update_secs == 0)
2787 redraw_view(view);
2788 update_view_title(view);
2789 view->update_secs = secs;
2792 return TRUE;
2795 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2796 if (opt_iconv_in != ICONV_NONE) {
2797 ICONV_CONST char *inbuf = line;
2798 size_t inlen = strlen(line) + 1;
2800 char *outbuf = out_buffer;
2801 size_t outlen = sizeof(out_buffer);
2803 size_t ret;
2805 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2806 if (ret != (size_t) -1)
2807 line = out_buffer;
2810 if (!view->ops->read(view, line)) {
2811 report("Allocation failure");
2812 end_update(view, TRUE);
2813 return FALSE;
2818 unsigned long lines = view->lines;
2819 int digits;
2821 for (digits = 0; lines; digits++)
2822 lines /= 10;
2824 /* Keep the displayed view in sync with line number scaling. */
2825 if (digits != view->digits) {
2826 view->digits = digits;
2827 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2828 redraw = TRUE;
2832 if (io_error(view->pipe)) {
2833 report("Failed to read: %s", io_strerror(view->pipe));
2834 end_update(view, TRUE);
2836 } else if (io_eof(view->pipe)) {
2837 if (view_is_displayed(view))
2838 report("");
2839 end_update(view, FALSE);
2842 if (restore_view_position(view))
2843 redraw = TRUE;
2845 if (!view_is_displayed(view))
2846 return TRUE;
2848 if (redraw)
2849 redraw_view_from(view, 0);
2850 else
2851 redraw_view_dirty(view);
2853 /* Update the title _after_ the redraw so that if the redraw picks up a
2854 * commit reference in view->ref it'll be available here. */
2855 update_view_title(view);
2856 return TRUE;
2859 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2861 static struct line *
2862 add_line_data(struct view *view, void *data, enum line_type type)
2864 struct line *line;
2866 if (!realloc_lines(&view->line, view->lines, 1))
2867 return NULL;
2869 line = &view->line[view->lines++];
2870 memset(line, 0, sizeof(*line));
2871 line->type = type;
2872 line->data = data;
2873 line->dirty = 1;
2875 return line;
2878 static struct line *
2879 add_line_text(struct view *view, const char *text, enum line_type type)
2881 char *data = text ? strdup(text) : NULL;
2883 return data ? add_line_data(view, data, type) : NULL;
2886 static struct line *
2887 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2889 char buf[SIZEOF_STR];
2890 int retval;
2892 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2893 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2897 * View opening
2900 static void
2901 load_view(struct view *view, enum open_flags flags)
2903 if (view->pipe)
2904 end_update(view, TRUE);
2905 if (view->ops->private_size) {
2906 if (!view->private)
2907 view->private = calloc(1, view->ops->private_size);
2908 else
2909 memset(view->private, 0, view->ops->private_size);
2911 if (!view->ops->open(view, flags)) {
2912 report("Failed to load %s view", view->name);
2913 return;
2915 restore_view_position(view);
2917 if (view->pipe && view->lines == 0) {
2918 /* Clear the old view and let the incremental updating refill
2919 * the screen. */
2920 werase(view->win);
2921 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2922 report("");
2923 } else if (view_is_displayed(view)) {
2924 redraw_view(view);
2925 report("");
2929 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2930 #define reload_view(view) load_view(view, OPEN_RELOAD)
2932 static void
2933 split_view(struct view *prev, struct view *view)
2935 display[1] = view;
2936 current_view = 1;
2937 view->parent = prev;
2938 resize_display();
2940 if (prev->lineno - prev->offset >= prev->height) {
2941 /* Take the title line into account. */
2942 int lines = prev->lineno - prev->offset - prev->height + 1;
2944 /* Scroll the view that was split if the current line is
2945 * outside the new limited view. */
2946 do_scroll_view(prev, lines);
2949 if (view != prev && view_is_displayed(prev)) {
2950 /* "Blur" the previous view. */
2951 update_view_title(prev);
2955 static void
2956 open_view(struct view *prev, enum request request, enum open_flags flags)
2958 bool split = !!(flags & OPEN_SPLIT);
2959 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2960 struct view *view = VIEW(request);
2961 int nviews = displayed_views();
2963 assert(flags ^ OPEN_REFRESH);
2965 if (view == prev && nviews == 1 && !reload) {
2966 report("Already in %s view", view->name);
2967 return;
2970 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
2971 report("The %s view is disabled in pager view", view->name);
2972 return;
2975 if (split) {
2976 split_view(prev, view);
2977 } else {
2978 maximize_view(view, FALSE);
2981 /* No prev signals that this is the first loaded view. */
2982 if (prev && view != prev) {
2983 view->prev = prev;
2986 load_view(view, flags);
2989 static void
2990 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2992 enum request request = view - views + REQ_OFFSET + 1;
2994 if (view->pipe)
2995 end_update(view, TRUE);
2996 view->dir = dir;
2998 if (!argv_copy(&view->argv, argv)) {
2999 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3000 } else {
3001 open_view(prev, request, flags | OPEN_PREPARED);
3005 static void
3006 open_external_viewer(const char *argv[], const char *dir)
3008 def_prog_mode(); /* save current tty modes */
3009 endwin(); /* restore original tty modes */
3010 io_run_fg(argv, dir);
3011 fprintf(stderr, "Press Enter to continue");
3012 getc(opt_tty);
3013 reset_prog_mode();
3014 redraw_display(TRUE);
3017 static void
3018 open_mergetool(const char *file)
3020 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3022 open_external_viewer(mergetool_argv, opt_cdup);
3025 static void
3026 open_editor(const char *file)
3028 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3029 char editor_cmd[SIZEOF_STR];
3030 const char *editor;
3031 int argc = 0;
3033 editor = getenv("GIT_EDITOR");
3034 if (!editor && *opt_editor)
3035 editor = opt_editor;
3036 if (!editor)
3037 editor = getenv("VISUAL");
3038 if (!editor)
3039 editor = getenv("EDITOR");
3040 if (!editor)
3041 editor = "vi";
3043 string_ncopy(editor_cmd, editor, strlen(editor));
3044 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3045 report("Failed to read editor command");
3046 return;
3049 editor_argv[argc] = file;
3050 open_external_viewer(editor_argv, opt_cdup);
3053 static void
3054 open_run_request(enum request request)
3056 struct run_request *req = get_run_request(request);
3057 const char **argv = NULL;
3059 if (!req) {
3060 report("Unknown run request");
3061 return;
3064 if (format_argv(&argv, req->argv, FALSE))
3065 open_external_viewer(argv, NULL);
3066 if (argv)
3067 argv_free(argv);
3068 free(argv);
3072 * User request switch noodle
3075 static int
3076 view_driver(struct view *view, enum request request)
3078 int i;
3080 if (request == REQ_NONE)
3081 return TRUE;
3083 if (request > REQ_NONE) {
3084 open_run_request(request);
3085 view_request(view, REQ_REFRESH);
3086 return TRUE;
3089 request = view_request(view, request);
3090 if (request == REQ_NONE)
3091 return TRUE;
3093 switch (request) {
3094 case REQ_MOVE_UP:
3095 case REQ_MOVE_DOWN:
3096 case REQ_MOVE_PAGE_UP:
3097 case REQ_MOVE_PAGE_DOWN:
3098 case REQ_MOVE_FIRST_LINE:
3099 case REQ_MOVE_LAST_LINE:
3100 move_view(view, request);
3101 break;
3103 case REQ_SCROLL_FIRST_COL:
3104 case REQ_SCROLL_LEFT:
3105 case REQ_SCROLL_RIGHT:
3106 case REQ_SCROLL_LINE_DOWN:
3107 case REQ_SCROLL_LINE_UP:
3108 case REQ_SCROLL_PAGE_DOWN:
3109 case REQ_SCROLL_PAGE_UP:
3110 scroll_view(view, request);
3111 break;
3113 case REQ_VIEW_BLAME:
3114 if (!opt_file[0]) {
3115 report("No file chosen, press %s to open tree view",
3116 get_view_key(view, REQ_VIEW_TREE));
3117 break;
3119 open_view(view, request, OPEN_DEFAULT);
3120 break;
3122 case REQ_VIEW_BLOB:
3123 if (!ref_blob[0]) {
3124 report("No file chosen, press %s to open tree view",
3125 get_view_key(view, REQ_VIEW_TREE));
3126 break;
3128 open_view(view, request, OPEN_DEFAULT);
3129 break;
3131 case REQ_VIEW_PAGER:
3132 if (view == NULL) {
3133 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3134 die("Failed to open stdin");
3135 open_view(view, request, OPEN_PREPARED);
3136 break;
3139 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3140 report("No pager content, press %s to run command from prompt",
3141 get_view_key(view, REQ_PROMPT));
3142 break;
3144 open_view(view, request, OPEN_DEFAULT);
3145 break;
3147 case REQ_VIEW_STAGE:
3148 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3149 report("No stage content, press %s to open the status view and choose file",
3150 get_view_key(view, REQ_VIEW_STATUS));
3151 break;
3153 open_view(view, request, OPEN_DEFAULT);
3154 break;
3156 case REQ_VIEW_STATUS:
3157 if (opt_is_inside_work_tree == FALSE) {
3158 report("The status view requires a working tree");
3159 break;
3161 open_view(view, request, OPEN_DEFAULT);
3162 break;
3164 case REQ_VIEW_MAIN:
3165 case REQ_VIEW_DIFF:
3166 case REQ_VIEW_LOG:
3167 case REQ_VIEW_TREE:
3168 case REQ_VIEW_HELP:
3169 case REQ_VIEW_BRANCH:
3170 open_view(view, request, OPEN_DEFAULT);
3171 break;
3173 case REQ_NEXT:
3174 case REQ_PREVIOUS:
3175 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3177 if (view->parent) {
3178 int line;
3180 view = view->parent;
3181 line = view->lineno;
3182 move_view(view, request);
3183 if (view_is_displayed(view))
3184 update_view_title(view);
3185 if (line != view->lineno)
3186 view_request(view, REQ_ENTER);
3187 } else {
3188 move_view(view, request);
3190 break;
3192 case REQ_VIEW_NEXT:
3194 int nviews = displayed_views();
3195 int next_view = (current_view + 1) % nviews;
3197 if (next_view == current_view) {
3198 report("Only one view is displayed");
3199 break;
3202 current_view = next_view;
3203 /* Blur out the title of the previous view. */
3204 update_view_title(view);
3205 report("");
3206 break;
3208 case REQ_REFRESH:
3209 report("Refreshing is not yet supported for the %s view", view->name);
3210 break;
3212 case REQ_MAXIMIZE:
3213 if (displayed_views() == 2)
3214 maximize_view(view, TRUE);
3215 break;
3217 case REQ_OPTIONS:
3218 case REQ_TOGGLE_LINENO:
3219 case REQ_TOGGLE_DATE:
3220 case REQ_TOGGLE_AUTHOR:
3221 case REQ_TOGGLE_FILENAME:
3222 case REQ_TOGGLE_GRAPHIC:
3223 case REQ_TOGGLE_REV_GRAPH:
3224 case REQ_TOGGLE_REFS:
3225 case REQ_TOGGLE_IGNORE_SPACE:
3226 toggle_option(request);
3227 if (view_has_flags(view, VIEW_DIFF_LIKE))
3228 reload_view(view);
3229 break;
3231 case REQ_TOGGLE_SORT_FIELD:
3232 case REQ_TOGGLE_SORT_ORDER:
3233 report("Sorting is not yet supported for the %s view", view->name);
3234 break;
3236 case REQ_DIFF_CONTEXT_UP:
3237 case REQ_DIFF_CONTEXT_DOWN:
3238 report("Changing the diff context is not yet supported for the %s view", view->name);
3239 break;
3241 case REQ_SEARCH:
3242 case REQ_SEARCH_BACK:
3243 search_view(view, request);
3244 break;
3246 case REQ_FIND_NEXT:
3247 case REQ_FIND_PREV:
3248 find_next(view, request);
3249 break;
3251 case REQ_STOP_LOADING:
3252 foreach_view(view, i) {
3253 if (view->pipe)
3254 report("Stopped loading the %s view", view->name),
3255 end_update(view, TRUE);
3257 break;
3259 case REQ_SHOW_VERSION:
3260 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3261 return TRUE;
3263 case REQ_SCREEN_REDRAW:
3264 redraw_display(TRUE);
3265 break;
3267 case REQ_EDIT:
3268 report("Nothing to edit");
3269 break;
3271 case REQ_ENTER:
3272 report("Nothing to enter");
3273 break;
3275 case REQ_VIEW_CLOSE:
3276 /* XXX: Mark closed views by letting view->prev point to the
3277 * view itself. Parents to closed view should never be
3278 * followed. */
3279 if (view->prev && view->prev != view) {
3280 maximize_view(view->prev, TRUE);
3281 view->prev = view;
3282 break;
3284 /* Fall-through */
3285 case REQ_QUIT:
3286 return FALSE;
3288 default:
3289 report("Unknown key, press %s for help",
3290 get_view_key(view, REQ_VIEW_HELP));
3291 return TRUE;
3294 return TRUE;
3299 * View backend utilities
3302 enum sort_field {
3303 ORDERBY_NAME,
3304 ORDERBY_DATE,
3305 ORDERBY_AUTHOR,
3308 struct sort_state {
3309 const enum sort_field *fields;
3310 size_t size, current;
3311 bool reverse;
3314 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3315 #define get_sort_field(state) ((state).fields[(state).current])
3316 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3318 static void
3319 sort_view(struct view *view, enum request request, struct sort_state *state,
3320 int (*compare)(const void *, const void *))
3322 switch (request) {
3323 case REQ_TOGGLE_SORT_FIELD:
3324 state->current = (state->current + 1) % state->size;
3325 break;
3327 case REQ_TOGGLE_SORT_ORDER:
3328 state->reverse = !state->reverse;
3329 break;
3330 default:
3331 die("Not a sort request");
3334 qsort(view->line, view->lines, sizeof(*view->line), compare);
3335 redraw_view(view);
3338 static bool
3339 update_diff_context(enum request request)
3341 int diff_context = opt_diff_context;
3343 switch (request) {
3344 case REQ_DIFF_CONTEXT_UP:
3345 opt_diff_context += 1;
3346 update_diff_context_arg(opt_diff_context);
3347 break;
3349 case REQ_DIFF_CONTEXT_DOWN:
3350 if (opt_diff_context == 0) {
3351 report("Diff context cannot be less than zero");
3352 break;
3354 opt_diff_context -= 1;
3355 update_diff_context_arg(opt_diff_context);
3356 break;
3358 default:
3359 die("Not a diff context request");
3362 return diff_context != opt_diff_context;
3365 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3367 /* Small author cache to reduce memory consumption. It uses binary
3368 * search to lookup or find place to position new entries. No entries
3369 * are ever freed. */
3370 static const char *
3371 get_author(const char *name)
3373 static const char **authors;
3374 static size_t authors_size;
3375 int from = 0, to = authors_size - 1;
3377 while (from <= to) {
3378 size_t pos = (to + from) / 2;
3379 int cmp = strcmp(name, authors[pos]);
3381 if (!cmp)
3382 return authors[pos];
3384 if (cmp < 0)
3385 to = pos - 1;
3386 else
3387 from = pos + 1;
3390 if (!realloc_authors(&authors, authors_size, 1))
3391 return NULL;
3392 name = strdup(name);
3393 if (!name)
3394 return NULL;
3396 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3397 authors[from] = name;
3398 authors_size++;
3400 return name;
3403 static void
3404 parse_timesec(struct time *time, const char *sec)
3406 time->sec = (time_t) atol(sec);
3409 static void
3410 parse_timezone(struct time *time, const char *zone)
3412 long tz;
3414 tz = ('0' - zone[1]) * 60 * 60 * 10;
3415 tz += ('0' - zone[2]) * 60 * 60;
3416 tz += ('0' - zone[3]) * 60 * 10;
3417 tz += ('0' - zone[4]) * 60;
3419 if (zone[0] == '-')
3420 tz = -tz;
3422 time->tz = tz;
3423 time->sec -= tz;
3426 /* Parse author lines where the name may be empty:
3427 * author <email@address.tld> 1138474660 +0100
3429 static void
3430 parse_author_line(char *ident, const char **author, struct time *time)
3432 char *nameend = strchr(ident, '<');
3433 char *emailend = strchr(ident, '>');
3435 if (nameend && emailend)
3436 *nameend = *emailend = 0;
3437 ident = chomp_string(ident);
3438 if (!*ident) {
3439 if (nameend)
3440 ident = chomp_string(nameend + 1);
3441 if (!*ident)
3442 ident = "Unknown";
3445 *author = get_author(ident);
3447 /* Parse epoch and timezone */
3448 if (emailend && emailend[1] == ' ') {
3449 char *secs = emailend + 2;
3450 char *zone = strchr(secs, ' ');
3452 parse_timesec(time, secs);
3454 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3455 parse_timezone(time, zone + 1);
3459 static struct line *
3460 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3462 for (; view->line < line; line--)
3463 if (line->type == type)
3464 return line;
3466 return NULL;
3470 * Blame
3473 struct blame_commit {
3474 char id[SIZEOF_REV]; /* SHA1 ID. */
3475 char title[128]; /* First line of the commit message. */
3476 const char *author; /* Author of the commit. */
3477 struct time time; /* Date from the author ident. */
3478 char filename[128]; /* Name of file. */
3479 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3480 char parent_filename[128]; /* Parent/previous name of file. */
3483 struct blame_header {
3484 char id[SIZEOF_REV]; /* SHA1 ID. */
3485 size_t orig_lineno;
3486 size_t lineno;
3487 size_t group;
3490 static bool
3491 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3493 const char *pos = *posref;
3495 *posref = NULL;
3496 pos = strchr(pos + 1, ' ');
3497 if (!pos || !isdigit(pos[1]))
3498 return FALSE;
3499 *number = atoi(pos + 1);
3500 if (*number < min || *number > max)
3501 return FALSE;
3503 *posref = pos;
3504 return TRUE;
3507 static bool
3508 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3510 const char *pos = text + SIZEOF_REV - 2;
3512 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3513 return FALSE;
3515 string_ncopy(header->id, text, SIZEOF_REV);
3517 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3518 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3519 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3520 return FALSE;
3522 return TRUE;
3525 static bool
3526 match_blame_header(const char *name, char **line)
3528 size_t namelen = strlen(name);
3529 bool matched = !strncmp(name, *line, namelen);
3531 if (matched)
3532 *line += namelen;
3534 return matched;
3537 static bool
3538 parse_blame_info(struct blame_commit *commit, char *line)
3540 if (match_blame_header("author ", &line)) {
3541 commit->author = get_author(line);
3543 } else if (match_blame_header("author-time ", &line)) {
3544 parse_timesec(&commit->time, line);
3546 } else if (match_blame_header("author-tz ", &line)) {
3547 parse_timezone(&commit->time, line);
3549 } else if (match_blame_header("summary ", &line)) {
3550 string_ncopy(commit->title, line, strlen(line));
3552 } else if (match_blame_header("previous ", &line)) {
3553 if (strlen(line) <= SIZEOF_REV)
3554 return FALSE;
3555 string_copy_rev(commit->parent_id, line);
3556 line += SIZEOF_REV;
3557 string_ncopy(commit->parent_filename, line, strlen(line));
3559 } else if (match_blame_header("filename ", &line)) {
3560 string_ncopy(commit->filename, line, strlen(line));
3561 return TRUE;
3564 return FALSE;
3568 * Pager backend
3571 static bool
3572 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3574 if (opt_line_number && draw_lineno(view, lineno))
3575 return TRUE;
3577 draw_text(view, line->type, line->data);
3578 return TRUE;
3581 static bool
3582 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3584 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3585 char ref[SIZEOF_STR];
3587 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3588 return TRUE;
3590 /* This is the only fatal call, since it can "corrupt" the buffer. */
3591 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3592 return FALSE;
3594 return TRUE;
3597 static void
3598 add_pager_refs(struct view *view, struct line *line)
3600 char buf[SIZEOF_STR];
3601 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3602 struct ref_list *list;
3603 size_t bufpos = 0, i;
3604 const char *sep = "Refs: ";
3605 bool is_tag = FALSE;
3607 assert(line->type == LINE_COMMIT);
3609 list = get_ref_list(commit_id);
3610 if (!list) {
3611 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3612 goto try_add_describe_ref;
3613 return;
3616 for (i = 0; i < list->size; i++) {
3617 struct ref *ref = list->refs[i];
3618 const char *fmt = ref->tag ? "%s[%s]" :
3619 ref->remote ? "%s<%s>" : "%s%s";
3621 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3622 return;
3623 sep = ", ";
3624 if (ref->tag)
3625 is_tag = TRUE;
3628 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3629 try_add_describe_ref:
3630 /* Add <tag>-g<commit_id> "fake" reference. */
3631 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3632 return;
3635 if (bufpos == 0)
3636 return;
3638 add_line_text(view, buf, LINE_PP_REFS);
3641 static bool
3642 pager_read(struct view *view, char *data)
3644 struct line *line;
3646 if (!data)
3647 return TRUE;
3649 line = add_line_text(view, data, get_line_type(data));
3650 if (!line)
3651 return FALSE;
3653 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3654 add_pager_refs(view, line);
3656 return TRUE;
3659 static enum request
3660 pager_request(struct view *view, enum request request, struct line *line)
3662 int split = 0;
3664 if (request != REQ_ENTER)
3665 return request;
3667 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3668 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3669 split = 1;
3672 /* Always scroll the view even if it was split. That way
3673 * you can use Enter to scroll through the log view and
3674 * split open each commit diff. */
3675 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3677 /* FIXME: A minor workaround. Scrolling the view will call report("")
3678 * but if we are scrolling a non-current view this won't properly
3679 * update the view title. */
3680 if (split)
3681 update_view_title(view);
3683 return REQ_NONE;
3686 static bool
3687 pager_grep(struct view *view, struct line *line)
3689 const char *text[] = { line->data, NULL };
3691 return grep_text(view, text);
3694 static void
3695 pager_select(struct view *view, struct line *line)
3697 if (line->type == LINE_COMMIT) {
3698 char *text = (char *)line->data + STRING_SIZE("commit ");
3700 if (!view_has_flags(view, VIEW_NO_REF))
3701 string_copy_rev(view->ref, text);
3702 string_copy_rev(ref_commit, text);
3706 static bool
3707 pager_open(struct view *view, enum open_flags flags)
3709 return begin_update(view, NULL, NULL, flags);
3712 static struct view_ops pager_ops = {
3713 "line",
3714 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3716 pager_open,
3717 pager_read,
3718 pager_draw,
3719 pager_request,
3720 pager_grep,
3721 pager_select,
3724 static bool
3725 log_open(struct view *view, enum open_flags flags)
3727 static const char *log_argv[] = {
3728 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3731 return begin_update(view, NULL, log_argv, flags);
3734 static enum request
3735 log_request(struct view *view, enum request request, struct line *line)
3737 switch (request) {
3738 case REQ_REFRESH:
3739 load_refs();
3740 refresh_view(view);
3741 return REQ_NONE;
3742 default:
3743 return pager_request(view, request, line);
3747 static struct view_ops log_ops = {
3748 "line",
3749 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3751 log_open,
3752 pager_read,
3753 pager_draw,
3754 log_request,
3755 pager_grep,
3756 pager_select,
3759 struct diff_state {
3760 bool reading_diff_stat;
3763 static bool
3764 diff_open(struct view *view, enum open_flags flags)
3766 static const char *diff_argv[] = {
3767 "git", "show", "--pretty=fuller", "--no-color", "--root",
3768 "--patch-with-stat", "--find-copies-harder", "-C",
3769 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3770 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3773 return begin_update(view, NULL, diff_argv, flags);
3776 static bool
3777 diff_common_read(struct view *view, char *data, struct diff_state *state)
3779 if (state->reading_diff_stat) {
3780 size_t len = strlen(data);
3781 char *pipe = strchr(data, '|');
3782 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3783 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3785 if (pipe && (has_histogram || has_bin_diff)) {
3786 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3787 } else {
3788 state->reading_diff_stat = FALSE;
3791 } else if (!strcmp(data, "---")) {
3792 state->reading_diff_stat = TRUE;
3795 return pager_read(view, data);
3798 static enum request
3799 diff_common_enter(struct view *view, enum request request, struct line *line)
3801 if (line->type == LINE_DIFF_STAT) {
3802 int file_number = 0;
3804 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3805 file_number++;
3806 line--;
3809 while (line < view->line + view->lines) {
3810 if (line->type == LINE_DIFF_HEADER) {
3811 if (file_number == 1) {
3812 break;
3814 file_number--;
3816 line++;
3820 select_view_line(view, line - view->line);
3821 report("");
3822 return REQ_NONE;
3824 } else {
3825 return pager_request(view, request, line);
3829 static bool
3830 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3832 char *sep = strchr(*text, c);
3834 if (sep != NULL) {
3835 *sep = 0;
3836 draw_text(view, *type, *text);
3837 *sep = c;
3838 *text = sep;
3839 *type = next_type;
3842 return sep != NULL;
3845 static bool
3846 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3848 char *text = line->data;
3849 enum line_type type = line->type;
3851 if (opt_line_number && draw_lineno(view, lineno))
3852 return TRUE;
3854 if (type == LINE_DIFF_STAT) {
3855 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3856 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3857 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3858 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3859 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3860 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3861 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3863 } else {
3864 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3865 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3869 draw_text(view, type, text);
3870 return TRUE;
3873 static bool
3874 diff_read(struct view *view, char *data)
3876 struct diff_state *state = view->private;
3878 if (!data) {
3879 /* Fall back to retry if no diff will be shown. */
3880 if (view->lines == 0 && opt_file_argv) {
3881 int pos = argv_size(view->argv)
3882 - argv_size(opt_file_argv) - 1;
3884 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3885 for (; view->argv[pos]; pos++) {
3886 free((void *) view->argv[pos]);
3887 view->argv[pos] = NULL;
3890 if (view->pipe)
3891 io_done(view->pipe);
3892 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3893 return FALSE;
3896 return TRUE;
3899 return diff_common_read(view, data, state);
3902 static bool
3903 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3904 struct blame_header *header, struct blame_commit *commit)
3906 char line_arg[SIZEOF_STR];
3907 const char *blame_argv[] = {
3908 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3910 struct io io;
3911 bool ok = FALSE;
3912 char *buf;
3914 if (!string_format(line_arg, "-L%d,+1", lineno))
3915 return FALSE;
3917 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3918 return FALSE;
3920 while ((buf = io_get(&io, '\n', TRUE))) {
3921 if (header) {
3922 if (!parse_blame_header(header, buf, 9999999))
3923 break;
3924 header = NULL;
3926 } else if (parse_blame_info(commit, buf)) {
3927 ok = TRUE;
3928 break;
3932 if (io_error(&io))
3933 ok = FALSE;
3935 io_done(&io);
3936 return ok;
3939 static bool
3940 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3942 return prefixcmp(chunk, "@@ -") ||
3943 !(chunk = strchr(chunk, marker)) ||
3944 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3947 static enum request
3948 diff_trace_origin(struct view *view, struct line *line)
3950 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3951 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3952 const char *chunk_data;
3953 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3954 int lineno = 0;
3955 const char *file = NULL;
3956 char ref[SIZEOF_REF];
3957 struct blame_header header;
3958 struct blame_commit commit;
3960 if (!diff || !chunk || chunk == line) {
3961 report("The line to trace must be inside a diff chunk");
3962 return REQ_NONE;
3965 for (; diff < line && !file; diff++) {
3966 const char *data = diff->data;
3968 if (!prefixcmp(data, "--- a/")) {
3969 file = data + STRING_SIZE("--- a/");
3970 break;
3974 if (diff == line || !file) {
3975 report("Failed to read the file name");
3976 return REQ_NONE;
3979 chunk_data = chunk->data;
3981 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
3982 report("Failed to read the line number");
3983 return REQ_NONE;
3986 if (lineno == 0) {
3987 report("This is the origin of the line");
3988 return REQ_NONE;
3991 for (chunk += 1; chunk < line; chunk++) {
3992 if (chunk->type == LINE_DIFF_ADD) {
3993 lineno += chunk_marker == '+';
3994 } else if (chunk->type == LINE_DIFF_DEL) {
3995 lineno += chunk_marker == '-';
3996 } else {
3997 lineno++;
4001 if (chunk_marker == '+')
4002 string_copy(ref, view->vid);
4003 else
4004 string_format(ref, "%s^", view->vid);
4006 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4007 report("Failed to read blame data");
4008 return REQ_NONE;
4011 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4012 string_copy(opt_ref, header.id);
4013 opt_goto_line = header.orig_lineno - 1;
4015 return REQ_VIEW_BLAME;
4018 static enum request
4019 diff_request(struct view *view, enum request request, struct line *line)
4021 switch (request) {
4022 case REQ_VIEW_BLAME:
4023 return diff_trace_origin(view, line);
4025 case REQ_DIFF_CONTEXT_UP:
4026 case REQ_DIFF_CONTEXT_DOWN:
4027 if (!update_diff_context(request))
4028 return REQ_NONE;
4029 reload_view(view);
4030 return REQ_NONE;
4033 case REQ_ENTER:
4034 return diff_common_enter(view, request, line);
4036 default:
4037 return pager_request(view, request, line);
4041 static void
4042 diff_select(struct view *view, struct line *line)
4044 if (line->type == LINE_DIFF_STAT) {
4045 const char *key = get_view_key(view, REQ_ENTER);
4047 string_format(view->ref, "Press '%s' to jump to file diff", key);
4048 } else {
4049 string_ncopy(view->ref, view->id, strlen(view->id));
4050 return pager_select(view, line);
4054 static struct view_ops diff_ops = {
4055 "line",
4056 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4057 sizeof(struct diff_state),
4058 diff_open,
4059 diff_read,
4060 diff_common_draw,
4061 diff_request,
4062 pager_grep,
4063 diff_select,
4067 * Help backend
4070 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4072 static bool
4073 help_open_keymap_title(struct view *view, enum keymap keymap)
4075 struct line *line;
4077 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4078 help_keymap_hidden[keymap] ? '+' : '-',
4079 enum_name(keymap_map[keymap]));
4080 if (line)
4081 line->other = keymap;
4083 return help_keymap_hidden[keymap];
4086 static void
4087 help_open_keymap(struct view *view, enum keymap keymap)
4089 const char *group = NULL;
4090 char buf[SIZEOF_STR];
4091 size_t bufpos;
4092 bool add_title = TRUE;
4093 int i;
4095 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4096 const char *key = NULL;
4098 if (req_info[i].request == REQ_NONE)
4099 continue;
4101 if (!req_info[i].request) {
4102 group = req_info[i].help;
4103 continue;
4106 key = get_keys(keymap, req_info[i].request, TRUE);
4107 if (!key || !*key)
4108 continue;
4110 if (add_title && help_open_keymap_title(view, keymap))
4111 return;
4112 add_title = FALSE;
4114 if (group) {
4115 add_line_text(view, group, LINE_HELP_GROUP);
4116 group = NULL;
4119 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4120 enum_name(req_info[i]), req_info[i].help);
4123 group = "External commands:";
4125 for (i = 0; i < run_requests; i++) {
4126 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4127 const char *key;
4128 int argc;
4130 if (!req || req->keymap != keymap)
4131 continue;
4133 key = get_key_name(req->key);
4134 if (!*key)
4135 key = "(no key defined)";
4137 if (add_title && help_open_keymap_title(view, keymap))
4138 return;
4139 if (group) {
4140 add_line_text(view, group, LINE_HELP_GROUP);
4141 group = NULL;
4144 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4145 if (!string_format_from(buf, &bufpos, "%s%s",
4146 argc ? " " : "", req->argv[argc]))
4147 return;
4149 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4153 static bool
4154 help_open(struct view *view, enum open_flags flags)
4156 enum keymap keymap;
4158 reset_view(view);
4159 view->p_restore = TRUE;
4160 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4161 add_line_text(view, "", LINE_DEFAULT);
4163 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4164 help_open_keymap(view, keymap);
4166 return TRUE;
4169 static enum request
4170 help_request(struct view *view, enum request request, struct line *line)
4172 switch (request) {
4173 case REQ_ENTER:
4174 if (line->type == LINE_HELP_KEYMAP) {
4175 help_keymap_hidden[line->other] =
4176 !help_keymap_hidden[line->other];
4177 refresh_view(view);
4180 return REQ_NONE;
4181 default:
4182 return pager_request(view, request, line);
4186 static struct view_ops help_ops = {
4187 "line",
4188 VIEW_NO_GIT_DIR,
4190 help_open,
4191 NULL,
4192 pager_draw,
4193 help_request,
4194 pager_grep,
4195 pager_select,
4200 * Tree backend
4203 struct tree_stack_entry {
4204 struct tree_stack_entry *prev; /* Entry below this in the stack */
4205 unsigned long lineno; /* Line number to restore */
4206 char *name; /* Position of name in opt_path */
4209 /* The top of the path stack. */
4210 static struct tree_stack_entry *tree_stack = NULL;
4211 unsigned long tree_lineno = 0;
4213 static void
4214 pop_tree_stack_entry(void)
4216 struct tree_stack_entry *entry = tree_stack;
4218 tree_lineno = entry->lineno;
4219 entry->name[0] = 0;
4220 tree_stack = entry->prev;
4221 free(entry);
4224 static void
4225 push_tree_stack_entry(const char *name, unsigned long lineno)
4227 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4228 size_t pathlen = strlen(opt_path);
4230 if (!entry)
4231 return;
4233 entry->prev = tree_stack;
4234 entry->name = opt_path + pathlen;
4235 tree_stack = entry;
4237 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4238 pop_tree_stack_entry();
4239 return;
4242 /* Move the current line to the first tree entry. */
4243 tree_lineno = 1;
4244 entry->lineno = lineno;
4247 /* Parse output from git-ls-tree(1):
4249 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4252 #define SIZEOF_TREE_ATTR \
4253 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4255 #define SIZEOF_TREE_MODE \
4256 STRING_SIZE("100644 ")
4258 #define TREE_ID_OFFSET \
4259 STRING_SIZE("100644 blob ")
4261 struct tree_entry {
4262 char id[SIZEOF_REV];
4263 mode_t mode;
4264 struct time time; /* Date from the author ident. */
4265 const char *author; /* Author of the commit. */
4266 char name[1];
4269 struct tree_state {
4270 const char *author_name;
4271 struct time author_time;
4272 bool read_date;
4275 static const char *
4276 tree_path(const struct line *line)
4278 return ((struct tree_entry *) line->data)->name;
4281 static int
4282 tree_compare_entry(const struct line *line1, const struct line *line2)
4284 if (line1->type != line2->type)
4285 return line1->type == LINE_TREE_DIR ? -1 : 1;
4286 return strcmp(tree_path(line1), tree_path(line2));
4289 static const enum sort_field tree_sort_fields[] = {
4290 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4292 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4294 static int
4295 tree_compare(const void *l1, const void *l2)
4297 const struct line *line1 = (const struct line *) l1;
4298 const struct line *line2 = (const struct line *) l2;
4299 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4300 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4302 if (line1->type == LINE_TREE_HEAD)
4303 return -1;
4304 if (line2->type == LINE_TREE_HEAD)
4305 return 1;
4307 switch (get_sort_field(tree_sort_state)) {
4308 case ORDERBY_DATE:
4309 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4311 case ORDERBY_AUTHOR:
4312 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4314 case ORDERBY_NAME:
4315 default:
4316 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4321 static struct line *
4322 tree_entry(struct view *view, enum line_type type, const char *path,
4323 const char *mode, const char *id)
4325 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4326 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4328 if (!entry || !line) {
4329 free(entry);
4330 return NULL;
4333 strncpy(entry->name, path, strlen(path));
4334 if (mode)
4335 entry->mode = strtoul(mode, NULL, 8);
4336 if (id)
4337 string_copy_rev(entry->id, id);
4339 return line;
4342 static bool
4343 tree_read_date(struct view *view, char *text, struct tree_state *state)
4345 if (!text && state->read_date) {
4346 state->read_date = FALSE;
4347 return TRUE;
4349 } else if (!text) {
4350 /* Find next entry to process */
4351 const char *log_file[] = {
4352 "git", "log", "--no-color", "--pretty=raw",
4353 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4356 if (!view->lines) {
4357 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4358 report("Tree is empty");
4359 return TRUE;
4362 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4363 report("Failed to load tree data");
4364 return TRUE;
4367 state->read_date = TRUE;
4368 return FALSE;
4370 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4371 parse_author_line(text + STRING_SIZE("author "),
4372 &state->author_name, &state->author_time);
4374 } else if (*text == ':') {
4375 char *pos;
4376 size_t annotated = 1;
4377 size_t i;
4379 pos = strchr(text, '\t');
4380 if (!pos)
4381 return TRUE;
4382 text = pos + 1;
4383 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4384 text += strlen(opt_path);
4385 pos = strchr(text, '/');
4386 if (pos)
4387 *pos = 0;
4389 for (i = 1; i < view->lines; i++) {
4390 struct line *line = &view->line[i];
4391 struct tree_entry *entry = line->data;
4393 annotated += !!entry->author;
4394 if (entry->author || strcmp(entry->name, text))
4395 continue;
4397 entry->author = state->author_name;
4398 entry->time = state->author_time;
4399 line->dirty = 1;
4400 break;
4403 if (annotated == view->lines)
4404 io_kill(view->pipe);
4406 return TRUE;
4409 static bool
4410 tree_read(struct view *view, char *text)
4412 struct tree_state *state = view->private;
4413 struct tree_entry *data;
4414 struct line *entry, *line;
4415 enum line_type type;
4416 size_t textlen = text ? strlen(text) : 0;
4417 char *path = text + SIZEOF_TREE_ATTR;
4419 if (state->read_date || !text)
4420 return tree_read_date(view, text, state);
4422 if (textlen <= SIZEOF_TREE_ATTR)
4423 return FALSE;
4424 if (view->lines == 0 &&
4425 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4426 return FALSE;
4428 /* Strip the path part ... */
4429 if (*opt_path) {
4430 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4431 size_t striplen = strlen(opt_path);
4433 if (pathlen > striplen)
4434 memmove(path, path + striplen,
4435 pathlen - striplen + 1);
4437 /* Insert "link" to parent directory. */
4438 if (view->lines == 1 &&
4439 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4440 return FALSE;
4443 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4444 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4445 if (!entry)
4446 return FALSE;
4447 data = entry->data;
4449 /* Skip "Directory ..." and ".." line. */
4450 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4451 if (tree_compare_entry(line, entry) <= 0)
4452 continue;
4454 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4456 line->data = data;
4457 line->type = type;
4458 for (; line <= entry; line++)
4459 line->dirty = line->cleareol = 1;
4460 return TRUE;
4463 if (tree_lineno > view->lineno) {
4464 view->lineno = tree_lineno;
4465 tree_lineno = 0;
4468 return TRUE;
4471 static bool
4472 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4474 struct tree_entry *entry = line->data;
4476 if (line->type == LINE_TREE_HEAD) {
4477 if (draw_text(view, line->type, "Directory path /"))
4478 return TRUE;
4479 } else {
4480 if (draw_mode(view, entry->mode))
4481 return TRUE;
4483 if (draw_author(view, entry->author))
4484 return TRUE;
4486 if (draw_date(view, &entry->time))
4487 return TRUE;
4490 draw_text(view, line->type, entry->name);
4491 return TRUE;
4494 static void
4495 open_blob_editor(const char *id)
4497 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4498 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4499 int fd = mkstemp(file);
4501 if (fd == -1)
4502 report("Failed to create temporary file");
4503 else if (!io_run_append(blob_argv, fd))
4504 report("Failed to save blob data to file");
4505 else
4506 open_editor(file);
4507 if (fd != -1)
4508 unlink(file);
4511 static enum request
4512 tree_request(struct view *view, enum request request, struct line *line)
4514 enum open_flags flags;
4515 struct tree_entry *entry = line->data;
4517 switch (request) {
4518 case REQ_VIEW_BLAME:
4519 if (line->type != LINE_TREE_FILE) {
4520 report("Blame only supported for files");
4521 return REQ_NONE;
4524 string_copy(opt_ref, view->vid);
4525 return request;
4527 case REQ_EDIT:
4528 if (line->type != LINE_TREE_FILE) {
4529 report("Edit only supported for files");
4530 } else if (!is_head_commit(view->vid)) {
4531 open_blob_editor(entry->id);
4532 } else {
4533 open_editor(opt_file);
4535 return REQ_NONE;
4537 case REQ_TOGGLE_SORT_FIELD:
4538 case REQ_TOGGLE_SORT_ORDER:
4539 sort_view(view, request, &tree_sort_state, tree_compare);
4540 return REQ_NONE;
4542 case REQ_PARENT:
4543 if (!*opt_path) {
4544 /* quit view if at top of tree */
4545 return REQ_VIEW_CLOSE;
4547 /* fake 'cd ..' */
4548 line = &view->line[1];
4549 break;
4551 case REQ_ENTER:
4552 break;
4554 default:
4555 return request;
4558 /* Cleanup the stack if the tree view is at a different tree. */
4559 while (!*opt_path && tree_stack)
4560 pop_tree_stack_entry();
4562 switch (line->type) {
4563 case LINE_TREE_DIR:
4564 /* Depending on whether it is a subdirectory or parent link
4565 * mangle the path buffer. */
4566 if (line == &view->line[1] && *opt_path) {
4567 pop_tree_stack_entry();
4569 } else {
4570 const char *basename = tree_path(line);
4572 push_tree_stack_entry(basename, view->lineno);
4575 /* Trees and subtrees share the same ID, so they are not not
4576 * unique like blobs. */
4577 flags = OPEN_RELOAD;
4578 request = REQ_VIEW_TREE;
4579 break;
4581 case LINE_TREE_FILE:
4582 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4583 request = REQ_VIEW_BLOB;
4584 break;
4586 default:
4587 return REQ_NONE;
4590 open_view(view, request, flags);
4591 if (request == REQ_VIEW_TREE)
4592 view->lineno = tree_lineno;
4594 return REQ_NONE;
4597 static bool
4598 tree_grep(struct view *view, struct line *line)
4600 struct tree_entry *entry = line->data;
4601 const char *text[] = {
4602 entry->name,
4603 mkauthor(entry->author, opt_author_cols, opt_author),
4604 mkdate(&entry->time, opt_date),
4605 NULL
4608 return grep_text(view, text);
4611 static void
4612 tree_select(struct view *view, struct line *line)
4614 struct tree_entry *entry = line->data;
4616 if (line->type == LINE_TREE_FILE) {
4617 string_copy_rev(ref_blob, entry->id);
4618 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4620 } else if (line->type != LINE_TREE_DIR) {
4621 return;
4624 string_copy_rev(view->ref, entry->id);
4627 static bool
4628 tree_open(struct view *view, enum open_flags flags)
4630 static const char *tree_argv[] = {
4631 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4634 if (view->lines == 0 && opt_prefix[0]) {
4635 char *pos = opt_prefix;
4637 while (pos && *pos) {
4638 char *end = strchr(pos, '/');
4640 if (end)
4641 *end = 0;
4642 push_tree_stack_entry(pos, 0);
4643 pos = end;
4644 if (end) {
4645 *end = '/';
4646 pos++;
4650 } else if (strcmp(view->vid, view->id)) {
4651 opt_path[0] = 0;
4654 return begin_update(view, opt_cdup, tree_argv, flags);
4657 static struct view_ops tree_ops = {
4658 "file",
4659 VIEW_NO_FLAGS,
4660 sizeof(struct tree_state),
4661 tree_open,
4662 tree_read,
4663 tree_draw,
4664 tree_request,
4665 tree_grep,
4666 tree_select,
4669 static bool
4670 blob_open(struct view *view, enum open_flags flags)
4672 static const char *blob_argv[] = {
4673 "git", "cat-file", "blob", "%(blob)", NULL
4676 return begin_update(view, NULL, blob_argv, flags);
4679 static bool
4680 blob_read(struct view *view, char *line)
4682 if (!line)
4683 return TRUE;
4684 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4687 static enum request
4688 blob_request(struct view *view, enum request request, struct line *line)
4690 switch (request) {
4691 case REQ_EDIT:
4692 open_blob_editor(view->vid);
4693 return REQ_NONE;
4694 default:
4695 return pager_request(view, request, line);
4699 static struct view_ops blob_ops = {
4700 "line",
4701 VIEW_NO_FLAGS,
4703 blob_open,
4704 blob_read,
4705 pager_draw,
4706 blob_request,
4707 pager_grep,
4708 pager_select,
4712 * Blame backend
4714 * Loading the blame view is a two phase job:
4716 * 1. File content is read either using opt_file from the
4717 * filesystem or using git-cat-file.
4718 * 2. Then blame information is incrementally added by
4719 * reading output from git-blame.
4722 struct blame {
4723 struct blame_commit *commit;
4724 unsigned long lineno;
4725 char text[1];
4728 struct blame_state {
4729 struct blame_commit *commit;
4730 int blamed;
4731 bool done_reading;
4732 bool auto_filename_display;
4735 static bool
4736 blame_detect_filename_display(struct view *view)
4738 bool show_filenames = FALSE;
4739 const char *filename = NULL;
4740 int i;
4742 if (opt_blame_argv) {
4743 for (i = 0; opt_blame_argv[i]; i++) {
4744 if (prefixcmp(opt_blame_argv[i], "-C"))
4745 continue;
4747 show_filenames = TRUE;
4751 for (i = 0; i < view->lines; i++) {
4752 struct blame *blame = view->line[i].data;
4754 if (blame->commit && blame->commit->id[0]) {
4755 if (!filename)
4756 filename = blame->commit->filename;
4757 else if (strcmp(filename, blame->commit->filename))
4758 show_filenames = TRUE;
4762 return show_filenames;
4765 static bool
4766 blame_open(struct view *view, enum open_flags flags)
4768 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4769 char path[SIZEOF_STR];
4770 size_t i;
4772 if (!view->prev && *opt_prefix) {
4773 string_copy(path, opt_file);
4774 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4775 return FALSE;
4778 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4779 const char *blame_cat_file_argv[] = {
4780 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4783 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4784 return FALSE;
4787 /* First pass: remove multiple references to the same commit. */
4788 for (i = 0; i < view->lines; i++) {
4789 struct blame *blame = view->line[i].data;
4791 if (blame->commit && blame->commit->id[0])
4792 blame->commit->id[0] = 0;
4793 else
4794 blame->commit = NULL;
4797 /* Second pass: free existing references. */
4798 for (i = 0; i < view->lines; i++) {
4799 struct blame *blame = view->line[i].data;
4801 if (blame->commit)
4802 free(blame->commit);
4805 string_format(view->vid, "%s", opt_file);
4806 string_format(view->ref, "%s ...", opt_file);
4808 return TRUE;
4811 static struct blame_commit *
4812 get_blame_commit(struct view *view, const char *id)
4814 size_t i;
4816 for (i = 0; i < view->lines; i++) {
4817 struct blame *blame = view->line[i].data;
4819 if (!blame->commit)
4820 continue;
4822 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4823 return blame->commit;
4827 struct blame_commit *commit = calloc(1, sizeof(*commit));
4829 if (commit)
4830 string_ncopy(commit->id, id, SIZEOF_REV);
4831 return commit;
4835 static struct blame_commit *
4836 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4838 struct blame_header header;
4839 struct blame_commit *commit;
4840 struct blame *blame;
4842 if (!parse_blame_header(&header, text, view->lines))
4843 return NULL;
4845 commit = get_blame_commit(view, text);
4846 if (!commit)
4847 return NULL;
4849 state->blamed += header.group;
4850 while (header.group--) {
4851 struct line *line = &view->line[header.lineno + header.group - 1];
4853 blame = line->data;
4854 blame->commit = commit;
4855 blame->lineno = header.orig_lineno + header.group - 1;
4856 line->dirty = 1;
4859 return commit;
4862 static bool
4863 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4865 if (!line) {
4866 const char *blame_argv[] = {
4867 "git", "blame", "%(blameargs)", "--incremental",
4868 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4871 if (view->lines == 0 && !view->prev)
4872 die("No blame exist for %s", view->vid);
4874 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4875 report("Failed to load blame data");
4876 return TRUE;
4879 if (opt_goto_line > 0) {
4880 select_view_line(view, opt_goto_line);
4881 opt_goto_line = 0;
4884 state->done_reading = TRUE;
4885 return FALSE;
4887 } else {
4888 size_t linelen = strlen(line);
4889 struct blame *blame = malloc(sizeof(*blame) + linelen);
4891 if (!blame)
4892 return FALSE;
4894 blame->commit = NULL;
4895 strncpy(blame->text, line, linelen);
4896 blame->text[linelen] = 0;
4897 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4901 static bool
4902 blame_read(struct view *view, char *line)
4904 struct blame_state *state = view->private;
4906 if (!state->done_reading)
4907 return blame_read_file(view, line, state);
4909 if (!line) {
4910 state->auto_filename_display = blame_detect_filename_display(view);
4911 string_format(view->ref, "%s", view->vid);
4912 if (view_is_displayed(view)) {
4913 update_view_title(view);
4914 redraw_view_from(view, 0);
4916 return TRUE;
4919 if (!state->commit) {
4920 state->commit = read_blame_commit(view, line, state);
4921 string_format(view->ref, "%s %2d%%", view->vid,
4922 view->lines ? state->blamed * 100 / view->lines : 0);
4924 } else if (parse_blame_info(state->commit, line)) {
4925 state->commit = NULL;
4928 return TRUE;
4931 static bool
4932 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4934 struct blame_state *state = view->private;
4935 struct blame *blame = line->data;
4936 struct time *time = NULL;
4937 const char *id = NULL, *author = NULL, *filename = NULL;
4938 enum line_type id_type = LINE_BLAME_ID;
4939 static const enum line_type blame_colors[] = {
4940 LINE_PALETTE_0,
4941 LINE_PALETTE_1,
4942 LINE_PALETTE_2,
4943 LINE_PALETTE_3,
4944 LINE_PALETTE_4,
4945 LINE_PALETTE_5,
4946 LINE_PALETTE_6,
4949 #define BLAME_COLOR(i) \
4950 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4952 if (blame->commit && *blame->commit->filename) {
4953 id = blame->commit->id;
4954 author = blame->commit->author;
4955 filename = blame->commit->filename;
4956 time = &blame->commit->time;
4957 id_type = BLAME_COLOR((long) blame->commit);
4960 if (draw_date(view, time))
4961 return TRUE;
4963 if (draw_author(view, author))
4964 return TRUE;
4966 if (draw_filename(view, filename, state->auto_filename_display))
4967 return TRUE;
4969 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4970 return TRUE;
4972 if (draw_lineno(view, lineno))
4973 return TRUE;
4975 draw_text(view, LINE_DEFAULT, blame->text);
4976 return TRUE;
4979 static bool
4980 check_blame_commit(struct blame *blame, bool check_null_id)
4982 if (!blame->commit)
4983 report("Commit data not loaded yet");
4984 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4985 report("No commit exist for the selected line");
4986 else
4987 return TRUE;
4988 return FALSE;
4991 static void
4992 setup_blame_parent_line(struct view *view, struct blame *blame)
4994 char from[SIZEOF_REF + SIZEOF_STR];
4995 char to[SIZEOF_REF + SIZEOF_STR];
4996 const char *diff_tree_argv[] = {
4997 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4998 "-U0", from, to, "--", NULL
5000 struct io io;
5001 int parent_lineno = -1;
5002 int blamed_lineno = -1;
5003 char *line;
5005 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5006 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5007 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5008 return;
5010 while ((line = io_get(&io, '\n', TRUE))) {
5011 if (*line == '@') {
5012 char *pos = strchr(line, '+');
5014 parent_lineno = atoi(line + 4);
5015 if (pos)
5016 blamed_lineno = atoi(pos + 1);
5018 } else if (*line == '+' && parent_lineno != -1) {
5019 if (blame->lineno == blamed_lineno - 1 &&
5020 !strcmp(blame->text, line + 1)) {
5021 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5022 break;
5024 blamed_lineno++;
5028 io_done(&io);
5031 static enum request
5032 blame_request(struct view *view, enum request request, struct line *line)
5034 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5035 struct blame *blame = line->data;
5037 switch (request) {
5038 case REQ_VIEW_BLAME:
5039 if (check_blame_commit(blame, TRUE)) {
5040 string_copy(opt_ref, blame->commit->id);
5041 string_copy(opt_file, blame->commit->filename);
5042 if (blame->lineno)
5043 view->lineno = blame->lineno;
5044 reload_view(view);
5046 break;
5048 case REQ_PARENT:
5049 if (!check_blame_commit(blame, TRUE))
5050 break;
5051 if (!*blame->commit->parent_id) {
5052 report("The selected commit has no parents");
5053 } else {
5054 string_copy_rev(opt_ref, blame->commit->parent_id);
5055 string_copy(opt_file, blame->commit->parent_filename);
5056 setup_blame_parent_line(view, blame);
5057 opt_goto_line = blame->lineno;
5058 reload_view(view);
5060 break;
5062 case REQ_ENTER:
5063 if (!check_blame_commit(blame, FALSE))
5064 break;
5066 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5067 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5068 break;
5070 if (!strcmp(blame->commit->id, NULL_ID)) {
5071 struct view *diff = VIEW(REQ_VIEW_DIFF);
5072 const char *diff_index_argv[] = {
5073 "git", "diff-index", "--root", "--patch-with-stat",
5074 "-C", "-M", opt_diff_context_arg,
5075 opt_ignore_space_arg,
5076 "HEAD", "--", view->vid, NULL
5079 if (!*blame->commit->parent_id) {
5080 diff_index_argv[1] = "diff";
5081 diff_index_argv[2] = "--no-color";
5082 diff_index_argv[8] = "--";
5083 diff_index_argv[9] = "/dev/null";
5086 open_argv(view, diff, diff_index_argv, NULL, flags);
5087 if (diff->pipe)
5088 string_copy_rev(diff->ref, NULL_ID);
5089 } else {
5090 open_view(view, REQ_VIEW_DIFF, flags);
5092 break;
5094 default:
5095 return request;
5098 return REQ_NONE;
5101 static bool
5102 blame_grep(struct view *view, struct line *line)
5104 struct blame *blame = line->data;
5105 struct blame_commit *commit = blame->commit;
5106 const char *text[] = {
5107 blame->text,
5108 commit ? commit->title : "",
5109 commit ? commit->id : "",
5110 commit && opt_author ? commit->author : "",
5111 commit ? mkdate(&commit->time, opt_date) : "",
5112 NULL
5115 return grep_text(view, text);
5118 static void
5119 blame_select(struct view *view, struct line *line)
5121 struct blame *blame = line->data;
5122 struct blame_commit *commit = blame->commit;
5124 if (!commit)
5125 return;
5127 if (!strcmp(commit->id, NULL_ID))
5128 string_ncopy(ref_commit, "HEAD", 4);
5129 else
5130 string_copy_rev(ref_commit, commit->id);
5133 static struct view_ops blame_ops = {
5134 "line",
5135 VIEW_ALWAYS_LINENO,
5136 sizeof(struct blame_state),
5137 blame_open,
5138 blame_read,
5139 blame_draw,
5140 blame_request,
5141 blame_grep,
5142 blame_select,
5146 * Branch backend
5149 struct branch {
5150 const char *author; /* Author of the last commit. */
5151 struct time time; /* Date of the last activity. */
5152 const struct ref *ref; /* Name and commit ID information. */
5155 static const struct ref branch_all;
5157 static const enum sort_field branch_sort_fields[] = {
5158 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5160 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5162 struct branch_state {
5163 char id[SIZEOF_REV];
5166 static int
5167 branch_compare(const void *l1, const void *l2)
5169 const struct branch *branch1 = ((const struct line *) l1)->data;
5170 const struct branch *branch2 = ((const struct line *) l2)->data;
5172 if (branch1->ref == &branch_all)
5173 return -1;
5174 else if (branch2->ref == &branch_all)
5175 return 1;
5177 switch (get_sort_field(branch_sort_state)) {
5178 case ORDERBY_DATE:
5179 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5181 case ORDERBY_AUTHOR:
5182 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5184 case ORDERBY_NAME:
5185 default:
5186 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5190 static bool
5191 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5193 struct branch *branch = line->data;
5194 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5196 if (draw_date(view, &branch->time))
5197 return TRUE;
5199 if (draw_author(view, branch->author))
5200 return TRUE;
5202 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5203 return TRUE;
5206 static enum request
5207 branch_request(struct view *view, enum request request, struct line *line)
5209 struct branch *branch = line->data;
5211 switch (request) {
5212 case REQ_REFRESH:
5213 load_refs();
5214 refresh_view(view);
5215 return REQ_NONE;
5217 case REQ_TOGGLE_SORT_FIELD:
5218 case REQ_TOGGLE_SORT_ORDER:
5219 sort_view(view, request, &branch_sort_state, branch_compare);
5220 return REQ_NONE;
5222 case REQ_ENTER:
5224 const struct ref *ref = branch->ref;
5225 const char *all_branches_argv[] = {
5226 "git", "log", "--no-color", "--pretty=raw", "--parents",
5227 "--topo-order",
5228 ref == &branch_all ? "--all" : ref->name, NULL
5230 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5232 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5233 return REQ_NONE;
5235 case REQ_JUMP_COMMIT:
5237 int lineno;
5239 for (lineno = 0; lineno < view->lines; lineno++) {
5240 struct branch *branch = view->line[lineno].data;
5242 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5243 select_view_line(view, lineno);
5244 report("");
5245 return REQ_NONE;
5249 default:
5250 return request;
5254 static bool
5255 branch_read(struct view *view, char *line)
5257 struct branch_state *state = view->private;
5258 struct branch *reference;
5259 size_t i;
5261 if (!line)
5262 return TRUE;
5264 switch (get_line_type(line)) {
5265 case LINE_COMMIT:
5266 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5267 return TRUE;
5269 case LINE_AUTHOR:
5270 for (i = 0, reference = NULL; i < view->lines; i++) {
5271 struct branch *branch = view->line[i].data;
5273 if (strcmp(branch->ref->id, state->id))
5274 continue;
5276 view->line[i].dirty = TRUE;
5277 if (reference) {
5278 branch->author = reference->author;
5279 branch->time = reference->time;
5280 continue;
5283 parse_author_line(line + STRING_SIZE("author "),
5284 &branch->author, &branch->time);
5285 reference = branch;
5287 return TRUE;
5289 default:
5290 return TRUE;
5295 static bool
5296 branch_open_visitor(void *data, const struct ref *ref)
5298 struct view *view = data;
5299 struct branch *branch;
5301 if (ref->tag || ref->ltag)
5302 return TRUE;
5304 branch = calloc(1, sizeof(*branch));
5305 if (!branch)
5306 return FALSE;
5308 branch->ref = ref;
5309 return !!add_line_data(view, branch, LINE_DEFAULT);
5312 static bool
5313 branch_open(struct view *view, enum open_flags flags)
5315 const char *branch_log[] = {
5316 "git", "log", "--no-color", "--pretty=raw",
5317 "--simplify-by-decoration", "--all", NULL
5320 if (!begin_update(view, NULL, branch_log, flags)) {
5321 report("Failed to load branch data");
5322 return TRUE;
5325 branch_open_visitor(view, &branch_all);
5326 foreach_ref(branch_open_visitor, view);
5327 view->p_restore = TRUE;
5329 return TRUE;
5332 static bool
5333 branch_grep(struct view *view, struct line *line)
5335 struct branch *branch = line->data;
5336 const char *text[] = {
5337 branch->ref->name,
5338 mkauthor(branch->author, opt_author_cols, opt_author),
5339 NULL
5342 return grep_text(view, text);
5345 static void
5346 branch_select(struct view *view, struct line *line)
5348 struct branch *branch = line->data;
5350 string_copy_rev(view->ref, branch->ref->id);
5351 string_copy_rev(ref_commit, branch->ref->id);
5352 string_copy_rev(ref_head, branch->ref->id);
5353 string_copy_rev(ref_branch, branch->ref->name);
5356 static struct view_ops branch_ops = {
5357 "branch",
5358 VIEW_NO_FLAGS,
5359 sizeof(struct branch_state),
5360 branch_open,
5361 branch_read,
5362 branch_draw,
5363 branch_request,
5364 branch_grep,
5365 branch_select,
5369 * Status backend
5372 struct status {
5373 char status;
5374 struct {
5375 mode_t mode;
5376 char rev[SIZEOF_REV];
5377 char name[SIZEOF_STR];
5378 } old;
5379 struct {
5380 mode_t mode;
5381 char rev[SIZEOF_REV];
5382 char name[SIZEOF_STR];
5383 } new;
5386 static char status_onbranch[SIZEOF_STR];
5387 static struct status stage_status;
5388 static enum line_type stage_line_type;
5390 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5392 /* This should work even for the "On branch" line. */
5393 static inline bool
5394 status_has_none(struct view *view, struct line *line)
5396 return line < view->line + view->lines && !line[1].data;
5399 /* Get fields from the diff line:
5400 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5402 static inline bool
5403 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5405 const char *old_mode = buf + 1;
5406 const char *new_mode = buf + 8;
5407 const char *old_rev = buf + 15;
5408 const char *new_rev = buf + 56;
5409 const char *status = buf + 97;
5411 if (bufsize < 98 ||
5412 old_mode[-1] != ':' ||
5413 new_mode[-1] != ' ' ||
5414 old_rev[-1] != ' ' ||
5415 new_rev[-1] != ' ' ||
5416 status[-1] != ' ')
5417 return FALSE;
5419 file->status = *status;
5421 string_copy_rev(file->old.rev, old_rev);
5422 string_copy_rev(file->new.rev, new_rev);
5424 file->old.mode = strtoul(old_mode, NULL, 8);
5425 file->new.mode = strtoul(new_mode, NULL, 8);
5427 file->old.name[0] = file->new.name[0] = 0;
5429 return TRUE;
5432 static bool
5433 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5435 struct status *unmerged = NULL;
5436 char *buf;
5437 struct io io;
5439 if (!io_run(&io, IO_RD, opt_cdup, argv))
5440 return FALSE;
5442 add_line_data(view, NULL, type);
5444 while ((buf = io_get(&io, 0, TRUE))) {
5445 struct status *file = unmerged;
5447 if (!file) {
5448 file = calloc(1, sizeof(*file));
5449 if (!file || !add_line_data(view, file, type))
5450 goto error_out;
5453 /* Parse diff info part. */
5454 if (status) {
5455 file->status = status;
5456 if (status == 'A')
5457 string_copy(file->old.rev, NULL_ID);
5459 } else if (!file->status || file == unmerged) {
5460 if (!status_get_diff(file, buf, strlen(buf)))
5461 goto error_out;
5463 buf = io_get(&io, 0, TRUE);
5464 if (!buf)
5465 break;
5467 /* Collapse all modified entries that follow an
5468 * associated unmerged entry. */
5469 if (unmerged == file) {
5470 unmerged->status = 'U';
5471 unmerged = NULL;
5472 } else if (file->status == 'U') {
5473 unmerged = file;
5477 /* Grab the old name for rename/copy. */
5478 if (!*file->old.name &&
5479 (file->status == 'R' || file->status == 'C')) {
5480 string_ncopy(file->old.name, buf, strlen(buf));
5482 buf = io_get(&io, 0, TRUE);
5483 if (!buf)
5484 break;
5487 /* git-ls-files just delivers a NUL separated list of
5488 * file names similar to the second half of the
5489 * git-diff-* output. */
5490 string_ncopy(file->new.name, buf, strlen(buf));
5491 if (!*file->old.name)
5492 string_copy(file->old.name, file->new.name);
5493 file = NULL;
5496 if (io_error(&io)) {
5497 error_out:
5498 io_done(&io);
5499 return FALSE;
5502 if (!view->line[view->lines - 1].data)
5503 add_line_data(view, NULL, LINE_STAT_NONE);
5505 io_done(&io);
5506 return TRUE;
5509 /* Don't show unmerged entries in the staged section. */
5510 static const char *status_diff_index_argv[] = {
5511 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5512 "--cached", "-M", "HEAD", NULL
5515 static const char *status_diff_files_argv[] = {
5516 "git", "diff-files", "-z", NULL
5519 static const char *status_list_other_argv[] = {
5520 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5523 static const char *status_list_no_head_argv[] = {
5524 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5527 static const char *update_index_argv[] = {
5528 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5531 /* Restore the previous line number to stay in the context or select a
5532 * line with something that can be updated. */
5533 static void
5534 status_restore(struct view *view)
5536 if (view->p_lineno >= view->lines)
5537 view->p_lineno = view->lines - 1;
5538 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5539 view->p_lineno++;
5540 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5541 view->p_lineno--;
5543 /* If the above fails, always skip the "On branch" line. */
5544 if (view->p_lineno < view->lines)
5545 view->lineno = view->p_lineno;
5546 else
5547 view->lineno = 1;
5549 if (view->lineno < view->offset)
5550 view->offset = view->lineno;
5551 else if (view->offset + view->height <= view->lineno)
5552 view->offset = view->lineno - view->height + 1;
5554 view->p_restore = FALSE;
5557 static void
5558 status_update_onbranch(void)
5560 static const char *paths[][2] = {
5561 { "rebase-apply/rebasing", "Rebasing" },
5562 { "rebase-apply/applying", "Applying mailbox" },
5563 { "rebase-apply/", "Rebasing mailbox" },
5564 { "rebase-merge/interactive", "Interactive rebase" },
5565 { "rebase-merge/", "Rebase merge" },
5566 { "MERGE_HEAD", "Merging" },
5567 { "BISECT_LOG", "Bisecting" },
5568 { "HEAD", "On branch" },
5570 char buf[SIZEOF_STR];
5571 struct stat stat;
5572 int i;
5574 if (is_initial_commit()) {
5575 string_copy(status_onbranch, "Initial commit");
5576 return;
5579 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5580 char *head = opt_head;
5582 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5583 lstat(buf, &stat) < 0)
5584 continue;
5586 if (!*opt_head) {
5587 struct io io;
5589 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5590 io_read_buf(&io, buf, sizeof(buf))) {
5591 head = buf;
5592 if (!prefixcmp(head, "refs/heads/"))
5593 head += STRING_SIZE("refs/heads/");
5597 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5598 string_copy(status_onbranch, opt_head);
5599 return;
5602 string_copy(status_onbranch, "Not currently on any branch");
5605 /* First parse staged info using git-diff-index(1), then parse unstaged
5606 * info using git-diff-files(1), and finally untracked files using
5607 * git-ls-files(1). */
5608 static bool
5609 status_open(struct view *view, enum open_flags flags)
5611 reset_view(view);
5613 add_line_data(view, NULL, LINE_STAT_HEAD);
5614 status_update_onbranch();
5616 io_run_bg(update_index_argv);
5618 if (is_initial_commit()) {
5619 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5620 return FALSE;
5621 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5622 return FALSE;
5625 if (!opt_untracked_dirs_content)
5626 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5628 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5629 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5630 return FALSE;
5632 /* Restore the exact position or use the specialized restore
5633 * mode? */
5634 if (!view->p_restore)
5635 status_restore(view);
5636 return TRUE;
5639 static bool
5640 status_draw(struct view *view, struct line *line, unsigned int lineno)
5642 struct status *status = line->data;
5643 enum line_type type;
5644 const char *text;
5646 if (!status) {
5647 switch (line->type) {
5648 case LINE_STAT_STAGED:
5649 type = LINE_STAT_SECTION;
5650 text = "Changes to be committed:";
5651 break;
5653 case LINE_STAT_UNSTAGED:
5654 type = LINE_STAT_SECTION;
5655 text = "Changed but not updated:";
5656 break;
5658 case LINE_STAT_UNTRACKED:
5659 type = LINE_STAT_SECTION;
5660 text = "Untracked files:";
5661 break;
5663 case LINE_STAT_NONE:
5664 type = LINE_DEFAULT;
5665 text = " (no files)";
5666 break;
5668 case LINE_STAT_HEAD:
5669 type = LINE_STAT_HEAD;
5670 text = status_onbranch;
5671 break;
5673 default:
5674 return FALSE;
5676 } else {
5677 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5679 buf[0] = status->status;
5680 if (draw_text(view, line->type, buf))
5681 return TRUE;
5682 type = LINE_DEFAULT;
5683 text = status->new.name;
5686 draw_text(view, type, text);
5687 return TRUE;
5690 static enum request
5691 status_enter(struct view *view, struct line *line)
5693 struct status *status = line->data;
5694 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5696 if (line->type == LINE_STAT_NONE ||
5697 (!status && line[1].type == LINE_STAT_NONE)) {
5698 report("No file to diff");
5699 return REQ_NONE;
5702 switch (line->type) {
5703 case LINE_STAT_STAGED:
5704 case LINE_STAT_UNSTAGED:
5705 break;
5707 case LINE_STAT_UNTRACKED:
5708 if (!status) {
5709 report("No file to show");
5710 return REQ_NONE;
5713 if (!suffixcmp(status->new.name, -1, "/")) {
5714 report("Cannot display a directory");
5715 return REQ_NONE;
5717 break;
5719 case LINE_STAT_HEAD:
5720 return REQ_NONE;
5722 default:
5723 die("line type %d not handled in switch", line->type);
5726 if (status) {
5727 stage_status = *status;
5728 } else {
5729 memset(&stage_status, 0, sizeof(stage_status));
5732 stage_line_type = line->type;
5734 open_view(view, REQ_VIEW_STAGE, flags);
5735 return REQ_NONE;
5738 static bool
5739 status_exists(struct view *view, struct status *status, enum line_type type)
5741 unsigned long lineno;
5743 for (lineno = 0; lineno < view->lines; lineno++) {
5744 struct line *line = &view->line[lineno];
5745 struct status *pos = line->data;
5747 if (line->type != type)
5748 continue;
5749 if (!pos && (!status || !status->status) && line[1].data) {
5750 select_view_line(view, lineno);
5751 return TRUE;
5753 if (pos && !strcmp(status->new.name, pos->new.name)) {
5754 select_view_line(view, lineno);
5755 return TRUE;
5759 return FALSE;
5763 static bool
5764 status_update_prepare(struct io *io, enum line_type type)
5766 const char *staged_argv[] = {
5767 "git", "update-index", "-z", "--index-info", NULL
5769 const char *others_argv[] = {
5770 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5773 switch (type) {
5774 case LINE_STAT_STAGED:
5775 return io_run(io, IO_WR, opt_cdup, staged_argv);
5777 case LINE_STAT_UNSTAGED:
5778 case LINE_STAT_UNTRACKED:
5779 return io_run(io, IO_WR, opt_cdup, others_argv);
5781 default:
5782 die("line type %d not handled in switch", type);
5783 return FALSE;
5787 static bool
5788 status_update_write(struct io *io, struct status *status, enum line_type type)
5790 switch (type) {
5791 case LINE_STAT_STAGED:
5792 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5793 status->old.rev, status->old.name, 0);
5795 case LINE_STAT_UNSTAGED:
5796 case LINE_STAT_UNTRACKED:
5797 return io_printf(io, "%s%c", status->new.name, 0);
5799 default:
5800 die("line type %d not handled in switch", type);
5801 return FALSE;
5805 static bool
5806 status_update_file(struct status *status, enum line_type type)
5808 struct io io;
5809 bool result;
5811 if (!status_update_prepare(&io, type))
5812 return FALSE;
5814 result = status_update_write(&io, status, type);
5815 return io_done(&io) && result;
5818 static bool
5819 status_update_files(struct view *view, struct line *line)
5821 char buf[sizeof(view->ref)];
5822 struct io io;
5823 bool result = TRUE;
5824 struct line *pos = view->line + view->lines;
5825 int files = 0;
5826 int file, done;
5827 int cursor_y = -1, cursor_x = -1;
5829 if (!status_update_prepare(&io, line->type))
5830 return FALSE;
5832 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5833 files++;
5835 string_copy(buf, view->ref);
5836 getsyx(cursor_y, cursor_x);
5837 for (file = 0, done = 5; result && file < files; line++, file++) {
5838 int almost_done = file * 100 / files;
5840 if (almost_done > done) {
5841 done = almost_done;
5842 string_format(view->ref, "updating file %u of %u (%d%% done)",
5843 file, files, done);
5844 update_view_title(view);
5845 setsyx(cursor_y, cursor_x);
5846 doupdate();
5848 result = status_update_write(&io, line->data, line->type);
5850 string_copy(view->ref, buf);
5852 return io_done(&io) && result;
5855 static bool
5856 status_update(struct view *view)
5858 struct line *line = &view->line[view->lineno];
5860 assert(view->lines);
5862 if (!line->data) {
5863 /* This should work even for the "On branch" line. */
5864 if (line < view->line + view->lines && !line[1].data) {
5865 report("Nothing to update");
5866 return FALSE;
5869 if (!status_update_files(view, line + 1)) {
5870 report("Failed to update file status");
5871 return FALSE;
5874 } else if (!status_update_file(line->data, line->type)) {
5875 report("Failed to update file status");
5876 return FALSE;
5879 return TRUE;
5882 static bool
5883 status_revert(struct status *status, enum line_type type, bool has_none)
5885 if (!status || type != LINE_STAT_UNSTAGED) {
5886 if (type == LINE_STAT_STAGED) {
5887 report("Cannot revert changes to staged files");
5888 } else if (type == LINE_STAT_UNTRACKED) {
5889 report("Cannot revert changes to untracked files");
5890 } else if (has_none) {
5891 report("Nothing to revert");
5892 } else {
5893 report("Cannot revert changes to multiple files");
5896 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5897 char mode[10] = "100644";
5898 const char *reset_argv[] = {
5899 "git", "update-index", "--cacheinfo", mode,
5900 status->old.rev, status->old.name, NULL
5902 const char *checkout_argv[] = {
5903 "git", "checkout", "--", status->old.name, NULL
5906 if (status->status == 'U') {
5907 string_format(mode, "%5o", status->old.mode);
5909 if (status->old.mode == 0 && status->new.mode == 0) {
5910 reset_argv[2] = "--force-remove";
5911 reset_argv[3] = status->old.name;
5912 reset_argv[4] = NULL;
5915 if (!io_run_fg(reset_argv, opt_cdup))
5916 return FALSE;
5917 if (status->old.mode == 0 && status->new.mode == 0)
5918 return TRUE;
5921 return io_run_fg(checkout_argv, opt_cdup);
5924 return FALSE;
5927 static enum request
5928 status_request(struct view *view, enum request request, struct line *line)
5930 struct status *status = line->data;
5932 switch (request) {
5933 case REQ_STATUS_UPDATE:
5934 if (!status_update(view))
5935 return REQ_NONE;
5936 break;
5938 case REQ_STATUS_REVERT:
5939 if (!status_revert(status, line->type, status_has_none(view, line)))
5940 return REQ_NONE;
5941 break;
5943 case REQ_STATUS_MERGE:
5944 if (!status || status->status != 'U') {
5945 report("Merging only possible for files with unmerged status ('U').");
5946 return REQ_NONE;
5948 open_mergetool(status->new.name);
5949 break;
5951 case REQ_EDIT:
5952 if (!status)
5953 return request;
5954 if (status->status == 'D') {
5955 report("File has been deleted.");
5956 return REQ_NONE;
5959 open_editor(status->new.name);
5960 break;
5962 case REQ_VIEW_BLAME:
5963 if (status)
5964 opt_ref[0] = 0;
5965 return request;
5967 case REQ_ENTER:
5968 /* After returning the status view has been split to
5969 * show the stage view. No further reloading is
5970 * necessary. */
5971 return status_enter(view, line);
5973 case REQ_REFRESH:
5974 /* Simply reload the view. */
5975 break;
5977 default:
5978 return request;
5981 refresh_view(view);
5983 return REQ_NONE;
5986 static void
5987 status_select(struct view *view, struct line *line)
5989 struct status *status = line->data;
5990 char file[SIZEOF_STR] = "all files";
5991 const char *text;
5992 const char *key;
5994 if (status && !string_format(file, "'%s'", status->new.name))
5995 return;
5997 if (!status && line[1].type == LINE_STAT_NONE)
5998 line++;
6000 switch (line->type) {
6001 case LINE_STAT_STAGED:
6002 text = "Press %s to unstage %s for commit";
6003 break;
6005 case LINE_STAT_UNSTAGED:
6006 text = "Press %s to stage %s for commit";
6007 break;
6009 case LINE_STAT_UNTRACKED:
6010 text = "Press %s to stage %s for addition";
6011 break;
6013 case LINE_STAT_HEAD:
6014 case LINE_STAT_NONE:
6015 text = "Nothing to update";
6016 break;
6018 default:
6019 die("line type %d not handled in switch", line->type);
6022 if (status && status->status == 'U') {
6023 text = "Press %s to resolve conflict in %s";
6024 key = get_view_key(view, REQ_STATUS_MERGE);
6026 } else {
6027 key = get_view_key(view, REQ_STATUS_UPDATE);
6030 string_format(view->ref, text, key, file);
6031 if (status)
6032 string_copy(opt_file, status->new.name);
6035 static bool
6036 status_grep(struct view *view, struct line *line)
6038 struct status *status = line->data;
6040 if (status) {
6041 const char buf[2] = { status->status, 0 };
6042 const char *text[] = { status->new.name, buf, NULL };
6044 return grep_text(view, text);
6047 return FALSE;
6050 static struct view_ops status_ops = {
6051 "file",
6052 VIEW_CUSTOM_STATUS,
6054 status_open,
6055 NULL,
6056 status_draw,
6057 status_request,
6058 status_grep,
6059 status_select,
6063 struct stage_state {
6064 struct diff_state diff;
6065 size_t chunks;
6066 int *chunk;
6069 static bool
6070 stage_diff_write(struct io *io, struct line *line, struct line *end)
6072 while (line < end) {
6073 if (!io_write(io, line->data, strlen(line->data)) ||
6074 !io_write(io, "\n", 1))
6075 return FALSE;
6076 line++;
6077 if (line->type == LINE_DIFF_CHUNK ||
6078 line->type == LINE_DIFF_HEADER)
6079 break;
6082 return TRUE;
6085 static bool
6086 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6088 const char *apply_argv[SIZEOF_ARG] = {
6089 "git", "apply", "--whitespace=nowarn", NULL
6091 struct line *diff_hdr;
6092 struct io io;
6093 int argc = 3;
6095 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6096 if (!diff_hdr)
6097 return FALSE;
6099 if (!revert)
6100 apply_argv[argc++] = "--cached";
6101 if (line != NULL)
6102 apply_argv[argc++] = "--unidiff-zero";
6103 if (revert || stage_line_type == LINE_STAT_STAGED)
6104 apply_argv[argc++] = "-R";
6105 apply_argv[argc++] = "-";
6106 apply_argv[argc++] = NULL;
6107 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6108 return FALSE;
6110 if (line != NULL) {
6111 int lineno = 0;
6112 struct line *context = chunk + 1;
6113 const char *markers[] = {
6114 line->type == LINE_DIFF_DEL ? "" : ",0",
6115 line->type == LINE_DIFF_DEL ? ",0" : "",
6118 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6120 while (context < line) {
6121 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6122 break;
6123 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6124 lineno++;
6126 context++;
6129 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6130 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6131 lineno, markers[0], lineno, markers[1]) ||
6132 !stage_diff_write(&io, line, line + 1)) {
6133 chunk = NULL;
6135 } else {
6136 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6137 !stage_diff_write(&io, chunk, view->line + view->lines))
6138 chunk = NULL;
6141 io_done(&io);
6142 io_run_bg(update_index_argv);
6144 return chunk ? TRUE : FALSE;
6147 static bool
6148 stage_update(struct view *view, struct line *line, bool single)
6150 struct line *chunk = NULL;
6152 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6153 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6155 if (chunk) {
6156 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6157 report("Failed to apply chunk");
6158 return FALSE;
6161 } else if (!stage_status.status) {
6162 view = view->parent;
6164 for (line = view->line; line < view->line + view->lines; line++)
6165 if (line->type == stage_line_type)
6166 break;
6168 if (!status_update_files(view, line + 1)) {
6169 report("Failed to update files");
6170 return FALSE;
6173 } else if (!status_update_file(&stage_status, stage_line_type)) {
6174 report("Failed to update file");
6175 return FALSE;
6178 return TRUE;
6181 static bool
6182 stage_revert(struct view *view, struct line *line)
6184 struct line *chunk = NULL;
6186 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6187 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6189 if (chunk) {
6190 if (!prompt_yesno("Are you sure you want to revert changes?"))
6191 return FALSE;
6193 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6194 report("Failed to revert chunk");
6195 return FALSE;
6197 return TRUE;
6199 } else {
6200 return status_revert(stage_status.status ? &stage_status : NULL,
6201 stage_line_type, FALSE);
6206 static void
6207 stage_next(struct view *view, struct line *line)
6209 struct stage_state *state = view->private;
6210 int i;
6212 if (!state->chunks) {
6213 for (line = view->line; line < view->line + view->lines; line++) {
6214 if (line->type != LINE_DIFF_CHUNK)
6215 continue;
6217 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6218 report("Allocation failure");
6219 return;
6222 state->chunk[state->chunks++] = line - view->line;
6226 for (i = 0; i < state->chunks; i++) {
6227 if (state->chunk[i] > view->lineno) {
6228 do_scroll_view(view, state->chunk[i] - view->lineno);
6229 report("Chunk %d of %d", i + 1, state->chunks);
6230 return;
6234 report("No next chunk found");
6237 static enum request
6238 stage_request(struct view *view, enum request request, struct line *line)
6240 switch (request) {
6241 case REQ_STATUS_UPDATE:
6242 if (!stage_update(view, line, FALSE))
6243 return REQ_NONE;
6244 break;
6246 case REQ_STATUS_REVERT:
6247 if (!stage_revert(view, line))
6248 return REQ_NONE;
6249 break;
6251 case REQ_STAGE_UPDATE_LINE:
6252 if (stage_line_type == LINE_STAT_UNTRACKED ||
6253 stage_status.status == 'A') {
6254 report("Staging single lines is not supported for new files");
6255 return REQ_NONE;
6257 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6258 report("Please select a change to stage");
6259 return REQ_NONE;
6261 if (!stage_update(view, line, TRUE))
6262 return REQ_NONE;
6263 break;
6265 case REQ_STAGE_NEXT:
6266 if (stage_line_type == LINE_STAT_UNTRACKED) {
6267 report("File is untracked; press %s to add",
6268 get_view_key(view, REQ_STATUS_UPDATE));
6269 return REQ_NONE;
6271 stage_next(view, line);
6272 return REQ_NONE;
6274 case REQ_EDIT:
6275 if (!stage_status.new.name[0])
6276 return request;
6277 if (stage_status.status == 'D') {
6278 report("File has been deleted.");
6279 return REQ_NONE;
6282 open_editor(stage_status.new.name);
6283 break;
6285 case REQ_REFRESH:
6286 /* Reload everything ... */
6287 break;
6289 case REQ_VIEW_BLAME:
6290 if (stage_status.new.name[0]) {
6291 string_copy(opt_file, stage_status.new.name);
6292 opt_ref[0] = 0;
6294 return request;
6296 case REQ_ENTER:
6297 return diff_common_enter(view, request, line);
6299 case REQ_DIFF_CONTEXT_UP:
6300 case REQ_DIFF_CONTEXT_DOWN:
6301 if (!update_diff_context(request))
6302 return REQ_NONE;
6303 break;
6305 default:
6306 return request;
6309 refresh_view(view->parent);
6311 /* Check whether the staged entry still exists, and close the
6312 * stage view if it doesn't. */
6313 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6314 status_restore(view->parent);
6315 return REQ_VIEW_CLOSE;
6318 refresh_view(view);
6320 return REQ_NONE;
6323 static bool
6324 stage_open(struct view *view, enum open_flags flags)
6326 static const char *no_head_diff_argv[] = {
6327 "git", "diff", "--no-color", "--patch-with-stat",
6328 opt_diff_context_arg, opt_ignore_space_arg,
6329 "--", "/dev/null", stage_status.new.name, NULL
6331 static const char *index_show_argv[] = {
6332 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6333 "--cached", opt_diff_context_arg, opt_ignore_space_arg,
6334 "HEAD", "--",
6335 stage_status.old.name, stage_status.new.name, NULL
6337 static const char *files_show_argv[] = {
6338 "git", "diff-files", "--root", "--patch-with-stat", "-C", "-M",
6339 opt_diff_context_arg, opt_ignore_space_arg, "--",
6340 stage_status.old.name, stage_status.new.name, NULL
6342 /* Diffs for unmerged entries are empty when passing the new
6343 * path, so leave out the new path. */
6344 static const char *files_unmerged_argv[] = {
6345 "git", "diff-files", "--root", "--patch-with-stat", "-C", "-M",
6346 opt_diff_context_arg, opt_ignore_space_arg, "--",
6347 stage_status.old.name, NULL
6349 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6350 const char **argv = NULL;
6351 const char *info;
6353 switch (stage_line_type) {
6354 case LINE_STAT_STAGED:
6355 if (is_initial_commit()) {
6356 argv = no_head_diff_argv;
6357 } else {
6358 argv = index_show_argv;
6360 if (stage_status.status)
6361 info = "Staged changes to %s";
6362 else
6363 info = "Staged changes";
6364 break;
6366 case LINE_STAT_UNSTAGED:
6367 if (stage_status.status != 'U')
6368 argv = files_show_argv;
6369 else
6370 argv = files_unmerged_argv;
6371 if (stage_status.status)
6372 info = "Unstaged changes to %s";
6373 else
6374 info = "Unstaged changes";
6375 break;
6377 case LINE_STAT_UNTRACKED:
6378 info = "Untracked file %s";
6379 argv = file_argv;
6380 break;
6382 case LINE_STAT_HEAD:
6383 default:
6384 die("line type %d not handled in switch", stage_line_type);
6387 string_format(view->ref, info, stage_status.new.name);
6388 view->vid[0] = 0;
6389 view->dir = opt_cdup;
6390 return argv_copy(&view->argv, argv)
6391 && begin_update(view, NULL, NULL, flags);
6394 static bool
6395 stage_read(struct view *view, char *data)
6397 struct stage_state *state = view->private;
6399 if (data && diff_common_read(view, data, &state->diff))
6400 return TRUE;
6402 return pager_read(view, data);
6405 static struct view_ops stage_ops = {
6406 "line",
6407 VIEW_DIFF_LIKE,
6408 sizeof(struct stage_state),
6409 stage_open,
6410 stage_read,
6411 diff_common_draw,
6412 stage_request,
6413 pager_grep,
6414 pager_select,
6419 * Revision graph
6422 static const enum line_type graph_colors[] = {
6423 LINE_PALETTE_0,
6424 LINE_PALETTE_1,
6425 LINE_PALETTE_2,
6426 LINE_PALETTE_3,
6427 LINE_PALETTE_4,
6428 LINE_PALETTE_5,
6429 LINE_PALETTE_6,
6432 static enum line_type get_graph_color(struct graph_symbol *symbol)
6434 if (symbol->commit)
6435 return LINE_GRAPH_COMMIT;
6436 assert(symbol->color < ARRAY_SIZE(graph_colors));
6437 return graph_colors[symbol->color];
6440 static bool
6441 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6443 const char *chars = graph_symbol_to_utf8(symbol);
6445 return draw_text(view, color, chars + !!first);
6448 static bool
6449 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6451 const char *chars = graph_symbol_to_ascii(symbol);
6453 return draw_text(view, color, chars + !!first);
6456 static bool
6457 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6459 const chtype *chars = graph_symbol_to_chtype(symbol);
6461 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6464 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6466 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6468 static const draw_graph_fn fns[] = {
6469 draw_graph_ascii,
6470 draw_graph_chtype,
6471 draw_graph_utf8
6473 draw_graph_fn fn = fns[opt_line_graphics];
6474 int i;
6476 for (i = 0; i < canvas->size; i++) {
6477 struct graph_symbol *symbol = &canvas->symbols[i];
6478 enum line_type color = get_graph_color(symbol);
6480 if (fn(view, symbol, color, i == 0))
6481 return TRUE;
6484 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6488 * Main view backend
6491 struct commit {
6492 char id[SIZEOF_REV]; /* SHA1 ID. */
6493 char title[128]; /* First line of the commit message. */
6494 const char *author; /* Author of the commit. */
6495 struct time time; /* Date from the author ident. */
6496 struct ref_list *refs; /* Repository references. */
6497 struct graph_canvas graph; /* Ancestry chain graphics. */
6500 static bool
6501 main_open(struct view *view, enum open_flags flags)
6503 static const char *main_argv[] = {
6504 "git", "log", "--no-color", "--pretty=raw", "--parents",
6505 "--topo-order", "%(diffargs)", "%(revargs)",
6506 "--", "%(fileargs)", NULL
6509 return begin_update(view, NULL, main_argv, flags);
6512 static bool
6513 main_draw(struct view *view, struct line *line, unsigned int lineno)
6515 struct commit *commit = line->data;
6517 if (!commit->author)
6518 return FALSE;
6520 if (opt_line_number && draw_lineno(view, lineno))
6521 return TRUE;
6523 if (draw_date(view, &commit->time))
6524 return TRUE;
6526 if (draw_author(view, commit->author))
6527 return TRUE;
6529 if (opt_rev_graph && draw_graph(view, &commit->graph))
6530 return TRUE;
6532 if (draw_refs(view, commit->refs))
6533 return TRUE;
6535 draw_text(view, LINE_DEFAULT, commit->title);
6536 return TRUE;
6539 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6540 static bool
6541 main_read(struct view *view, char *line)
6543 struct graph *graph = view->private;
6544 enum line_type type;
6545 struct commit *commit;
6547 if (!line) {
6548 if (!view->lines && !view->prev)
6549 die("No revisions match the given arguments.");
6550 if (view->lines > 0) {
6551 commit = view->line[view->lines - 1].data;
6552 view->line[view->lines - 1].dirty = 1;
6553 if (!commit->author) {
6554 view->lines--;
6555 free(commit);
6559 done_graph(graph);
6560 return TRUE;
6563 type = get_line_type(line);
6564 if (type == LINE_COMMIT) {
6565 bool is_boundary;
6567 commit = calloc(1, sizeof(struct commit));
6568 if (!commit)
6569 return FALSE;
6571 line += STRING_SIZE("commit ");
6572 is_boundary = *line == '-';
6573 if (is_boundary)
6574 line++;
6576 string_copy_rev(commit->id, line);
6577 commit->refs = get_ref_list(commit->id);
6578 add_line_data(view, commit, LINE_MAIN_COMMIT);
6579 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6580 return TRUE;
6583 if (!view->lines)
6584 return TRUE;
6585 commit = view->line[view->lines - 1].data;
6587 switch (type) {
6588 case LINE_PARENT:
6589 if (!graph->has_parents)
6590 graph_add_parent(graph, line + STRING_SIZE("parent "));
6591 break;
6593 case LINE_AUTHOR:
6594 parse_author_line(line + STRING_SIZE("author "),
6595 &commit->author, &commit->time);
6596 graph_render_parents(graph);
6597 break;
6599 default:
6600 /* Fill in the commit title if it has not already been set. */
6601 if (commit->title[0])
6602 break;
6604 /* Require titles to start with a non-space character at the
6605 * offset used by git log. */
6606 if (strncmp(line, " ", 4))
6607 break;
6608 line += 4;
6609 /* Well, if the title starts with a whitespace character,
6610 * try to be forgiving. Otherwise we end up with no title. */
6611 while (isspace(*line))
6612 line++;
6613 if (*line == '\0')
6614 break;
6615 /* FIXME: More graceful handling of titles; append "..." to
6616 * shortened titles, etc. */
6618 string_expand(commit->title, sizeof(commit->title), line, 1);
6619 view->line[view->lines - 1].dirty = 1;
6622 return TRUE;
6625 static enum request
6626 main_request(struct view *view, enum request request, struct line *line)
6628 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6630 switch (request) {
6631 case REQ_ENTER:
6632 if (view_is_displayed(view) && display[0] != view)
6633 maximize_view(view, TRUE);
6634 open_view(view, REQ_VIEW_DIFF, flags);
6635 break;
6636 case REQ_REFRESH:
6637 load_refs();
6638 refresh_view(view);
6639 break;
6641 case REQ_JUMP_COMMIT:
6643 int lineno;
6645 for (lineno = 0; lineno < view->lines; lineno++) {
6646 struct commit *commit = view->line[lineno].data;
6648 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6649 select_view_line(view, lineno);
6650 report("");
6651 return REQ_NONE;
6655 report("Unable to find commit '%s'", opt_search);
6656 break;
6658 default:
6659 return request;
6662 return REQ_NONE;
6665 static bool
6666 grep_refs(struct ref_list *list, regex_t *regex)
6668 regmatch_t pmatch;
6669 size_t i;
6671 if (!opt_show_refs || !list)
6672 return FALSE;
6674 for (i = 0; i < list->size; i++) {
6675 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6676 return TRUE;
6679 return FALSE;
6682 static bool
6683 main_grep(struct view *view, struct line *line)
6685 struct commit *commit = line->data;
6686 const char *text[] = {
6687 commit->title,
6688 mkauthor(commit->author, opt_author_cols, opt_author),
6689 mkdate(&commit->time, opt_date),
6690 NULL
6693 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6696 static void
6697 main_select(struct view *view, struct line *line)
6699 struct commit *commit = line->data;
6701 string_copy_rev(view->ref, commit->id);
6702 string_copy_rev(ref_commit, view->ref);
6705 static struct view_ops main_ops = {
6706 "commit",
6707 VIEW_NO_FLAGS,
6708 sizeof(struct graph),
6709 main_open,
6710 main_read,
6711 main_draw,
6712 main_request,
6713 main_grep,
6714 main_select,
6719 * Status management
6722 /* Whether or not the curses interface has been initialized. */
6723 static bool cursed = FALSE;
6725 /* Terminal hacks and workarounds. */
6726 static bool use_scroll_redrawwin;
6727 static bool use_scroll_status_wclear;
6729 /* The status window is used for polling keystrokes. */
6730 static WINDOW *status_win;
6732 /* Reading from the prompt? */
6733 static bool input_mode = FALSE;
6735 static bool status_empty = FALSE;
6737 /* Update status and title window. */
6738 static void
6739 report(const char *msg, ...)
6741 struct view *view = display[current_view];
6743 if (input_mode)
6744 return;
6746 if (!view) {
6747 char buf[SIZEOF_STR];
6748 int retval;
6750 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6751 die("%s", buf);
6754 if (!status_empty || *msg) {
6755 va_list args;
6757 va_start(args, msg);
6759 wmove(status_win, 0, 0);
6760 if (view->has_scrolled && use_scroll_status_wclear)
6761 wclear(status_win);
6762 if (*msg) {
6763 vwprintw(status_win, msg, args);
6764 status_empty = FALSE;
6765 } else {
6766 status_empty = TRUE;
6768 wclrtoeol(status_win);
6769 wnoutrefresh(status_win);
6771 va_end(args);
6774 update_view_title(view);
6777 static void
6778 init_display(void)
6780 const char *term;
6781 int x, y;
6783 /* Initialize the curses library */
6784 if (isatty(STDIN_FILENO)) {
6785 cursed = !!initscr();
6786 opt_tty = stdin;
6787 } else {
6788 /* Leave stdin and stdout alone when acting as a pager. */
6789 opt_tty = fopen("/dev/tty", "r+");
6790 if (!opt_tty)
6791 die("Failed to open /dev/tty");
6792 cursed = !!newterm(NULL, opt_tty, opt_tty);
6795 if (!cursed)
6796 die("Failed to initialize curses");
6798 nonl(); /* Disable conversion and detect newlines from input. */
6799 cbreak(); /* Take input chars one at a time, no wait for \n */
6800 noecho(); /* Don't echo input */
6801 leaveok(stdscr, FALSE);
6803 if (has_colors())
6804 init_colors();
6806 getmaxyx(stdscr, y, x);
6807 status_win = newwin(1, x, y - 1, 0);
6808 if (!status_win)
6809 die("Failed to create status window");
6811 /* Enable keyboard mapping */
6812 keypad(status_win, TRUE);
6813 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6815 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6816 set_tabsize(opt_tab_size);
6817 #else
6818 TABSIZE = opt_tab_size;
6819 #endif
6821 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6822 if (term && !strcmp(term, "gnome-terminal")) {
6823 /* In the gnome-terminal-emulator, the message from
6824 * scrolling up one line when impossible followed by
6825 * scrolling down one line causes corruption of the
6826 * status line. This is fixed by calling wclear. */
6827 use_scroll_status_wclear = TRUE;
6828 use_scroll_redrawwin = FALSE;
6830 } else if (term && !strcmp(term, "xrvt-xpm")) {
6831 /* No problems with full optimizations in xrvt-(unicode)
6832 * and aterm. */
6833 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6835 } else {
6836 /* When scrolling in (u)xterm the last line in the
6837 * scrolling direction will update slowly. */
6838 use_scroll_redrawwin = TRUE;
6839 use_scroll_status_wclear = FALSE;
6843 static int
6844 get_input(int prompt_position)
6846 struct view *view;
6847 int i, key, cursor_y, cursor_x;
6849 if (prompt_position)
6850 input_mode = TRUE;
6852 while (TRUE) {
6853 bool loading = FALSE;
6855 foreach_view (view, i) {
6856 update_view(view);
6857 if (view_is_displayed(view) && view->has_scrolled &&
6858 use_scroll_redrawwin)
6859 redrawwin(view->win);
6860 view->has_scrolled = FALSE;
6861 if (view->pipe)
6862 loading = TRUE;
6865 /* Update the cursor position. */
6866 if (prompt_position) {
6867 getbegyx(status_win, cursor_y, cursor_x);
6868 cursor_x = prompt_position;
6869 } else {
6870 view = display[current_view];
6871 getbegyx(view->win, cursor_y, cursor_x);
6872 cursor_x = view->width - 1;
6873 cursor_y += view->lineno - view->offset;
6875 setsyx(cursor_y, cursor_x);
6877 /* Refresh, accept single keystroke of input */
6878 doupdate();
6879 nodelay(status_win, loading);
6880 key = wgetch(status_win);
6882 /* wgetch() with nodelay() enabled returns ERR when
6883 * there's no input. */
6884 if (key == ERR) {
6886 } else if (key == KEY_RESIZE) {
6887 int height, width;
6889 getmaxyx(stdscr, height, width);
6891 wresize(status_win, 1, width);
6892 mvwin(status_win, height - 1, 0);
6893 wnoutrefresh(status_win);
6894 resize_display();
6895 redraw_display(TRUE);
6897 } else {
6898 input_mode = FALSE;
6899 if (key == erasechar())
6900 key = KEY_BACKSPACE;
6901 return key;
6906 static char *
6907 prompt_input(const char *prompt, input_handler handler, void *data)
6909 enum input_status status = INPUT_OK;
6910 static char buf[SIZEOF_STR];
6911 size_t pos = 0;
6913 buf[pos] = 0;
6915 while (status == INPUT_OK || status == INPUT_SKIP) {
6916 int key;
6918 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6919 wclrtoeol(status_win);
6921 key = get_input(pos + 1);
6922 switch (key) {
6923 case KEY_RETURN:
6924 case KEY_ENTER:
6925 case '\n':
6926 status = pos ? INPUT_STOP : INPUT_CANCEL;
6927 break;
6929 case KEY_BACKSPACE:
6930 if (pos > 0)
6931 buf[--pos] = 0;
6932 else
6933 status = INPUT_CANCEL;
6934 break;
6936 case KEY_ESC:
6937 status = INPUT_CANCEL;
6938 break;
6940 default:
6941 if (pos >= sizeof(buf)) {
6942 report("Input string too long");
6943 return NULL;
6946 status = handler(data, buf, key);
6947 if (status == INPUT_OK)
6948 buf[pos++] = (char) key;
6952 /* Clear the status window */
6953 status_empty = FALSE;
6954 report("");
6956 if (status == INPUT_CANCEL)
6957 return NULL;
6959 buf[pos++] = 0;
6961 return buf;
6964 static enum input_status
6965 prompt_yesno_handler(void *data, char *buf, int c)
6967 if (c == 'y' || c == 'Y')
6968 return INPUT_STOP;
6969 if (c == 'n' || c == 'N')
6970 return INPUT_CANCEL;
6971 return INPUT_SKIP;
6974 static bool
6975 prompt_yesno(const char *prompt)
6977 char prompt2[SIZEOF_STR];
6979 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6980 return FALSE;
6982 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6985 static enum input_status
6986 read_prompt_handler(void *data, char *buf, int c)
6988 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6991 static char *
6992 read_prompt(const char *prompt)
6994 return prompt_input(prompt, read_prompt_handler, NULL);
6997 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6999 enum input_status status = INPUT_OK;
7000 int size = 0;
7002 while (items[size].text)
7003 size++;
7005 while (status == INPUT_OK) {
7006 const struct menu_item *item = &items[*selected];
7007 int key;
7008 int i;
7010 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7011 prompt, *selected + 1, size);
7012 if (item->hotkey)
7013 wprintw(status_win, "[%c] ", (char) item->hotkey);
7014 wprintw(status_win, "%s", item->text);
7015 wclrtoeol(status_win);
7017 key = get_input(COLS - 1);
7018 switch (key) {
7019 case KEY_RETURN:
7020 case KEY_ENTER:
7021 case '\n':
7022 status = INPUT_STOP;
7023 break;
7025 case KEY_LEFT:
7026 case KEY_UP:
7027 *selected = *selected - 1;
7028 if (*selected < 0)
7029 *selected = size - 1;
7030 break;
7032 case KEY_RIGHT:
7033 case KEY_DOWN:
7034 *selected = (*selected + 1) % size;
7035 break;
7037 case KEY_ESC:
7038 status = INPUT_CANCEL;
7039 break;
7041 default:
7042 for (i = 0; items[i].text; i++)
7043 if (items[i].hotkey == key) {
7044 *selected = i;
7045 status = INPUT_STOP;
7046 break;
7051 /* Clear the status window */
7052 status_empty = FALSE;
7053 report("");
7055 return status != INPUT_CANCEL;
7059 * Repository properties
7062 static struct ref **refs = NULL;
7063 static size_t refs_size = 0;
7064 static struct ref *refs_head = NULL;
7066 static struct ref_list **ref_lists = NULL;
7067 static size_t ref_lists_size = 0;
7069 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7070 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7071 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7073 static int
7074 compare_refs(const void *ref1_, const void *ref2_)
7076 const struct ref *ref1 = *(const struct ref **)ref1_;
7077 const struct ref *ref2 = *(const struct ref **)ref2_;
7079 if (ref1->tag != ref2->tag)
7080 return ref2->tag - ref1->tag;
7081 if (ref1->ltag != ref2->ltag)
7082 return ref2->ltag - ref1->ltag;
7083 if (ref1->head != ref2->head)
7084 return ref2->head - ref1->head;
7085 if (ref1->tracked != ref2->tracked)
7086 return ref2->tracked - ref1->tracked;
7087 if (ref1->replace != ref2->replace)
7088 return ref2->replace - ref1->replace;
7089 /* Order remotes last. */
7090 if (ref1->remote != ref2->remote)
7091 return ref1->remote - ref2->remote;
7092 return strcmp(ref1->name, ref2->name);
7095 static void
7096 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7098 size_t i;
7100 for (i = 0; i < refs_size; i++)
7101 if (!visitor(data, refs[i]))
7102 break;
7105 static struct ref *
7106 get_ref_head()
7108 return refs_head;
7111 static struct ref_list *
7112 get_ref_list(const char *id)
7114 struct ref_list *list;
7115 size_t i;
7117 for (i = 0; i < ref_lists_size; i++)
7118 if (!strcmp(id, ref_lists[i]->id))
7119 return ref_lists[i];
7121 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7122 return NULL;
7123 list = calloc(1, sizeof(*list));
7124 if (!list)
7125 return NULL;
7127 for (i = 0; i < refs_size; i++) {
7128 if (!strcmp(id, refs[i]->id) &&
7129 realloc_refs_list(&list->refs, list->size, 1))
7130 list->refs[list->size++] = refs[i];
7133 if (!list->refs) {
7134 free(list);
7135 return NULL;
7138 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7139 ref_lists[ref_lists_size++] = list;
7140 return list;
7143 static int
7144 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7146 struct ref *ref = NULL;
7147 bool tag = FALSE;
7148 bool ltag = FALSE;
7149 bool remote = FALSE;
7150 bool replace = FALSE;
7151 bool tracked = FALSE;
7152 bool head = FALSE;
7153 int from = 0, to = refs_size - 1;
7155 if (!prefixcmp(name, "refs/tags/")) {
7156 if (!suffixcmp(name, namelen, "^{}")) {
7157 namelen -= 3;
7158 name[namelen] = 0;
7159 } else {
7160 ltag = TRUE;
7163 tag = TRUE;
7164 namelen -= STRING_SIZE("refs/tags/");
7165 name += STRING_SIZE("refs/tags/");
7167 } else if (!prefixcmp(name, "refs/remotes/")) {
7168 remote = TRUE;
7169 namelen -= STRING_SIZE("refs/remotes/");
7170 name += STRING_SIZE("refs/remotes/");
7171 tracked = !strcmp(opt_remote, name);
7173 } else if (!prefixcmp(name, "refs/replace/")) {
7174 replace = TRUE;
7175 id = name + strlen("refs/replace/");
7176 idlen = namelen - strlen("refs/replace/");
7177 name = "replaced";
7178 namelen = strlen(name);
7180 } else if (!prefixcmp(name, "refs/heads/")) {
7181 namelen -= STRING_SIZE("refs/heads/");
7182 name += STRING_SIZE("refs/heads/");
7183 if (strlen(opt_head) == namelen
7184 && !strncmp(opt_head, name, namelen))
7185 return OK;
7187 } else if (!strcmp(name, "HEAD")) {
7188 head = TRUE;
7189 if (*opt_head) {
7190 namelen = strlen(opt_head);
7191 name = opt_head;
7195 /* If we are reloading or it's an annotated tag, replace the
7196 * previous SHA1 with the resolved commit id; relies on the fact
7197 * git-ls-remote lists the commit id of an annotated tag right
7198 * before the commit id it points to. */
7199 while ((from <= to) && !replace) {
7200 size_t pos = (to + from) / 2;
7201 int cmp = strcmp(name, refs[pos]->name);
7203 if (!cmp) {
7204 ref = refs[pos];
7205 break;
7208 if (cmp < 0)
7209 to = pos - 1;
7210 else
7211 from = pos + 1;
7214 if (!ref) {
7215 if (!realloc_refs(&refs, refs_size, 1))
7216 return ERR;
7217 ref = calloc(1, sizeof(*ref) + namelen);
7218 if (!ref)
7219 return ERR;
7220 memmove(refs + from + 1, refs + from,
7221 (refs_size - from) * sizeof(*refs));
7222 refs[from] = ref;
7223 strncpy(ref->name, name, namelen);
7224 refs_size++;
7227 ref->head = head;
7228 ref->tag = tag;
7229 ref->ltag = ltag;
7230 ref->remote = remote;
7231 ref->replace = replace;
7232 ref->tracked = tracked;
7233 string_copy_rev(ref->id, id);
7235 if (head)
7236 refs_head = ref;
7237 return OK;
7240 static int
7241 load_refs(void)
7243 const char *head_argv[] = {
7244 "git", "symbolic-ref", "HEAD", NULL
7246 static const char *ls_remote_argv[SIZEOF_ARG] = {
7247 "git", "ls-remote", opt_git_dir, NULL
7249 static bool init = FALSE;
7250 size_t i;
7252 if (!init) {
7253 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7254 die("TIG_LS_REMOTE contains too many arguments");
7255 init = TRUE;
7258 if (!*opt_git_dir)
7259 return OK;
7261 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7262 !prefixcmp(opt_head, "refs/heads/")) {
7263 char *offset = opt_head + STRING_SIZE("refs/heads/");
7265 memmove(opt_head, offset, strlen(offset) + 1);
7268 refs_head = NULL;
7269 for (i = 0; i < refs_size; i++)
7270 refs[i]->id[0] = 0;
7272 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7273 return ERR;
7275 /* Update the ref lists to reflect changes. */
7276 for (i = 0; i < ref_lists_size; i++) {
7277 struct ref_list *list = ref_lists[i];
7278 size_t old, new;
7280 for (old = new = 0; old < list->size; old++)
7281 if (!strcmp(list->id, list->refs[old]->id))
7282 list->refs[new++] = list->refs[old];
7283 list->size = new;
7286 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7288 return OK;
7291 static void
7292 set_remote_branch(const char *name, const char *value, size_t valuelen)
7294 if (!strcmp(name, ".remote")) {
7295 string_ncopy(opt_remote, value, valuelen);
7297 } else if (*opt_remote && !strcmp(name, ".merge")) {
7298 size_t from = strlen(opt_remote);
7300 if (!prefixcmp(value, "refs/heads/"))
7301 value += STRING_SIZE("refs/heads/");
7303 if (!string_format_from(opt_remote, &from, "/%s", value))
7304 opt_remote[0] = 0;
7308 static void
7309 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7311 const char *argv[SIZEOF_ARG] = { name, "=" };
7312 int argc = 1 + (cmd == option_set_command);
7313 enum option_code error;
7315 if (!argv_from_string(argv, &argc, value))
7316 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7317 else
7318 error = cmd(argc, argv);
7320 if (error != OPT_OK)
7321 warn("Option 'tig.%s': %s", name, option_errors[error]);
7324 static bool
7325 set_environment_variable(const char *name, const char *value)
7327 size_t len = strlen(name) + 1 + strlen(value) + 1;
7328 char *env = malloc(len);
7330 if (env &&
7331 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7332 putenv(env) == 0)
7333 return TRUE;
7334 free(env);
7335 return FALSE;
7338 static void
7339 set_work_tree(const char *value)
7341 char cwd[SIZEOF_STR];
7343 if (!getcwd(cwd, sizeof(cwd)))
7344 die("Failed to get cwd path: %s", strerror(errno));
7345 if (chdir(opt_git_dir) < 0)
7346 die("Failed to chdir(%s): %s", strerror(errno));
7347 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7348 die("Failed to get git path: %s", strerror(errno));
7349 if (chdir(cwd) < 0)
7350 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7351 if (chdir(value) < 0)
7352 die("Failed to chdir(%s): %s", value, strerror(errno));
7353 if (!getcwd(cwd, sizeof(cwd)))
7354 die("Failed to get cwd path: %s", strerror(errno));
7355 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7356 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7357 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7358 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7359 opt_is_inside_work_tree = TRUE;
7362 static int
7363 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7365 if (!strcmp(name, "i18n.commitencoding"))
7366 string_ncopy(opt_encoding, value, valuelen);
7368 else if (!strcmp(name, "core.editor"))
7369 string_ncopy(opt_editor, value, valuelen);
7371 else if (!strcmp(name, "core.worktree"))
7372 set_work_tree(value);
7374 else if (!prefixcmp(name, "tig.color."))
7375 set_repo_config_option(name + 10, value, option_color_command);
7377 else if (!prefixcmp(name, "tig.bind."))
7378 set_repo_config_option(name + 9, value, option_bind_command);
7380 else if (!prefixcmp(name, "tig."))
7381 set_repo_config_option(name + 4, value, option_set_command);
7383 else if (*opt_head && !prefixcmp(name, "branch.") &&
7384 !strncmp(name + 7, opt_head, strlen(opt_head)))
7385 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7387 return OK;
7390 static int
7391 load_git_config(void)
7393 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7395 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7398 static int
7399 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7401 if (!opt_git_dir[0]) {
7402 string_ncopy(opt_git_dir, name, namelen);
7404 } else if (opt_is_inside_work_tree == -1) {
7405 /* This can be 3 different values depending on the
7406 * version of git being used. If git-rev-parse does not
7407 * understand --is-inside-work-tree it will simply echo
7408 * the option else either "true" or "false" is printed.
7409 * Default to true for the unknown case. */
7410 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7412 } else if (*name == '.') {
7413 string_ncopy(opt_cdup, name, namelen);
7415 } else {
7416 string_ncopy(opt_prefix, name, namelen);
7419 return OK;
7422 static int
7423 load_repo_info(void)
7425 const char *rev_parse_argv[] = {
7426 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7427 "--show-cdup", "--show-prefix", NULL
7430 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7435 * Main
7438 static const char usage[] =
7439 "tig " TIG_VERSION " (" __DATE__ ")\n"
7440 "\n"
7441 "Usage: tig [options] [revs] [--] [paths]\n"
7442 " or: tig show [options] [revs] [--] [paths]\n"
7443 " or: tig blame [options] [rev] [--] path\n"
7444 " or: tig status\n"
7445 " or: tig < [git command output]\n"
7446 "\n"
7447 "Options:\n"
7448 " +<number> Select line <number> in the first view\n"
7449 " -v, --version Show version and exit\n"
7450 " -h, --help Show help message and exit";
7452 static void __NORETURN
7453 quit(int sig)
7455 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7456 if (cursed)
7457 endwin();
7458 exit(0);
7461 static void __NORETURN
7462 die(const char *err, ...)
7464 va_list args;
7466 endwin();
7468 va_start(args, err);
7469 fputs("tig: ", stderr);
7470 vfprintf(stderr, err, args);
7471 fputs("\n", stderr);
7472 va_end(args);
7474 exit(1);
7477 static void
7478 warn(const char *msg, ...)
7480 va_list args;
7482 va_start(args, msg);
7483 fputs("tig warning: ", stderr);
7484 vfprintf(stderr, msg, args);
7485 fputs("\n", stderr);
7486 va_end(args);
7489 static int
7490 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7492 const char ***filter_args = data;
7494 return argv_append(filter_args, name) ? OK : ERR;
7497 static void
7498 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7500 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7501 const char **all_argv = NULL;
7503 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7504 !argv_append_array(&all_argv, argv) ||
7505 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7506 die("Failed to split arguments");
7507 argv_free(all_argv);
7508 free(all_argv);
7511 static void
7512 filter_options(const char *argv[], bool blame)
7514 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7516 if (blame)
7517 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7518 else
7519 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7521 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7524 static enum request
7525 parse_options(int argc, const char *argv[])
7527 enum request request = REQ_VIEW_MAIN;
7528 const char *subcommand;
7529 bool seen_dashdash = FALSE;
7530 const char **filter_argv = NULL;
7531 int i;
7533 if (!isatty(STDIN_FILENO))
7534 return REQ_VIEW_PAGER;
7536 if (argc <= 1)
7537 return REQ_VIEW_MAIN;
7539 subcommand = argv[1];
7540 if (!strcmp(subcommand, "status")) {
7541 if (argc > 2)
7542 warn("ignoring arguments after `%s'", subcommand);
7543 return REQ_VIEW_STATUS;
7545 } else if (!strcmp(subcommand, "blame")) {
7546 request = REQ_VIEW_BLAME;
7548 } else if (!strcmp(subcommand, "show")) {
7549 request = REQ_VIEW_DIFF;
7551 } else {
7552 subcommand = NULL;
7555 for (i = 1 + !!subcommand; i < argc; i++) {
7556 const char *opt = argv[i];
7558 // stop parsing our options after -- and let rev-parse handle the rest
7559 if (!seen_dashdash) {
7560 if (!strcmp(opt, "--")) {
7561 seen_dashdash = TRUE;
7562 continue;
7564 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7565 printf("tig version %s\n", TIG_VERSION);
7566 quit(0);
7568 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7569 printf("%s\n", usage);
7570 quit(0);
7572 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7573 opt_lineno = atoi(opt + 1);
7574 continue;
7579 if (!argv_append(&filter_argv, opt))
7580 die("command too long");
7583 if (filter_argv)
7584 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7586 /* Finish validating and setting up blame options */
7587 if (request == REQ_VIEW_BLAME) {
7588 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7589 die("invalid number of options to blame\n\n%s", usage);
7591 if (opt_rev_argv) {
7592 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7595 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7598 return request;
7602 main(int argc, const char *argv[])
7604 const char *codeset = ENCODING_UTF8;
7605 enum request request = parse_options(argc, argv);
7606 struct view *view;
7608 signal(SIGINT, quit);
7609 signal(SIGPIPE, SIG_IGN);
7611 if (setlocale(LC_ALL, "")) {
7612 codeset = nl_langinfo(CODESET);
7615 if (load_repo_info() == ERR)
7616 die("Failed to load repo info.");
7618 if (load_options() == ERR)
7619 die("Failed to load user config.");
7621 if (load_git_config() == ERR)
7622 die("Failed to load repo config.");
7624 /* Require a git repository unless when running in pager mode. */
7625 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7626 die("Not a git repository");
7628 if (*opt_encoding && strcmp(opt_encoding, ENCODING_UTF8)) {
7629 opt_iconv_in = iconv_open(ENCODING_UTF8, opt_encoding);
7630 if (opt_iconv_in == ICONV_NONE)
7631 die("Failed to initialize character set conversion");
7634 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7635 char translit[SIZEOF_STR];
7637 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7638 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7639 else
7640 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7641 if (opt_iconv_out == ICONV_NONE)
7642 die("Failed to initialize character set conversion");
7645 if (load_refs() == ERR)
7646 die("Failed to load refs.");
7648 init_display();
7650 while (view_driver(display[current_view], request)) {
7651 int key = get_input(0);
7653 view = display[current_view];
7654 request = get_keybinding(view->keymap, key);
7656 /* Some low-level request handling. This keeps access to
7657 * status_win restricted. */
7658 switch (request) {
7659 case REQ_NONE:
7660 report("Unknown key, press %s for help",
7661 get_view_key(view, REQ_VIEW_HELP));
7662 break;
7663 case REQ_PROMPT:
7665 char *cmd = read_prompt(":");
7667 if (cmd && string_isnumber(cmd)) {
7668 int lineno = view->lineno + 1;
7670 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7671 select_view_line(view, lineno - 1);
7672 report("");
7673 } else {
7674 report("Unable to parse '%s' as a line number", cmd);
7676 } else if (cmd && iscommit(cmd)) {
7677 string_ncopy(opt_search, cmd, strlen(cmd));
7679 request = view_request(view, REQ_JUMP_COMMIT);
7680 if (request == REQ_JUMP_COMMIT) {
7681 report("Jumping to commits is not supported by the '%s' view", view->name);
7684 } else if (cmd) {
7685 struct view *next = VIEW(REQ_VIEW_PAGER);
7686 const char *argv[SIZEOF_ARG] = { "git" };
7687 int argc = 1;
7689 /* When running random commands, initially show the
7690 * command in the title. However, it maybe later be
7691 * overwritten if a commit line is selected. */
7692 string_ncopy(next->ref, cmd, strlen(cmd));
7694 if (!argv_from_string(argv, &argc, cmd)) {
7695 report("Too many arguments");
7696 } else if (!format_argv(&next->argv, argv, FALSE)) {
7697 report("Argument formatting failed");
7698 } else {
7699 next->dir = NULL;
7700 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7704 request = REQ_NONE;
7705 break;
7707 case REQ_SEARCH:
7708 case REQ_SEARCH_BACK:
7710 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7711 char *search = read_prompt(prompt);
7713 if (search)
7714 string_ncopy(opt_search, search, strlen(search));
7715 else if (*opt_search)
7716 request = request == REQ_SEARCH ?
7717 REQ_FIND_NEXT :
7718 REQ_FIND_PREV;
7719 else
7720 request = REQ_NONE;
7721 break;
7723 default:
7724 break;
7728 quit(0);
7730 return 0;